three.webgpu.nodes.js 1.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183
  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, EventDispatcher, MathUtils, WebGLCoordinateSystem, WebGPUCoordinateSystem, ColorManagement, SRGBTransfer, NoToneMapping, StaticDrawUsage, InterleavedBuffer, InterleavedBufferAttribute, DynamicDrawUsage, NoColorSpace, 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, warnOnce, 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, 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, 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, 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, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } 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. morphChanged = true;
  330. }
  331. }
  332. if ( morphChanged ) return true;
  333. }
  334. // lights
  335. if ( renderObjectData.lights ) {
  336. for ( let i = 0; i < lightsData.length; i ++ ) {
  337. if ( renderObjectData.lights[ i ].map !== lightsData[ i ].map ) {
  338. return false;
  339. }
  340. }
  341. }
  342. // center
  343. if ( renderObjectData.center ) {
  344. if ( renderObjectData.center.equals( object.center ) === false ) {
  345. renderObjectData.center.copy( object.center );
  346. return true;
  347. }
  348. }
  349. // bundle
  350. if ( renderObject.bundle !== null ) {
  351. renderObjectData.version = renderObject.bundle.version;
  352. }
  353. return true;
  354. }
  355. /**
  356. * Returns the lights data for the given material lights.
  357. *
  358. * @param {Array<Light>} materialLights - The material lights.
  359. * @return {Array<Object>} The lights data for the given material lights.
  360. */
  361. getLightsData( materialLights ) {
  362. const lights = [];
  363. for ( const light of materialLights ) {
  364. if ( light.isSpotLight === true && light.map !== null ) {
  365. // only add lights that have a map
  366. lights.push( { map: light.map.version } );
  367. }
  368. }
  369. return lights;
  370. }
  371. /**
  372. * Returns the lights for the given lights node and render ID.
  373. *
  374. * @param {LightsNode} lightsNode - The lights node.
  375. * @param {number} renderId - The render ID.
  376. * @return {Array} The lights for the given lights node and render ID.
  377. */
  378. getLights( lightsNode, renderId ) {
  379. if ( _lightsCache.has( lightsNode ) ) {
  380. const cached = _lightsCache.get( lightsNode );
  381. if ( cached.renderId === renderId ) {
  382. return cached.lightsData;
  383. }
  384. }
  385. const lightsData = this.getLightsData( lightsNode.getLights() );
  386. _lightsCache.set( lightsNode, { renderId, lightsData } );
  387. return lightsData;
  388. }
  389. /**
  390. * Checks if the given render object requires a refresh.
  391. *
  392. * @param {RenderObject} renderObject - The render object.
  393. * @param {NodeFrame} nodeFrame - The current node frame.
  394. * @return {boolean} Whether the given render object requires a refresh or not.
  395. */
  396. needsRefresh( renderObject, nodeFrame ) {
  397. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  398. return true;
  399. const { renderId } = nodeFrame;
  400. if ( this.renderId !== renderId ) {
  401. this.renderId = renderId;
  402. return true;
  403. }
  404. const isStatic = renderObject.object.static === true;
  405. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  406. if ( isStatic || isBundle )
  407. return false;
  408. const lightsData = this.getLights( renderObject.lightsNode, renderId );
  409. const notEqual = this.equals( renderObject, lightsData ) !== true;
  410. return notEqual;
  411. }
  412. }
  413. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  414. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  415. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  416. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  417. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  418. function cyrb53( value, seed = 0 ) {
  419. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  420. if ( value instanceof Array ) {
  421. for ( let i = 0, val; i < value.length; i ++ ) {
  422. val = value[ i ];
  423. h1 = Math.imul( h1 ^ val, 2654435761 );
  424. h2 = Math.imul( h2 ^ val, 1597334677 );
  425. }
  426. } else {
  427. for ( let i = 0, ch; i < value.length; i ++ ) {
  428. ch = value.charCodeAt( i );
  429. h1 = Math.imul( h1 ^ ch, 2654435761 );
  430. h2 = Math.imul( h2 ^ ch, 1597334677 );
  431. }
  432. }
  433. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  434. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  435. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  436. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  437. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  438. }
  439. /**
  440. * Computes a hash for the given string.
  441. *
  442. * @method
  443. * @param {string} str - The string to be hashed.
  444. * @return {number} The hash.
  445. */
  446. const hashString = ( str ) => cyrb53( str );
  447. /**
  448. * Computes a hash for the given array.
  449. *
  450. * @method
  451. * @param {Array<number>} array - The array to be hashed.
  452. * @return {number} The hash.
  453. */
  454. const hashArray = ( array ) => cyrb53( array );
  455. /**
  456. * Computes a hash for the given list of parameters.
  457. *
  458. * @method
  459. * @param {...number} params - A list of parameters.
  460. * @return {number} The hash.
  461. */
  462. const hash$1 = ( ...params ) => cyrb53( params );
  463. /**
  464. * Computes a cache key for the given node.
  465. *
  466. * @method
  467. * @param {Object|Node} object - The object to be hashed.
  468. * @param {boolean} [force=false] - Whether to force a cache key computation or not.
  469. * @return {number} The hash.
  470. */
  471. function getCacheKey$1( object, force = false ) {
  472. const values = [];
  473. if ( object.isNode === true ) {
  474. values.push( object.id );
  475. object = object.getSelf();
  476. }
  477. for ( const { property, childNode } of getNodeChildren( object ) ) {
  478. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  479. }
  480. return cyrb53( values );
  481. }
  482. /**
  483. * This generator function can be used to iterate over the node children
  484. * of the given object.
  485. *
  486. * @generator
  487. * @param {Object} node - The object to be hashed.
  488. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  489. * @yields {Object} A result node holding the property, index (if available) and the child node.
  490. */
  491. function* getNodeChildren( node, toJSON = false ) {
  492. for ( const property in node ) {
  493. // Ignore private properties.
  494. if ( property.startsWith( '_' ) === true ) continue;
  495. const object = node[ property ];
  496. if ( Array.isArray( object ) === true ) {
  497. for ( let i = 0; i < object.length; i ++ ) {
  498. const child = object[ i ];
  499. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  500. yield { property, index: i, childNode: child };
  501. }
  502. }
  503. } else if ( object && object.isNode === true ) {
  504. yield { property, childNode: object };
  505. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  506. for ( const subProperty in object ) {
  507. // Ignore private properties.
  508. if ( subProperty.startsWith( '_' ) === true ) continue;
  509. const child = object[ subProperty ];
  510. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  511. yield { property, index: subProperty, childNode: child };
  512. }
  513. }
  514. }
  515. }
  516. }
  517. const typeFromLength = /*@__PURE__*/ new Map( [
  518. [ 1, 'float' ],
  519. [ 2, 'vec2' ],
  520. [ 3, 'vec3' ],
  521. [ 4, 'vec4' ],
  522. [ 9, 'mat3' ],
  523. [ 16, 'mat4' ]
  524. ] );
  525. const dataFromObject = /*@__PURE__*/ new WeakMap();
  526. /**
  527. * Returns the data type for the given the length.
  528. *
  529. * @method
  530. * @param {number} length - The length.
  531. * @return {string} The data type.
  532. */
  533. function getTypeFromLength( length ) {
  534. return typeFromLength.get( length );
  535. }
  536. /**
  537. * Returns the typed array for the given data type.
  538. *
  539. * @method
  540. * @param {string} type - The data type.
  541. * @return {TypedArray} The typed array.
  542. */
  543. function getTypedArrayFromType( type ) {
  544. // Handle component type for vectors and matrices
  545. if ( /[iu]?vec\d/.test( type ) ) {
  546. // Handle int vectors
  547. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  548. // Handle uint vectors
  549. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  550. // Default to float vectors
  551. return Float32Array;
  552. }
  553. // Handle matrices (always float)
  554. if ( /mat\d/.test( type ) ) return Float32Array;
  555. // Basic types
  556. if ( /float/.test( type ) ) return Float32Array;
  557. if ( /uint/.test( type ) ) return Uint32Array;
  558. if ( /int/.test( type ) ) return Int32Array;
  559. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  560. }
  561. /**
  562. * Returns the length for the given data type.
  563. *
  564. * @method
  565. * @param {string} type - The data type.
  566. * @return {number} The length.
  567. */
  568. function getLengthFromType( type ) {
  569. if ( /float|int|uint/.test( type ) ) return 1;
  570. if ( /vec2/.test( type ) ) return 2;
  571. if ( /vec3/.test( type ) ) return 3;
  572. if ( /vec4/.test( type ) ) return 4;
  573. if ( /mat2/.test( type ) ) return 4;
  574. if ( /mat3/.test( type ) ) return 9;
  575. if ( /mat4/.test( type ) ) return 16;
  576. console.error( 'THREE.TSL: Unsupported type:', type );
  577. }
  578. /**
  579. * Returns the gpu memory length for the given data type.
  580. *
  581. * @method
  582. * @param {string} type - The data type.
  583. * @return {number} The length.
  584. */
  585. function getMemoryLengthFromType( type ) {
  586. if ( /float|int|uint/.test( type ) ) return 1;
  587. if ( /vec2/.test( type ) ) return 2;
  588. if ( /vec3/.test( type ) ) return 3;
  589. if ( /vec4/.test( type ) ) return 4;
  590. if ( /mat2/.test( type ) ) return 4;
  591. if ( /mat3/.test( type ) ) return 12;
  592. if ( /mat4/.test( type ) ) return 16;
  593. console.error( 'THREE.TSL: Unsupported type:', type );
  594. }
  595. /**
  596. * Returns the byte boundary for the given data type.
  597. *
  598. * @method
  599. * @param {string} type - The data type.
  600. * @return {number} The byte boundary.
  601. */
  602. function getByteBoundaryFromType( type ) {
  603. if ( /float|int|uint/.test( type ) ) return 4;
  604. if ( /vec2/.test( type ) ) return 8;
  605. if ( /vec3/.test( type ) ) return 16;
  606. if ( /vec4/.test( type ) ) return 16;
  607. if ( /mat2/.test( type ) ) return 8;
  608. if ( /mat3/.test( type ) ) return 48;
  609. if ( /mat4/.test( type ) ) return 64;
  610. console.error( 'THREE.TSL: Unsupported type:', type );
  611. }
  612. /**
  613. * Returns the data type for the given value.
  614. *
  615. * @method
  616. * @param {any} value - The value.
  617. * @return {?string} The data type.
  618. */
  619. function getValueType( value ) {
  620. if ( value === undefined || value === null ) return null;
  621. const typeOf = typeof value;
  622. if ( value.isNode === true ) {
  623. return 'node';
  624. } else if ( typeOf === 'number' ) {
  625. return 'float';
  626. } else if ( typeOf === 'boolean' ) {
  627. return 'bool';
  628. } else if ( typeOf === 'string' ) {
  629. return 'string';
  630. } else if ( typeOf === 'function' ) {
  631. return 'shader';
  632. } else if ( value.isVector2 === true ) {
  633. return 'vec2';
  634. } else if ( value.isVector3 === true ) {
  635. return 'vec3';
  636. } else if ( value.isVector4 === true ) {
  637. return 'vec4';
  638. } else if ( value.isMatrix2 === true ) {
  639. return 'mat2';
  640. } else if ( value.isMatrix3 === true ) {
  641. return 'mat3';
  642. } else if ( value.isMatrix4 === true ) {
  643. return 'mat4';
  644. } else if ( value.isColor === true ) {
  645. return 'color';
  646. } else if ( value instanceof ArrayBuffer ) {
  647. return 'ArrayBuffer';
  648. }
  649. return null;
  650. }
  651. /**
  652. * Returns the value/object for the given data type and parameters.
  653. *
  654. * @method
  655. * @param {string} type - The given type.
  656. * @param {...any} params - A parameter list.
  657. * @return {any} The value/object.
  658. */
  659. function getValueFromType( type, ...params ) {
  660. const last4 = type ? type.slice( -4 ) : undefined;
  661. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  662. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  663. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  664. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  665. }
  666. if ( type === 'color' ) {
  667. return new Color( ...params );
  668. } else if ( last4 === 'vec2' ) {
  669. return new Vector2( ...params );
  670. } else if ( last4 === 'vec3' ) {
  671. return new Vector3( ...params );
  672. } else if ( last4 === 'vec4' ) {
  673. return new Vector4( ...params );
  674. } else if ( last4 === 'mat2' ) {
  675. return new Matrix2( ...params );
  676. } else if ( last4 === 'mat3' ) {
  677. return new Matrix3( ...params );
  678. } else if ( last4 === 'mat4' ) {
  679. return new Matrix4( ...params );
  680. } else if ( type === 'bool' ) {
  681. return params[ 0 ] || false;
  682. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  683. return params[ 0 ] || 0;
  684. } else if ( type === 'string' ) {
  685. return params[ 0 ] || '';
  686. } else if ( type === 'ArrayBuffer' ) {
  687. return base64ToArrayBuffer( params[ 0 ] );
  688. }
  689. return null;
  690. }
  691. /**
  692. * Gets the object data that can be shared between different rendering steps.
  693. *
  694. * @param {Object} object - The object to get the data for.
  695. * @return {Object} The object data.
  696. */
  697. function getDataFromObject( object ) {
  698. let data = dataFromObject.get( object );
  699. if ( data === undefined ) {
  700. data = {};
  701. dataFromObject.set( object, data );
  702. }
  703. return data;
  704. }
  705. /**
  706. * Converts the given array buffer to a Base64 string.
  707. *
  708. * @method
  709. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  710. * @return {string} The Base64 string.
  711. */
  712. function arrayBufferToBase64( arrayBuffer ) {
  713. let chars = '';
  714. const array = new Uint8Array( arrayBuffer );
  715. for ( let i = 0; i < array.length; i ++ ) {
  716. chars += String.fromCharCode( array[ i ] );
  717. }
  718. return btoa( chars );
  719. }
  720. /**
  721. * Converts the given Base64 string to an array buffer.
  722. *
  723. * @method
  724. * @param {string} base64 - The Base64 string.
  725. * @return {ArrayBuffer} The array buffer.
  726. */
  727. function base64ToArrayBuffer( base64 ) {
  728. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  729. }
  730. var NodeUtils = /*#__PURE__*/Object.freeze({
  731. __proto__: null,
  732. arrayBufferToBase64: arrayBufferToBase64,
  733. base64ToArrayBuffer: base64ToArrayBuffer,
  734. getByteBoundaryFromType: getByteBoundaryFromType,
  735. getCacheKey: getCacheKey$1,
  736. getDataFromObject: getDataFromObject,
  737. getLengthFromType: getLengthFromType,
  738. getMemoryLengthFromType: getMemoryLengthFromType,
  739. getNodeChildren: getNodeChildren,
  740. getTypeFromLength: getTypeFromLength,
  741. getTypedArrayFromType: getTypedArrayFromType,
  742. getValueFromType: getValueFromType,
  743. getValueType: getValueType,
  744. hash: hash$1,
  745. hashArray: hashArray,
  746. hashString: hashString
  747. });
  748. /**
  749. * Possible shader stages.
  750. *
  751. * @property {string} VERTEX The vertex shader stage.
  752. * @property {string} FRAGMENT The fragment shader stage.
  753. */
  754. const NodeShaderStage = {
  755. VERTEX: 'vertex',
  756. FRAGMENT: 'fragment'
  757. };
  758. /**
  759. * Update types of a node.
  760. *
  761. * @property {string} NONE The update method is not executed.
  762. * @property {string} FRAME The update method is executed per frame.
  763. * @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.
  764. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  765. */
  766. const NodeUpdateType = {
  767. NONE: 'none',
  768. FRAME: 'frame',
  769. RENDER: 'render',
  770. OBJECT: 'object'
  771. };
  772. /**
  773. * Data types of a node.
  774. *
  775. * @property {string} BOOLEAN Boolean type.
  776. * @property {string} INTEGER Integer type.
  777. * @property {string} FLOAT Float type.
  778. * @property {string} VECTOR2 Two-dimensional vector type.
  779. * @property {string} VECTOR3 Three-dimensional vector type.
  780. * @property {string} VECTOR4 Four-dimensional vector type.
  781. * @property {string} MATRIX2 2x2 matrix type.
  782. * @property {string} MATRIX3 3x3 matrix type.
  783. * @property {string} MATRIX4 4x4 matrix type.
  784. */
  785. const NodeType = {
  786. BOOLEAN: 'bool',
  787. INTEGER: 'int',
  788. FLOAT: 'float',
  789. VECTOR2: 'vec2',
  790. VECTOR3: 'vec3',
  791. VECTOR4: 'vec4',
  792. MATRIX2: 'mat2',
  793. MATRIX3: 'mat3',
  794. MATRIX4: 'mat4'
  795. };
  796. /**
  797. * Access types of a node. These are relevant for compute and storage usage.
  798. *
  799. * @property {string} READ_ONLY Read-only access
  800. * @property {string} WRITE_ONLY Write-only access.
  801. * @property {string} READ_WRITE Read and write access.
  802. */
  803. const NodeAccess = {
  804. READ_ONLY: 'readOnly',
  805. WRITE_ONLY: 'writeOnly',
  806. READ_WRITE: 'readWrite',
  807. };
  808. const defaultShaderStages = [ 'fragment', 'vertex' ];
  809. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  810. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  811. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  812. const _parentBuildStage = {
  813. analyze: 'setup',
  814. generate: 'analyze'
  815. };
  816. let _nodeId = 0;
  817. /**
  818. * Base class for all nodes.
  819. *
  820. * @augments EventDispatcher
  821. */
  822. class Node extends EventDispatcher {
  823. static get type() {
  824. return 'Node';
  825. }
  826. /**
  827. * Constructs a new node.
  828. *
  829. * @param {?string} nodeType - The node type.
  830. */
  831. constructor( nodeType = null ) {
  832. super();
  833. /**
  834. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  835. *
  836. * @type {?string}
  837. * @default null
  838. */
  839. this.nodeType = nodeType;
  840. /**
  841. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  842. *
  843. * @type {string}
  844. * @default 'none'
  845. */
  846. this.updateType = NodeUpdateType.NONE;
  847. /**
  848. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  849. *
  850. * @type {string}
  851. * @default 'none'
  852. */
  853. this.updateBeforeType = NodeUpdateType.NONE;
  854. /**
  855. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  856. *
  857. * @type {string}
  858. * @default 'none'
  859. */
  860. this.updateAfterType = NodeUpdateType.NONE;
  861. /**
  862. * The UUID of the node.
  863. *
  864. * @type {string}
  865. * @readonly
  866. */
  867. this.uuid = MathUtils.generateUUID();
  868. /**
  869. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  870. *
  871. * @type {number}
  872. * @readonly
  873. * @default 0
  874. */
  875. this.version = 0;
  876. /**
  877. * Whether this node is global or not. This property is relevant for the internal
  878. * node caching system. All nodes which should be declared just once should
  879. * set this flag to `true` (a typical example is {@link AttributeNode}).
  880. *
  881. * @type {boolean}
  882. * @default false
  883. */
  884. this.global = false;
  885. /**
  886. * Create a list of parents for this node during the build process.
  887. *
  888. * @type {boolean}
  889. * @default false
  890. */
  891. this.parents = false;
  892. /**
  893. * This flag can be used for type testing.
  894. *
  895. * @type {boolean}
  896. * @readonly
  897. * @default true
  898. */
  899. this.isNode = true;
  900. // private
  901. /**
  902. * The cache key of this node.
  903. *
  904. * @private
  905. * @type {?number}
  906. * @default null
  907. */
  908. this._cacheKey = null;
  909. /**
  910. * The cache key 's version.
  911. *
  912. * @private
  913. * @type {number}
  914. * @default 0
  915. */
  916. this._cacheKeyVersion = 0;
  917. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  918. }
  919. /**
  920. * Set this property to `true` when the node should be regenerated.
  921. *
  922. * @type {boolean}
  923. * @default false
  924. * @param {boolean} value
  925. */
  926. set needsUpdate( value ) {
  927. if ( value === true ) {
  928. this.version ++;
  929. }
  930. }
  931. /**
  932. * The type of the class. The value is usually the constructor name.
  933. *
  934. * @type {string}
  935. * @readonly
  936. */
  937. get type() {
  938. return this.constructor.type;
  939. }
  940. /**
  941. * Convenient method for defining {@link Node#update}.
  942. *
  943. * @param {Function} callback - The update method.
  944. * @param {string} updateType - The update type.
  945. * @return {Node} A reference to this node.
  946. */
  947. onUpdate( callback, updateType ) {
  948. this.updateType = updateType;
  949. this.update = callback.bind( this.getSelf() );
  950. return this;
  951. }
  952. /**
  953. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  954. * this method automatically sets the update type to `FRAME`.
  955. *
  956. * @param {Function} callback - The update method.
  957. * @return {Node} A reference to this node.
  958. */
  959. onFrameUpdate( callback ) {
  960. return this.onUpdate( callback, NodeUpdateType.FRAME );
  961. }
  962. /**
  963. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  964. * this method automatically sets the update type to `RENDER`.
  965. *
  966. * @param {Function} callback - The update method.
  967. * @return {Node} A reference to this node.
  968. */
  969. onRenderUpdate( callback ) {
  970. return this.onUpdate( callback, NodeUpdateType.RENDER );
  971. }
  972. /**
  973. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  974. * this method automatically sets the update type to `OBJECT`.
  975. *
  976. * @param {Function} callback - The update method.
  977. * @return {Node} A reference to this node.
  978. */
  979. onObjectUpdate( callback ) {
  980. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  981. }
  982. /**
  983. * Convenient method for defining {@link Node#updateReference}.
  984. *
  985. * @param {Function} callback - The update method.
  986. * @return {Node} A reference to this node.
  987. */
  988. onReference( callback ) {
  989. this.updateReference = callback.bind( this.getSelf() );
  990. return this;
  991. }
  992. /**
  993. * The `this` reference might point to a Proxy so this method can be used
  994. * to get the reference to the actual node instance.
  995. *
  996. * @return {Node} A reference to the node.
  997. */
  998. getSelf() {
  999. // Returns non-node object.
  1000. return this.self || this;
  1001. }
  1002. /**
  1003. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  1004. * to such objects based on a given state (e.g. the current node frame or builder).
  1005. *
  1006. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  1007. * @return {any} The updated reference.
  1008. */
  1009. updateReference( /*state*/ ) {
  1010. return this;
  1011. }
  1012. /**
  1013. * By default this method returns the value of the {@link Node#global} flag. This method
  1014. * can be overwritten in derived classes if an analytical way is required to determine the
  1015. * global cache referring to the current shader-stage.
  1016. *
  1017. * @param {NodeBuilder} builder - The current node builder.
  1018. * @return {boolean} Whether this node is global or not.
  1019. */
  1020. isGlobal( /*builder*/ ) {
  1021. return this.global;
  1022. }
  1023. /**
  1024. * Generator function that can be used to iterate over the child nodes.
  1025. *
  1026. * @generator
  1027. * @yields {Node} A child node.
  1028. */
  1029. * getChildren() {
  1030. for ( const { childNode } of getNodeChildren( this ) ) {
  1031. yield childNode;
  1032. }
  1033. }
  1034. /**
  1035. * Calling this method dispatches the `dispose` event. This event can be used
  1036. * to register event listeners for clean up tasks.
  1037. */
  1038. dispose() {
  1039. this.dispatchEvent( { type: 'dispose' } );
  1040. }
  1041. /**
  1042. * Callback for {@link Node#traverse}.
  1043. *
  1044. * @callback traverseCallback
  1045. * @param {Node} node - The current node.
  1046. */
  1047. /**
  1048. * Can be used to traverse through the node's hierarchy.
  1049. *
  1050. * @param {traverseCallback} callback - A callback that is executed per node.
  1051. */
  1052. traverse( callback ) {
  1053. callback( this );
  1054. for ( const childNode of this.getChildren() ) {
  1055. childNode.traverse( callback );
  1056. }
  1057. }
  1058. /**
  1059. * Returns the cache key for this node.
  1060. *
  1061. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1062. * @return {number} The cache key of the node.
  1063. */
  1064. getCacheKey( force = false ) {
  1065. force = force || this.version !== this._cacheKeyVersion;
  1066. if ( force === true || this._cacheKey === null ) {
  1067. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  1068. this._cacheKeyVersion = this.version;
  1069. }
  1070. return this._cacheKey;
  1071. }
  1072. /**
  1073. * Generate a custom cache key for this node.
  1074. *
  1075. * @return {number} The cache key of the node.
  1076. */
  1077. customCacheKey() {
  1078. return 0;
  1079. }
  1080. /**
  1081. * Returns the references to this node which is by default `this`.
  1082. *
  1083. * @return {Node} A reference to this node.
  1084. */
  1085. getScope() {
  1086. return this;
  1087. }
  1088. /**
  1089. * Returns the hash of the node which is used to identify the node. By default it's
  1090. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1091. * depending on their implementation.
  1092. *
  1093. * @param {NodeBuilder} builder - The current node builder.
  1094. * @return {string} The hash.
  1095. */
  1096. getHash( /*builder*/ ) {
  1097. return this.uuid;
  1098. }
  1099. /**
  1100. * Returns the update type of {@link Node#update}.
  1101. *
  1102. * @return {NodeUpdateType} The update type.
  1103. */
  1104. getUpdateType() {
  1105. return this.updateType;
  1106. }
  1107. /**
  1108. * Returns the update type of {@link Node#updateBefore}.
  1109. *
  1110. * @return {NodeUpdateType} The update type.
  1111. */
  1112. getUpdateBeforeType() {
  1113. return this.updateBeforeType;
  1114. }
  1115. /**
  1116. * Returns the update type of {@link Node#updateAfter}.
  1117. *
  1118. * @return {NodeUpdateType} The update type.
  1119. */
  1120. getUpdateAfterType() {
  1121. return this.updateAfterType;
  1122. }
  1123. /**
  1124. * Certain types are composed of multiple elements. For example a `vec3`
  1125. * is composed of three `float` values. This method returns the type of
  1126. * these elements.
  1127. *
  1128. * @param {NodeBuilder} builder - The current node builder.
  1129. * @return {string} The type of the node.
  1130. */
  1131. getElementType( builder ) {
  1132. const type = this.getNodeType( builder );
  1133. const elementType = builder.getElementType( type );
  1134. return elementType;
  1135. }
  1136. /**
  1137. * Returns the node member type for the given name.
  1138. *
  1139. * @param {NodeBuilder} builder - The current node builder.
  1140. * @param {string} name - The name of the member.
  1141. * @return {string} The type of the node.
  1142. */
  1143. getMemberType( /*builder, name*/ ) {
  1144. return 'void';
  1145. }
  1146. /**
  1147. * Returns the node's type.
  1148. *
  1149. * @param {NodeBuilder} builder - The current node builder.
  1150. * @return {string} The type of the node.
  1151. */
  1152. getNodeType( builder ) {
  1153. const nodeProperties = builder.getNodeProperties( this );
  1154. if ( nodeProperties.outputNode ) {
  1155. return nodeProperties.outputNode.getNodeType( builder );
  1156. }
  1157. return this.nodeType;
  1158. }
  1159. /**
  1160. * This method is used during the build process of a node and ensures
  1161. * equal nodes are not built multiple times but just once. For example if
  1162. * `attribute( 'uv' )` is used multiple times by the user, the build
  1163. * process makes sure to process just the first node.
  1164. *
  1165. * @param {NodeBuilder} builder - The current node builder.
  1166. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1167. */
  1168. getShared( builder ) {
  1169. const hash = this.getHash( builder );
  1170. const nodeFromHash = builder.getNodeFromHash( hash );
  1171. return nodeFromHash || this;
  1172. }
  1173. /**
  1174. * Returns the number of elements in the node array.
  1175. *
  1176. * @param {NodeBuilder} builder - The current node builder.
  1177. * @return {?number} The number of elements in the node array.
  1178. */
  1179. getArrayCount( /*builder*/ ) {
  1180. return null;
  1181. }
  1182. /**
  1183. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1184. * This method is often overwritten in derived modules to prepare the node which is used as a node's output/result.
  1185. * If an output node is prepared, then it must be returned in the `return` statement of the derived module's setup function.
  1186. *
  1187. * @param {NodeBuilder} builder - The current node builder.
  1188. * @return {?Node} The output node.
  1189. */
  1190. setup( builder ) {
  1191. const nodeProperties = builder.getNodeProperties( this );
  1192. let index = 0;
  1193. for ( const childNode of this.getChildren() ) {
  1194. nodeProperties[ 'node' + index ++ ] = childNode;
  1195. }
  1196. // return a outputNode if exists or null
  1197. return nodeProperties.outputNode || null;
  1198. }
  1199. /**
  1200. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1201. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1202. *
  1203. * @param {NodeBuilder} builder - The current node builder.
  1204. * @param {?Node} output - The target output node.
  1205. */
  1206. analyze( builder, output = null ) {
  1207. const usageCount = builder.increaseUsage( this );
  1208. if ( this.parents === true ) {
  1209. const nodeData = builder.getDataFromNode( this, 'any' );
  1210. nodeData.stages = nodeData.stages || {};
  1211. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1212. nodeData.stages[ builder.shaderStage ].push( output );
  1213. }
  1214. if ( usageCount === 1 ) {
  1215. // node flow children
  1216. const nodeProperties = builder.getNodeProperties( this );
  1217. for ( const childNode of Object.values( nodeProperties ) ) {
  1218. if ( childNode && childNode.isNode === true ) {
  1219. childNode.build( builder, this );
  1220. }
  1221. }
  1222. }
  1223. }
  1224. /**
  1225. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1226. * This state builds the output node and returns the resulting shader string.
  1227. *
  1228. * @param {NodeBuilder} builder - The current node builder.
  1229. * @param {?string} output - Can be used to define the output type.
  1230. * @return {?string} The generated shader string.
  1231. */
  1232. generate( builder, output ) {
  1233. const { outputNode } = builder.getNodeProperties( this );
  1234. if ( outputNode && outputNode.isNode === true ) {
  1235. return outputNode.build( builder, output );
  1236. }
  1237. }
  1238. /**
  1239. * The method can be implemented to update the node's internal state before it is used to render an object.
  1240. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1241. *
  1242. * @abstract
  1243. * @param {NodeFrame} frame - A reference to the current node frame.
  1244. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1245. */
  1246. updateBefore( /*frame*/ ) {
  1247. console.warn( 'Abstract function.' );
  1248. }
  1249. /**
  1250. * The method can be implemented to update the node's internal state after it was used to render an object.
  1251. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1252. *
  1253. * @abstract
  1254. * @param {NodeFrame} frame - A reference to the current node frame.
  1255. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1256. */
  1257. updateAfter( /*frame*/ ) {
  1258. console.warn( 'Abstract function.' );
  1259. }
  1260. /**
  1261. * The method can be implemented to update the node's internal state when it is used to render an object.
  1262. * The {@link Node#updateType} property defines how often the update is executed.
  1263. *
  1264. * @abstract
  1265. * @param {NodeFrame} frame - A reference to the current node frame.
  1266. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1267. */
  1268. update( /*frame*/ ) {
  1269. console.warn( 'Abstract function.' );
  1270. }
  1271. /**
  1272. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1273. * - **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.
  1274. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1275. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1276. *
  1277. * @param {NodeBuilder} builder - The current node builder.
  1278. * @param {string|Node|null} [output=null] - Can be used to define the output type.
  1279. * @return {Node|string|null} The result of the build process, depending on the build stage.
  1280. */
  1281. build( builder, output = null ) {
  1282. const refNode = this.getShared( builder );
  1283. if ( this !== refNode ) {
  1284. return refNode.build( builder, output );
  1285. }
  1286. //
  1287. const nodeData = builder.getDataFromNode( this );
  1288. nodeData.buildStages = nodeData.buildStages || {};
  1289. nodeData.buildStages[ builder.buildStage ] = true;
  1290. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1291. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1292. // force parent build stage (setup or analyze)
  1293. const previousBuildStage = builder.getBuildStage();
  1294. builder.setBuildStage( parentBuildStage );
  1295. this.build( builder );
  1296. builder.setBuildStage( previousBuildStage );
  1297. }
  1298. //
  1299. builder.addNode( this );
  1300. builder.addChain( this );
  1301. /* Build stages expected results:
  1302. - "setup" -> Node
  1303. - "analyze" -> null
  1304. - "generate" -> String
  1305. */
  1306. let result = null;
  1307. const buildStage = builder.getBuildStage();
  1308. if ( buildStage === 'setup' ) {
  1309. this.updateReference( builder );
  1310. const properties = builder.getNodeProperties( this );
  1311. if ( properties.initialized !== true ) {
  1312. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1313. properties.initialized = true;
  1314. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1315. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1316. // !! no outputNode !!
  1317. //outputNode = builder.stack;
  1318. }*/
  1319. for ( const childNode of Object.values( properties ) ) {
  1320. if ( childNode && childNode.isNode === true ) {
  1321. if ( childNode.parents === true ) {
  1322. const childProperties = builder.getNodeProperties( childNode );
  1323. childProperties.parents = childProperties.parents || [];
  1324. childProperties.parents.push( this );
  1325. }
  1326. childNode.build( builder );
  1327. }
  1328. }
  1329. }
  1330. result = properties.outputNode;
  1331. } else if ( buildStage === 'analyze' ) {
  1332. this.analyze( builder, output );
  1333. } else if ( buildStage === 'generate' ) {
  1334. const isGenerateOnce = this.generate.length === 1;
  1335. if ( isGenerateOnce ) {
  1336. const type = this.getNodeType( builder );
  1337. const nodeData = builder.getDataFromNode( this );
  1338. result = nodeData.snippet;
  1339. if ( result === undefined ) {
  1340. if ( nodeData.generated === undefined ) {
  1341. nodeData.generated = true;
  1342. result = this.generate( builder ) || '';
  1343. nodeData.snippet = result;
  1344. } else {
  1345. console.warn( 'THREE.Node: Recursion detected.', this );
  1346. result = '/* Recursion detected. */';
  1347. }
  1348. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1349. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1350. }
  1351. result = builder.format( result, type, output );
  1352. } else {
  1353. result = this.generate( builder, output ) || '';
  1354. }
  1355. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1356. // if no snippet is generated, return a default value
  1357. console.error( `THREE.TSL: Invalid generated code, expected a "${ output }".` );
  1358. result = builder.generateConst( output );
  1359. }
  1360. }
  1361. builder.removeChain( this );
  1362. builder.addSequentialNode( this );
  1363. return result;
  1364. }
  1365. /**
  1366. * Returns the child nodes as a JSON object.
  1367. *
  1368. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1369. */
  1370. getSerializeChildren() {
  1371. return getNodeChildren( this );
  1372. }
  1373. /**
  1374. * Serializes the node to JSON.
  1375. *
  1376. * @param {Object} json - The output JSON object.
  1377. */
  1378. serialize( json ) {
  1379. const nodeChildren = this.getSerializeChildren();
  1380. const inputNodes = {};
  1381. for ( const { property, index, childNode } of nodeChildren ) {
  1382. if ( index !== undefined ) {
  1383. if ( inputNodes[ property ] === undefined ) {
  1384. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1385. }
  1386. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1387. } else {
  1388. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1389. }
  1390. }
  1391. if ( Object.keys( inputNodes ).length > 0 ) {
  1392. json.inputNodes = inputNodes;
  1393. }
  1394. }
  1395. /**
  1396. * Deserializes the node from the given JSON.
  1397. *
  1398. * @param {Object} json - The JSON object.
  1399. */
  1400. deserialize( json ) {
  1401. if ( json.inputNodes !== undefined ) {
  1402. const nodes = json.meta.nodes;
  1403. for ( const property in json.inputNodes ) {
  1404. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1405. const inputArray = [];
  1406. for ( const uuid of json.inputNodes[ property ] ) {
  1407. inputArray.push( nodes[ uuid ] );
  1408. }
  1409. this[ property ] = inputArray;
  1410. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1411. const inputObject = {};
  1412. for ( const subProperty in json.inputNodes[ property ] ) {
  1413. const uuid = json.inputNodes[ property ][ subProperty ];
  1414. inputObject[ subProperty ] = nodes[ uuid ];
  1415. }
  1416. this[ property ] = inputObject;
  1417. } else {
  1418. const uuid = json.inputNodes[ property ];
  1419. this[ property ] = nodes[ uuid ];
  1420. }
  1421. }
  1422. }
  1423. }
  1424. /**
  1425. * Serializes the node into the three.js JSON Object/Scene format.
  1426. *
  1427. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1428. * @return {Object} The serialized node.
  1429. */
  1430. toJSON( meta ) {
  1431. const { uuid, type } = this;
  1432. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1433. if ( isRoot ) {
  1434. meta = {
  1435. textures: {},
  1436. images: {},
  1437. nodes: {}
  1438. };
  1439. }
  1440. // serialize
  1441. let data = meta.nodes[ uuid ];
  1442. if ( data === undefined ) {
  1443. data = {
  1444. uuid,
  1445. type,
  1446. meta,
  1447. metadata: {
  1448. version: 4.7,
  1449. type: 'Node',
  1450. generator: 'Node.toJSON'
  1451. }
  1452. };
  1453. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1454. this.serialize( data );
  1455. delete data.meta;
  1456. }
  1457. // TODO: Copied from Object3D.toJSON
  1458. function extractFromCache( cache ) {
  1459. const values = [];
  1460. for ( const key in cache ) {
  1461. const data = cache[ key ];
  1462. delete data.metadata;
  1463. values.push( data );
  1464. }
  1465. return values;
  1466. }
  1467. if ( isRoot ) {
  1468. const textures = extractFromCache( meta.textures );
  1469. const images = extractFromCache( meta.images );
  1470. const nodes = extractFromCache( meta.nodes );
  1471. if ( textures.length > 0 ) data.textures = textures;
  1472. if ( images.length > 0 ) data.images = images;
  1473. if ( nodes.length > 0 ) data.nodes = nodes;
  1474. }
  1475. return data;
  1476. }
  1477. }
  1478. /**
  1479. * Base class for representing element access on an array-like
  1480. * node data structures.
  1481. *
  1482. * @augments Node
  1483. */
  1484. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1485. static get type() {
  1486. return 'ArrayElementNode';
  1487. }
  1488. /**
  1489. * Constructs an array element node.
  1490. *
  1491. * @param {Node} node - The array-like node.
  1492. * @param {Node} indexNode - The index node that defines the element access.
  1493. */
  1494. constructor( node, indexNode ) {
  1495. super();
  1496. /**
  1497. * The array-like node.
  1498. *
  1499. * @type {Node}
  1500. */
  1501. this.node = node;
  1502. /**
  1503. * The index node that defines the element access.
  1504. *
  1505. * @type {Node}
  1506. */
  1507. this.indexNode = indexNode;
  1508. /**
  1509. * This flag can be used for type testing.
  1510. *
  1511. * @type {boolean}
  1512. * @readonly
  1513. * @default true
  1514. */
  1515. this.isArrayElementNode = true;
  1516. }
  1517. /**
  1518. * This method is overwritten since the node type is inferred from the array-like node.
  1519. *
  1520. * @param {NodeBuilder} builder - The current node builder.
  1521. * @return {string} The node type.
  1522. */
  1523. getNodeType( builder ) {
  1524. return this.node.getElementType( builder );
  1525. }
  1526. generate( builder ) {
  1527. const indexType = this.indexNode.getNodeType( builder );
  1528. const nodeSnippet = this.node.build( builder );
  1529. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1530. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1531. }
  1532. }
  1533. /**
  1534. * This module is part of the TSL core and usually not used in app level code.
  1535. * It represents a convert operation during the shader generation process
  1536. * meaning it converts the data type of a node to a target data type.
  1537. *
  1538. * @augments Node
  1539. */
  1540. class ConvertNode extends Node {
  1541. static get type() {
  1542. return 'ConvertNode';
  1543. }
  1544. /**
  1545. * Constructs a new convert node.
  1546. *
  1547. * @param {Node} node - The node which type should be converted.
  1548. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1549. */
  1550. constructor( node, convertTo ) {
  1551. super();
  1552. /**
  1553. * The node which type should be converted.
  1554. *
  1555. * @type {Node}
  1556. */
  1557. this.node = node;
  1558. /**
  1559. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1560. *
  1561. * @type {string}
  1562. */
  1563. this.convertTo = convertTo;
  1564. }
  1565. /**
  1566. * This method is overwritten since the implementation tries to infer the best
  1567. * matching type from the {@link ConvertNode#convertTo} property.
  1568. *
  1569. * @param {NodeBuilder} builder - The current node builder.
  1570. * @return {string} The node type.
  1571. */
  1572. getNodeType( builder ) {
  1573. const requestType = this.node.getNodeType( builder );
  1574. let convertTo = null;
  1575. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1576. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1577. convertTo = overloadingType;
  1578. }
  1579. }
  1580. return convertTo;
  1581. }
  1582. serialize( data ) {
  1583. super.serialize( data );
  1584. data.convertTo = this.convertTo;
  1585. }
  1586. deserialize( data ) {
  1587. super.deserialize( data );
  1588. this.convertTo = data.convertTo;
  1589. }
  1590. generate( builder, output ) {
  1591. const node = this.node;
  1592. const type = this.getNodeType( builder );
  1593. const snippet = node.build( builder, type );
  1594. return builder.format( snippet, type, output );
  1595. }
  1596. }
  1597. /**
  1598. * This module uses cache management to create temporary variables
  1599. * if the node is used more than once to prevent duplicate calculations.
  1600. *
  1601. * The class acts as a base class for many other nodes types.
  1602. *
  1603. * @augments Node
  1604. */
  1605. class TempNode extends Node {
  1606. static get type() {
  1607. return 'TempNode';
  1608. }
  1609. /**
  1610. * Constructs a temp node.
  1611. *
  1612. * @param {?string} nodeType - The node type.
  1613. */
  1614. constructor( nodeType = null ) {
  1615. super( nodeType );
  1616. /**
  1617. * This flag can be used for type testing.
  1618. *
  1619. * @type {boolean}
  1620. * @readonly
  1621. * @default true
  1622. */
  1623. this.isTempNode = true;
  1624. }
  1625. /**
  1626. * Whether this node is used more than once in context of other nodes.
  1627. *
  1628. * @param {NodeBuilder} builder - The node builder.
  1629. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1630. */
  1631. hasDependencies( builder ) {
  1632. return builder.getDataFromNode( this ).usageCount > 1;
  1633. }
  1634. build( builder, output ) {
  1635. const buildStage = builder.getBuildStage();
  1636. if ( buildStage === 'generate' ) {
  1637. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1638. const nodeData = builder.getDataFromNode( this );
  1639. if ( nodeData.propertyName !== undefined ) {
  1640. return builder.format( nodeData.propertyName, type, output );
  1641. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1642. const snippet = super.build( builder, type );
  1643. const nodeVar = builder.getVarFromNode( this, null, type );
  1644. const propertyName = builder.getPropertyName( nodeVar );
  1645. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1646. nodeData.snippet = snippet;
  1647. nodeData.propertyName = propertyName;
  1648. return builder.format( nodeData.propertyName, type, output );
  1649. }
  1650. }
  1651. return super.build( builder, output );
  1652. }
  1653. }
  1654. /**
  1655. * This module is part of the TSL core and usually not used in app level code.
  1656. * It represents a join operation during the shader generation process.
  1657. * For example in can compose/join two single floats into a `vec2` type.
  1658. *
  1659. * @augments TempNode
  1660. */
  1661. class JoinNode extends TempNode {
  1662. static get type() {
  1663. return 'JoinNode';
  1664. }
  1665. /**
  1666. * Constructs a new join node.
  1667. *
  1668. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1669. * @param {?string} [nodeType=null] - The node type.
  1670. */
  1671. constructor( nodes = [], nodeType = null ) {
  1672. super( nodeType );
  1673. /**
  1674. * An array of nodes that should be joined.
  1675. *
  1676. * @type {Array<Node>}
  1677. */
  1678. this.nodes = nodes;
  1679. }
  1680. /**
  1681. * This method is overwritten since the node type must be inferred from the
  1682. * joined data length if not explicitly defined.
  1683. *
  1684. * @param {NodeBuilder} builder - The current node builder.
  1685. * @return {string} The node type.
  1686. */
  1687. getNodeType( builder ) {
  1688. if ( this.nodeType !== null ) {
  1689. return builder.getVectorType( this.nodeType );
  1690. }
  1691. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1692. }
  1693. generate( builder, output ) {
  1694. const type = this.getNodeType( builder );
  1695. const maxLength = builder.getTypeLength( type );
  1696. const nodes = this.nodes;
  1697. const primitiveType = builder.getComponentType( type );
  1698. const snippetValues = [];
  1699. let length = 0;
  1700. for ( const input of nodes ) {
  1701. if ( length >= maxLength ) {
  1702. console.error( `THREE.TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1703. break;
  1704. }
  1705. let inputType = input.getNodeType( builder );
  1706. let inputTypeLength = builder.getTypeLength( inputType );
  1707. let inputSnippet;
  1708. if ( length + inputTypeLength > maxLength ) {
  1709. console.error( `THREE.TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1710. inputTypeLength = maxLength - length;
  1711. inputType = builder.getTypeFromLength( inputTypeLength );
  1712. }
  1713. length += inputTypeLength;
  1714. inputSnippet = input.build( builder, inputType );
  1715. const inputPrimitiveType = builder.getComponentType( inputType );
  1716. if ( inputPrimitiveType !== primitiveType ) {
  1717. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1718. }
  1719. snippetValues.push( inputSnippet );
  1720. }
  1721. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1722. return builder.format( snippet, type, output );
  1723. }
  1724. }
  1725. const _stringVectorComponents = vectorComponents.join( '' );
  1726. /**
  1727. * This module is part of the TSL core and usually not used in app level code.
  1728. * `SplitNode` represents a property access operation which means it is
  1729. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1730. * For example:
  1731. * ```js
  1732. * const redValue = color.r;
  1733. * ```
  1734. *
  1735. * @augments Node
  1736. */
  1737. class SplitNode extends Node {
  1738. static get type() {
  1739. return 'SplitNode';
  1740. }
  1741. /**
  1742. * Constructs a new split node.
  1743. *
  1744. * @param {Node} node - The node that should be accessed.
  1745. * @param {string} [components='x'] - The components that should be accessed.
  1746. */
  1747. constructor( node, components = 'x' ) {
  1748. super();
  1749. /**
  1750. * The node that should be accessed.
  1751. *
  1752. * @type {Node}
  1753. */
  1754. this.node = node;
  1755. /**
  1756. * The components that should be accessed.
  1757. *
  1758. * @type {string}
  1759. */
  1760. this.components = components;
  1761. /**
  1762. * This flag can be used for type testing.
  1763. *
  1764. * @type {boolean}
  1765. * @readonly
  1766. * @default true
  1767. */
  1768. this.isSplitNode = true;
  1769. }
  1770. /**
  1771. * Returns the vector length which is computed based on the requested components.
  1772. *
  1773. * @return {number} The vector length.
  1774. */
  1775. getVectorLength() {
  1776. let vectorLength = this.components.length;
  1777. for ( const c of this.components ) {
  1778. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1779. }
  1780. return vectorLength;
  1781. }
  1782. /**
  1783. * Returns the component type of the node's type.
  1784. *
  1785. * @param {NodeBuilder} builder - The current node builder.
  1786. * @return {string} The component type.
  1787. */
  1788. getComponentType( builder ) {
  1789. return builder.getComponentType( this.node.getNodeType( builder ) );
  1790. }
  1791. /**
  1792. * This method is overwritten since the node type is inferred from requested components.
  1793. *
  1794. * @param {NodeBuilder} builder - The current node builder.
  1795. * @return {string} The node type.
  1796. */
  1797. getNodeType( builder ) {
  1798. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1799. }
  1800. generate( builder, output ) {
  1801. const node = this.node;
  1802. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1803. let snippet = null;
  1804. if ( nodeTypeLength > 1 ) {
  1805. let type = null;
  1806. const componentsLength = this.getVectorLength();
  1807. if ( componentsLength >= nodeTypeLength ) {
  1808. // needed expand the input node
  1809. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1810. }
  1811. const nodeSnippet = node.build( builder, type );
  1812. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1813. // unnecessary swizzle
  1814. snippet = builder.format( nodeSnippet, type, output );
  1815. } else {
  1816. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1817. }
  1818. } else {
  1819. // ignore .components if .node returns float/integer
  1820. snippet = node.build( builder, output );
  1821. }
  1822. return snippet;
  1823. }
  1824. serialize( data ) {
  1825. super.serialize( data );
  1826. data.components = this.components;
  1827. }
  1828. deserialize( data ) {
  1829. super.deserialize( data );
  1830. this.components = data.components;
  1831. }
  1832. }
  1833. /**
  1834. * This module is part of the TSL core and usually not used in app level code.
  1835. * `SetNode` represents a set operation which means it is used to implement any
  1836. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1837. * For example:
  1838. * ```js
  1839. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1840. * ```
  1841. *
  1842. * @augments TempNode
  1843. */
  1844. class SetNode extends TempNode {
  1845. static get type() {
  1846. return 'SetNode';
  1847. }
  1848. /**
  1849. * Constructs a new set node.
  1850. *
  1851. * @param {Node} sourceNode - The node that should be updated.
  1852. * @param {string} components - The components that should be updated.
  1853. * @param {Node} targetNode - The value node.
  1854. */
  1855. constructor( sourceNode, components, targetNode ) {
  1856. super();
  1857. /**
  1858. * The node that should be updated.
  1859. *
  1860. * @type {Node}
  1861. */
  1862. this.sourceNode = sourceNode;
  1863. /**
  1864. * The components that should be updated.
  1865. *
  1866. * @type {string}
  1867. */
  1868. this.components = components;
  1869. /**
  1870. * The value node.
  1871. *
  1872. * @type {Node}
  1873. */
  1874. this.targetNode = targetNode;
  1875. }
  1876. /**
  1877. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1878. *
  1879. * @param {NodeBuilder} builder - The current node builder.
  1880. * @return {string} The node type.
  1881. */
  1882. getNodeType( builder ) {
  1883. return this.sourceNode.getNodeType( builder );
  1884. }
  1885. generate( builder ) {
  1886. const { sourceNode, components, targetNode } = this;
  1887. const sourceType = this.getNodeType( builder );
  1888. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1889. const targetType = builder.getTypeFromLength( components.length, componentType );
  1890. const targetSnippet = targetNode.build( builder, targetType );
  1891. const sourceSnippet = sourceNode.build( builder, sourceType );
  1892. const length = builder.getTypeLength( sourceType );
  1893. const snippetValues = [];
  1894. for ( let i = 0; i < length; i ++ ) {
  1895. const component = vectorComponents[ i ];
  1896. if ( component === components[ 0 ] ) {
  1897. snippetValues.push( targetSnippet );
  1898. i += components.length - 1;
  1899. } else {
  1900. snippetValues.push( sourceSnippet + '.' + component );
  1901. }
  1902. }
  1903. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1904. }
  1905. }
  1906. /**
  1907. * This module is part of the TSL core and usually not used in app level code.
  1908. * It represents a flip operation during the shader generation process
  1909. * meaning it flips normalized values with the following formula:
  1910. * ```
  1911. * x = 1 - x;
  1912. * ```
  1913. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1914. * `flipSTPQ()` method invocations on node objects. For example:
  1915. * ```js
  1916. * uvNode = uvNode.flipY();
  1917. * ```
  1918. *
  1919. * @augments TempNode
  1920. */
  1921. class FlipNode extends TempNode {
  1922. static get type() {
  1923. return 'FlipNode';
  1924. }
  1925. /**
  1926. * Constructs a new flip node.
  1927. *
  1928. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1929. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1930. */
  1931. constructor( sourceNode, components ) {
  1932. super();
  1933. /**
  1934. * The node which component(s) should be flipped.
  1935. *
  1936. * @type {Node}
  1937. */
  1938. this.sourceNode = sourceNode;
  1939. /**
  1940. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1941. *
  1942. * @type {string}
  1943. */
  1944. this.components = components;
  1945. }
  1946. /**
  1947. * This method is overwritten since the node type is inferred from the source node.
  1948. *
  1949. * @param {NodeBuilder} builder - The current node builder.
  1950. * @return {string} The node type.
  1951. */
  1952. getNodeType( builder ) {
  1953. return this.sourceNode.getNodeType( builder );
  1954. }
  1955. generate( builder ) {
  1956. const { components, sourceNode } = this;
  1957. const sourceType = this.getNodeType( builder );
  1958. const sourceSnippet = sourceNode.build( builder );
  1959. const sourceCache = builder.getVarFromNode( this );
  1960. const sourceProperty = builder.getPropertyName( sourceCache );
  1961. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1962. const length = builder.getTypeLength( sourceType );
  1963. const snippetValues = [];
  1964. let componentIndex = 0;
  1965. for ( let i = 0; i < length; i ++ ) {
  1966. const component = vectorComponents[ i ];
  1967. if ( component === components[ componentIndex ] ) {
  1968. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1969. componentIndex ++;
  1970. } else {
  1971. snippetValues.push( sourceProperty + '.' + component );
  1972. }
  1973. }
  1974. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1975. }
  1976. }
  1977. /**
  1978. * Base class for representing data input nodes.
  1979. *
  1980. * @augments Node
  1981. */
  1982. class InputNode extends Node {
  1983. static get type() {
  1984. return 'InputNode';
  1985. }
  1986. /**
  1987. * Constructs a new input node.
  1988. *
  1989. * @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).
  1990. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1991. */
  1992. constructor( value, nodeType = null ) {
  1993. super( nodeType );
  1994. /**
  1995. * This flag can be used for type testing.
  1996. *
  1997. * @type {boolean}
  1998. * @readonly
  1999. * @default true
  2000. */
  2001. this.isInputNode = true;
  2002. /**
  2003. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2004. *
  2005. * @type {any}
  2006. */
  2007. this.value = value;
  2008. /**
  2009. * The precision of the value in the shader.
  2010. *
  2011. * @type {?('low'|'medium'|'high')}
  2012. * @default null
  2013. */
  2014. this.precision = null;
  2015. }
  2016. getNodeType( /*builder*/ ) {
  2017. if ( this.nodeType === null ) {
  2018. return getValueType( this.value );
  2019. }
  2020. return this.nodeType;
  2021. }
  2022. /**
  2023. * Returns the input type of the node which is by default the node type. Derived modules
  2024. * might overwrite this method and use a fixed type or compute one analytically.
  2025. *
  2026. * A typical example for different input and node types are textures. The input type of a
  2027. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2028. *
  2029. * @param {NodeBuilder} builder - The current node builder.
  2030. * @return {string} The input type.
  2031. */
  2032. getInputType( builder ) {
  2033. return this.getNodeType( builder );
  2034. }
  2035. /**
  2036. * Sets the precision to the given value. The method can be
  2037. * overwritten in derived classes if the final precision must be computed
  2038. * analytically.
  2039. *
  2040. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2041. * @return {InputNode} A reference to this node.
  2042. */
  2043. setPrecision( precision ) {
  2044. this.precision = precision;
  2045. return this;
  2046. }
  2047. serialize( data ) {
  2048. super.serialize( data );
  2049. data.value = this.value;
  2050. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2051. data.valueType = getValueType( this.value );
  2052. data.nodeType = this.nodeType;
  2053. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2054. data.precision = this.precision;
  2055. }
  2056. deserialize( data ) {
  2057. super.deserialize( data );
  2058. this.nodeType = data.nodeType;
  2059. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2060. this.precision = data.precision || null;
  2061. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2062. }
  2063. generate( /*builder, output*/ ) {
  2064. console.warn( 'Abstract function.' );
  2065. }
  2066. }
  2067. const _regNum = /float|u?int/;
  2068. /**
  2069. * Class for representing a constant value in the shader.
  2070. *
  2071. * @augments InputNode
  2072. */
  2073. class ConstNode extends InputNode {
  2074. static get type() {
  2075. return 'ConstNode';
  2076. }
  2077. /**
  2078. * Constructs a new input node.
  2079. *
  2080. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2081. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2082. */
  2083. constructor( value, nodeType = null ) {
  2084. super( value, nodeType );
  2085. /**
  2086. * This flag can be used for type testing.
  2087. *
  2088. * @type {boolean}
  2089. * @readonly
  2090. * @default true
  2091. */
  2092. this.isConstNode = true;
  2093. }
  2094. /**
  2095. * Generates the shader string of the value with the current node builder.
  2096. *
  2097. * @param {NodeBuilder} builder - The current node builder.
  2098. * @return {string} The generated value as a shader string.
  2099. */
  2100. generateConst( builder ) {
  2101. return builder.generateConst( this.getNodeType( builder ), this.value );
  2102. }
  2103. generate( builder, output ) {
  2104. const type = this.getNodeType( builder );
  2105. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2106. return builder.generateConst( output, this.value );
  2107. }
  2108. return builder.format( this.generateConst( builder ), type, output );
  2109. }
  2110. }
  2111. /**
  2112. * Base class for representing member access on an object-like
  2113. * node data structures.
  2114. *
  2115. * @augments Node
  2116. */
  2117. class MemberNode extends Node {
  2118. static get type() {
  2119. return 'MemberNode';
  2120. }
  2121. /**
  2122. * Constructs an array element node.
  2123. *
  2124. * @param {Node} node - The array-like node.
  2125. * @param {string} property - The property name.
  2126. */
  2127. constructor( node, property ) {
  2128. super();
  2129. /**
  2130. * The array-like node.
  2131. *
  2132. * @type {Node}
  2133. */
  2134. this.node = node;
  2135. /**
  2136. * The property name.
  2137. *
  2138. * @type {Node}
  2139. */
  2140. this.property = property;
  2141. /**
  2142. * This flag can be used for type testing.
  2143. *
  2144. * @type {boolean}
  2145. * @readonly
  2146. * @default true
  2147. */
  2148. this.isMemberNode = true;
  2149. }
  2150. getNodeType( builder ) {
  2151. return this.node.getMemberType( builder, this.property );
  2152. }
  2153. generate( builder ) {
  2154. const propertyName = this.node.build( builder );
  2155. return propertyName + '.' + this.property;
  2156. }
  2157. }
  2158. let currentStack = null;
  2159. const NodeElements = new Map();
  2160. function addMethodChaining( name, nodeElement ) {
  2161. if ( NodeElements.has( name ) ) {
  2162. console.warn( `THREE.TSL: Redefinition of method chaining '${ name }'.` );
  2163. return;
  2164. }
  2165. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2166. NodeElements.set( name, nodeElement );
  2167. }
  2168. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2169. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2170. const shaderNodeHandler = {
  2171. setup( NodeClosure, params ) {
  2172. const inputs = params.shift();
  2173. return NodeClosure( nodeObjects( inputs ), ...params );
  2174. },
  2175. get( node, prop, nodeObj ) {
  2176. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2177. if ( node.isStackNode !== true && prop === 'assign' ) {
  2178. return ( ...params ) => {
  2179. currentStack.assign( nodeObj, ...params );
  2180. return nodeObj;
  2181. };
  2182. } else if ( NodeElements.has( prop ) ) {
  2183. const nodeElement = NodeElements.get( prop );
  2184. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  2185. } else if ( prop === 'toVarIntent' ) {
  2186. return () => nodeObj;
  2187. } else if ( prop === 'self' ) {
  2188. return node;
  2189. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  2190. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  2191. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  2192. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  2193. // accessing properties ( swizzle )
  2194. prop = parseSwizzle( prop );
  2195. return nodeObject( new SplitNode( nodeObj, prop ) );
  2196. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2197. // set properties ( swizzle ) and sort to xyzw sequence
  2198. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  2199. return ( value ) => nodeObject( new SetNode( node, prop, nodeObject( value ) ) );
  2200. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2201. // set properties ( swizzle ) and sort to xyzw sequence
  2202. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  2203. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  2204. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  2205. // accessing property
  2206. if ( prop === 'width' ) prop = 'x';
  2207. else if ( prop === 'height' ) prop = 'y';
  2208. else if ( prop === 'depth' ) prop = 'z';
  2209. return nodeObject( new SplitNode( node, prop ) );
  2210. } else if ( /^\d+$/.test( prop ) === true ) {
  2211. // accessing array
  2212. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  2213. } else if ( /^get$/.test( prop ) === true ) {
  2214. // accessing properties
  2215. return ( value ) => nodeObject( new MemberNode( nodeObj, value ) );
  2216. }
  2217. }
  2218. return Reflect.get( node, prop, nodeObj );
  2219. },
  2220. set( node, prop, value, nodeObj ) {
  2221. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2222. // setting properties
  2223. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  2224. nodeObj[ prop ].assign( value );
  2225. return true;
  2226. }
  2227. }
  2228. return Reflect.set( node, prop, value, nodeObj );
  2229. }
  2230. };
  2231. const nodeObjectsCacheMap = new WeakMap();
  2232. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2233. const ShaderNodeObject = function ( obj, altType = null ) {
  2234. const type = getValueType( obj );
  2235. if ( type === 'node' ) {
  2236. let nodeObject = nodeObjectsCacheMap.get( obj );
  2237. if ( nodeObject === undefined ) {
  2238. nodeObject = new Proxy( obj, shaderNodeHandler );
  2239. nodeObjectsCacheMap.set( obj, nodeObject );
  2240. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  2241. }
  2242. return nodeObject;
  2243. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2244. return nodeObject( getConstNode( obj, altType ) );
  2245. } else if ( type === 'shader' ) {
  2246. return obj.isFn ? obj : Fn( obj );
  2247. }
  2248. return obj;
  2249. };
  2250. const ShaderNodeObjects = function ( objects, altType = null ) {
  2251. for ( const name in objects ) {
  2252. objects[ name ] = nodeObject( objects[ name ], altType );
  2253. }
  2254. return objects;
  2255. };
  2256. const ShaderNodeArray = function ( array, altType = null ) {
  2257. const len = array.length;
  2258. for ( let i = 0; i < len; i ++ ) {
  2259. array[ i ] = nodeObject( array[ i ], altType );
  2260. }
  2261. return array;
  2262. };
  2263. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2264. function assignNode( node ) {
  2265. if ( settings !== null ) {
  2266. node = nodeObject( Object.assign( node, settings ) );
  2267. if ( settings.intent === true ) {
  2268. node = node.toVarIntent();
  2269. }
  2270. } else {
  2271. node = nodeObject( node );
  2272. }
  2273. return node;
  2274. }
  2275. let fn, name = scope, minParams, maxParams;
  2276. function verifyParamsLimit( params ) {
  2277. let tslName;
  2278. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2279. else tslName = NodeClass.type;
  2280. if ( minParams !== undefined && params.length < minParams ) {
  2281. console.error( `THREE.TSL: "${ tslName }" parameter length is less than minimum required.` );
  2282. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2283. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2284. console.error( `THREE.TSL: "${ tslName }" parameter length exceeds limit.` );
  2285. return params.slice( 0, maxParams );
  2286. }
  2287. return params;
  2288. }
  2289. if ( scope === null ) {
  2290. fn = ( ...params ) => {
  2291. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2292. };
  2293. } else if ( factor !== null ) {
  2294. factor = nodeObject( factor );
  2295. fn = ( ...params ) => {
  2296. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2297. };
  2298. } else {
  2299. fn = ( ...params ) => {
  2300. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2301. };
  2302. }
  2303. fn.setParameterLength = ( ...params ) => {
  2304. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2305. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2306. return fn;
  2307. };
  2308. fn.setName = ( value ) => {
  2309. name = value;
  2310. return fn;
  2311. };
  2312. return fn;
  2313. };
  2314. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2315. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2316. };
  2317. class ShaderCallNodeInternal extends Node {
  2318. constructor( shaderNode, inputNodes ) {
  2319. super();
  2320. this.shaderNode = shaderNode;
  2321. this.inputNodes = inputNodes;
  2322. this.isShaderCallNodeInternal = true;
  2323. }
  2324. getNodeType( builder ) {
  2325. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2326. }
  2327. getMemberType( builder, name ) {
  2328. return this.getOutputNode( builder ).getMemberType( builder, name );
  2329. }
  2330. call( builder ) {
  2331. const { shaderNode, inputNodes } = this;
  2332. const properties = builder.getNodeProperties( shaderNode );
  2333. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2334. const subBuildProperty = subBuild || 'default';
  2335. if ( properties[ subBuildProperty ] ) {
  2336. return properties[ subBuildProperty ];
  2337. }
  2338. //
  2339. const previousSubBuildFn = builder.subBuildFn;
  2340. builder.subBuildFn = subBuild;
  2341. let result = null;
  2342. if ( shaderNode.layout ) {
  2343. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2344. if ( functionNodesCacheMap === undefined ) {
  2345. functionNodesCacheMap = new WeakMap();
  2346. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2347. }
  2348. let functionNode = functionNodesCacheMap.get( shaderNode );
  2349. if ( functionNode === undefined ) {
  2350. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2351. functionNodesCacheMap.set( shaderNode, functionNode );
  2352. }
  2353. builder.addInclude( functionNode );
  2354. result = nodeObject( functionNode.call( inputNodes ) );
  2355. } else {
  2356. let inputs = inputNodes;
  2357. if ( Array.isArray( inputs ) ) {
  2358. // If inputs is an array, we need to convert it to a Proxy
  2359. // so we can call TSL functions using the syntax `Fn( ( { r, g, b } ) => { ... } )`
  2360. // and call through `fn( 0, 1, 0 )` or `fn( { r: 0, g: 1, b: 0 } )`
  2361. let index = 0;
  2362. inputs = new Proxy( inputs, {
  2363. get: ( target, property, receiver ) => {
  2364. let value;
  2365. if ( target[ property ] === undefined ) {
  2366. value = target[ index ++ ];
  2367. } else {
  2368. value = Reflect.get( target, property, receiver );
  2369. }
  2370. return value;
  2371. }
  2372. } );
  2373. }
  2374. const secureNodeBuilder = new Proxy( builder, {
  2375. get: ( target, property, receiver ) => {
  2376. let value;
  2377. if ( Symbol.iterator === property ) {
  2378. value = function* () {
  2379. yield undefined;
  2380. };
  2381. } else {
  2382. value = Reflect.get( target, property, receiver );
  2383. }
  2384. return value;
  2385. }
  2386. } );
  2387. const jsFunc = shaderNode.jsFunc;
  2388. const outputNode = inputs !== null || jsFunc.length > 1 ? jsFunc( inputs || [], secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2389. result = nodeObject( outputNode );
  2390. }
  2391. builder.subBuildFn = previousSubBuildFn;
  2392. if ( shaderNode.once ) {
  2393. properties[ subBuildProperty ] = result;
  2394. }
  2395. return result;
  2396. }
  2397. setupOutput( builder ) {
  2398. builder.addStack();
  2399. builder.stack.outputNode = this.call( builder );
  2400. return builder.removeStack();
  2401. }
  2402. getOutputNode( builder ) {
  2403. const properties = builder.getNodeProperties( this );
  2404. const subBuildOutput = builder.getSubBuildOutput( this );
  2405. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2406. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2407. return properties[ subBuildOutput ];
  2408. }
  2409. build( builder, output = null ) {
  2410. let result = null;
  2411. const buildStage = builder.getBuildStage();
  2412. const properties = builder.getNodeProperties( this );
  2413. const subBuildOutput = builder.getSubBuildOutput( this );
  2414. const outputNode = this.getOutputNode( builder );
  2415. if ( buildStage === 'setup' ) {
  2416. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2417. if ( properties[ subBuildInitialized ] !== true ) {
  2418. properties[ subBuildInitialized ] = true;
  2419. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2420. properties[ subBuildOutput ].build( builder );
  2421. // If the shaderNode has subBuilds, add them to the chaining nodes
  2422. // so they can be built later in the build process.
  2423. if ( this.shaderNode.subBuilds ) {
  2424. for ( const node of builder.chaining ) {
  2425. const nodeData = builder.getDataFromNode( node, 'any' );
  2426. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2427. for ( const subBuild of this.shaderNode.subBuilds ) {
  2428. nodeData.subBuilds.add( subBuild );
  2429. }
  2430. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2431. }
  2432. }
  2433. }
  2434. result = properties[ subBuildOutput ];
  2435. } else if ( buildStage === 'analyze' ) {
  2436. outputNode.build( builder, output );
  2437. } else if ( buildStage === 'generate' ) {
  2438. result = outputNode.build( builder, output ) || '';
  2439. }
  2440. return result;
  2441. }
  2442. }
  2443. class ShaderNodeInternal extends Node {
  2444. constructor( jsFunc, nodeType ) {
  2445. super( nodeType );
  2446. this.jsFunc = jsFunc;
  2447. this.layout = null;
  2448. this.global = true;
  2449. this.once = false;
  2450. }
  2451. setLayout( layout ) {
  2452. this.layout = layout;
  2453. return this;
  2454. }
  2455. call( inputs = null ) {
  2456. nodeObjects( inputs );
  2457. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2458. }
  2459. setup() {
  2460. return this.call();
  2461. }
  2462. }
  2463. const bools = [ false, true ];
  2464. const uints = [ 0, 1, 2, 3 ];
  2465. const ints = [ -1, -2 ];
  2466. 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 ];
  2467. const boolsCacheMap = new Map();
  2468. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2469. const uintsCacheMap = new Map();
  2470. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2471. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2472. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2473. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2474. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2475. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2476. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2477. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2478. const getConstNode = ( value, type ) => {
  2479. if ( constNodesCacheMap.has( value ) ) {
  2480. return constNodesCacheMap.get( value );
  2481. } else if ( value.isNode === true ) {
  2482. return value;
  2483. } else {
  2484. return new ConstNode( value, type );
  2485. }
  2486. };
  2487. const ConvertType = function ( type, cacheMap = null ) {
  2488. return ( ...params ) => {
  2489. for ( const param of params ) {
  2490. if ( param === undefined ) {
  2491. console.error( `THREE.TSL: Invalid parameter for the type "${ type }".` );
  2492. return nodeObject( new ConstNode( 0, type ) );
  2493. }
  2494. }
  2495. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2496. const paramType = typeof param;
  2497. return paramType !== 'object' && paramType !== 'function';
  2498. } ) ) ) {
  2499. params = [ getValueFromType( type, ...params ) ];
  2500. }
  2501. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2502. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2503. }
  2504. if ( params.length === 1 ) {
  2505. const node = getConstNode( params[ 0 ], type );
  2506. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2507. return nodeObjectIntent( new ConvertNode( node, type ) );
  2508. }
  2509. const nodes = params.map( param => getConstNode( param ) );
  2510. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2511. };
  2512. };
  2513. // exports
  2514. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2515. // utils
  2516. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2517. // shader node base
  2518. function ShaderNode( jsFunc, nodeType ) {
  2519. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2520. }
  2521. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2522. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2523. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2524. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2525. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2526. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2527. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { intent: true, ...settings } );
  2528. let fnId = 0;
  2529. class FnNode extends Node {
  2530. constructor( jsFunc, layout = null ) {
  2531. super();
  2532. let nodeType = null;
  2533. if ( layout !== null ) {
  2534. if ( typeof layout === 'object' ) {
  2535. nodeType = layout.return;
  2536. } else {
  2537. if ( typeof layout === 'string' ) {
  2538. nodeType = layout;
  2539. } else {
  2540. console.error( 'THREE.TSL: Invalid layout type.' );
  2541. }
  2542. layout = null;
  2543. }
  2544. }
  2545. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2546. if ( layout !== null ) {
  2547. this.setLayout( layout );
  2548. }
  2549. this.isFn = true;
  2550. }
  2551. setLayout( layout ) {
  2552. const nodeType = this.shaderNode.nodeType;
  2553. if ( typeof layout.inputs !== 'object' ) {
  2554. const fullLayout = {
  2555. name: 'fn' + fnId ++,
  2556. type: nodeType,
  2557. inputs: []
  2558. };
  2559. for ( const name in layout ) {
  2560. if ( name === 'return' ) continue;
  2561. fullLayout.inputs.push( {
  2562. name: name,
  2563. type: layout[ name ]
  2564. } );
  2565. }
  2566. layout = fullLayout;
  2567. }
  2568. this.shaderNode.setLayout( layout );
  2569. return this;
  2570. }
  2571. getNodeType( builder ) {
  2572. return this.shaderNode.getNodeType( builder ) || 'float';
  2573. }
  2574. call( ...params ) {
  2575. let inputs;
  2576. nodeObjects( params );
  2577. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2578. if ( isArrayAsParameter ) {
  2579. inputs = [ ...params ];
  2580. } else {
  2581. inputs = params[ 0 ];
  2582. }
  2583. const fnCall = this.shaderNode.call( inputs );
  2584. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2585. return fnCall.toVarIntent();
  2586. }
  2587. once( subBuilds = null ) {
  2588. this.shaderNode.once = true;
  2589. this.shaderNode.subBuilds = subBuilds;
  2590. return this;
  2591. }
  2592. generate( builder ) {
  2593. const type = this.getNodeType( builder );
  2594. console.error( 'THREE.TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".' );
  2595. return builder.generateConst( type );
  2596. }
  2597. }
  2598. function Fn( jsFunc, layout = null ) {
  2599. const instance = new FnNode( jsFunc, layout );
  2600. return new Proxy( () => {}, {
  2601. apply( target, thisArg, params ) {
  2602. return instance.call( ...params );
  2603. },
  2604. get( target, prop, receiver ) {
  2605. return Reflect.get( instance, prop, receiver );
  2606. },
  2607. set( target, prop, value, receiver ) {
  2608. return Reflect.set( instance, prop, value, receiver );
  2609. }
  2610. } );
  2611. }
  2612. //
  2613. const setCurrentStack = ( stack ) => {
  2614. currentStack = stack;
  2615. };
  2616. const getCurrentStack = () => currentStack;
  2617. /**
  2618. * Represent a conditional node using if/else statements.
  2619. *
  2620. * ```js
  2621. * If( condition, function )
  2622. * .ElseIf( condition, function )
  2623. * .Else( function )
  2624. * ```
  2625. * @tsl
  2626. * @function
  2627. * @param {...any} params - The parameters for the conditional node.
  2628. * @returns {StackNode} The conditional node.
  2629. */
  2630. const If = ( ...params ) => currentStack.If( ...params );
  2631. /**
  2632. * Represent a conditional node using switch/case statements.
  2633. *
  2634. * ```js
  2635. * Switch( value )
  2636. * .Case( 1, function )
  2637. * .Case( 2, 3, 4, function )
  2638. * .Default( function )
  2639. * ```
  2640. * @tsl
  2641. * @function
  2642. * @param {...any} params - The parameters for the conditional node.
  2643. * @returns {StackNode} The conditional node.
  2644. */
  2645. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2646. /**
  2647. * Add the given node to the current stack.
  2648. *
  2649. * @param {Node} node - The node to add.
  2650. * @returns {Node} The node that was added to the stack.
  2651. */
  2652. function Stack( node ) {
  2653. if ( currentStack ) currentStack.add( node );
  2654. return node;
  2655. }
  2656. addMethodChaining( 'toStack', Stack );
  2657. // types
  2658. const color = new ConvertType( 'color' );
  2659. const float = new ConvertType( 'float', cacheMaps.float );
  2660. const int = new ConvertType( 'int', cacheMaps.ints );
  2661. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2662. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2663. const vec2 = new ConvertType( 'vec2' );
  2664. const ivec2 = new ConvertType( 'ivec2' );
  2665. const uvec2 = new ConvertType( 'uvec2' );
  2666. const bvec2 = new ConvertType( 'bvec2' );
  2667. const vec3 = new ConvertType( 'vec3' );
  2668. const ivec3 = new ConvertType( 'ivec3' );
  2669. const uvec3 = new ConvertType( 'uvec3' );
  2670. const bvec3 = new ConvertType( 'bvec3' );
  2671. const vec4 = new ConvertType( 'vec4' );
  2672. const ivec4 = new ConvertType( 'ivec4' );
  2673. const uvec4 = new ConvertType( 'uvec4' );
  2674. const bvec4 = new ConvertType( 'bvec4' );
  2675. const mat2 = new ConvertType( 'mat2' );
  2676. const mat3 = new ConvertType( 'mat3' );
  2677. const mat4 = new ConvertType( 'mat4' );
  2678. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2679. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2680. addMethodChaining( 'toColor', color );
  2681. addMethodChaining( 'toFloat', float );
  2682. addMethodChaining( 'toInt', int );
  2683. addMethodChaining( 'toUint', uint );
  2684. addMethodChaining( 'toBool', bool );
  2685. addMethodChaining( 'toVec2', vec2 );
  2686. addMethodChaining( 'toIVec2', ivec2 );
  2687. addMethodChaining( 'toUVec2', uvec2 );
  2688. addMethodChaining( 'toBVec2', bvec2 );
  2689. addMethodChaining( 'toVec3', vec3 );
  2690. addMethodChaining( 'toIVec3', ivec3 );
  2691. addMethodChaining( 'toUVec3', uvec3 );
  2692. addMethodChaining( 'toBVec3', bvec3 );
  2693. addMethodChaining( 'toVec4', vec4 );
  2694. addMethodChaining( 'toIVec4', ivec4 );
  2695. addMethodChaining( 'toUVec4', uvec4 );
  2696. addMethodChaining( 'toBVec4', bvec4 );
  2697. addMethodChaining( 'toMat2', mat2 );
  2698. addMethodChaining( 'toMat3', mat3 );
  2699. addMethodChaining( 'toMat4', mat4 );
  2700. // basic nodes
  2701. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2702. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2703. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2704. addMethodChaining( 'element', element );
  2705. addMethodChaining( 'convert', convert );
  2706. // deprecated
  2707. /**
  2708. * @tsl
  2709. * @function
  2710. * @deprecated since r176. Use {@link Stack} instead.
  2711. *
  2712. * @param {Node} node - The node to add.
  2713. * @returns {Function}
  2714. */
  2715. const append = ( node ) => { // @deprecated, r176
  2716. console.warn( 'THREE.TSL: append() has been renamed to Stack().' );
  2717. return Stack( node );
  2718. };
  2719. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2720. console.warn( 'THREE.TSL: .append() has been renamed to .toStack().' );
  2721. return Stack( node );
  2722. } );
  2723. /**
  2724. * This class represents a shader property. It can be used
  2725. * to explicitly define a property and assign a value to it.
  2726. *
  2727. * ```js
  2728. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2729. *```
  2730. * `PropertyNode` is used by the engine to predefined common material properties
  2731. * for TSL code.
  2732. *
  2733. * @augments Node
  2734. */
  2735. class PropertyNode extends Node {
  2736. static get type() {
  2737. return 'PropertyNode';
  2738. }
  2739. /**
  2740. * Constructs a new property node.
  2741. *
  2742. * @param {string} nodeType - The type of the node.
  2743. * @param {?string} [name=null] - The name of the property in the shader.
  2744. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2745. */
  2746. constructor( nodeType, name = null, varying = false ) {
  2747. super( nodeType );
  2748. /**
  2749. * The name of the property in the shader. If no name is defined,
  2750. * the node system auto-generates one.
  2751. *
  2752. * @type {?string}
  2753. * @default null
  2754. */
  2755. this.name = name;
  2756. /**
  2757. * Whether this property is a varying or not.
  2758. *
  2759. * @type {boolean}
  2760. * @default false
  2761. */
  2762. this.varying = varying;
  2763. /**
  2764. * This flag can be used for type testing.
  2765. *
  2766. * @type {boolean}
  2767. * @readonly
  2768. * @default true
  2769. */
  2770. this.isPropertyNode = true;
  2771. /**
  2772. * This flag is used for global cache.
  2773. *
  2774. * @type {boolean}
  2775. * @default true
  2776. */
  2777. this.global = true;
  2778. }
  2779. getHash( builder ) {
  2780. return this.name || super.getHash( builder );
  2781. }
  2782. generate( builder ) {
  2783. let nodeVar;
  2784. if ( this.varying === true ) {
  2785. nodeVar = builder.getVaryingFromNode( this, this.name );
  2786. nodeVar.needsInterpolation = true;
  2787. } else {
  2788. nodeVar = builder.getVarFromNode( this, this.name );
  2789. }
  2790. return builder.getPropertyName( nodeVar );
  2791. }
  2792. }
  2793. /**
  2794. * TSL function for creating a property node.
  2795. *
  2796. * @tsl
  2797. * @function
  2798. * @param {string} type - The type of the node.
  2799. * @param {?string} [name=null] - The name of the property in the shader.
  2800. * @returns {PropertyNode}
  2801. */
  2802. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2803. /**
  2804. * TSL function for creating a varying property node.
  2805. *
  2806. * @tsl
  2807. * @function
  2808. * @param {string} type - The type of the node.
  2809. * @param {?string} [name=null] - The name of the varying in the shader.
  2810. * @returns {PropertyNode}
  2811. */
  2812. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2813. /**
  2814. * TSL object that represents the shader variable `DiffuseColor`.
  2815. *
  2816. * @tsl
  2817. * @type {PropertyNode<vec4>}
  2818. */
  2819. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2820. /**
  2821. * TSL object that represents the shader variable `EmissiveColor`.
  2822. *
  2823. * @tsl
  2824. * @type {PropertyNode<vec3>}
  2825. */
  2826. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2827. /**
  2828. * TSL object that represents the shader variable `Roughness`.
  2829. *
  2830. * @tsl
  2831. * @type {PropertyNode<float>}
  2832. */
  2833. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2834. /**
  2835. * TSL object that represents the shader variable `Metalness`.
  2836. *
  2837. * @tsl
  2838. * @type {PropertyNode<float>}
  2839. */
  2840. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2841. /**
  2842. * TSL object that represents the shader variable `Clearcoat`.
  2843. *
  2844. * @tsl
  2845. * @type {PropertyNode<float>}
  2846. */
  2847. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2848. /**
  2849. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2850. *
  2851. * @tsl
  2852. * @type {PropertyNode<float>}
  2853. */
  2854. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2855. /**
  2856. * TSL object that represents the shader variable `Sheen`.
  2857. *
  2858. * @tsl
  2859. * @type {PropertyNode<vec3>}
  2860. */
  2861. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2862. /**
  2863. * TSL object that represents the shader variable `SheenRoughness`.
  2864. *
  2865. * @tsl
  2866. * @type {PropertyNode<float>}
  2867. */
  2868. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2869. /**
  2870. * TSL object that represents the shader variable `Iridescence`.
  2871. *
  2872. * @tsl
  2873. * @type {PropertyNode<float>}
  2874. */
  2875. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2876. /**
  2877. * TSL object that represents the shader variable `IridescenceIOR`.
  2878. *
  2879. * @tsl
  2880. * @type {PropertyNode<float>}
  2881. */
  2882. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2883. /**
  2884. * TSL object that represents the shader variable `IridescenceThickness`.
  2885. *
  2886. * @tsl
  2887. * @type {PropertyNode<float>}
  2888. */
  2889. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2890. /**
  2891. * TSL object that represents the shader variable `AlphaT`.
  2892. *
  2893. * @tsl
  2894. * @type {PropertyNode<float>}
  2895. */
  2896. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2897. /**
  2898. * TSL object that represents the shader variable `Anisotropy`.
  2899. *
  2900. * @tsl
  2901. * @type {PropertyNode<float>}
  2902. */
  2903. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2904. /**
  2905. * TSL object that represents the shader variable `AnisotropyT`.
  2906. *
  2907. * @tsl
  2908. * @type {PropertyNode<vec3>}
  2909. */
  2910. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2911. /**
  2912. * TSL object that represents the shader variable `AnisotropyB`.
  2913. *
  2914. * @tsl
  2915. * @type {PropertyNode<vec3>}
  2916. */
  2917. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2918. /**
  2919. * TSL object that represents the shader variable `SpecularColor`.
  2920. *
  2921. * @tsl
  2922. * @type {PropertyNode<color>}
  2923. */
  2924. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2925. /**
  2926. * TSL object that represents the shader variable `SpecularF90`.
  2927. *
  2928. * @tsl
  2929. * @type {PropertyNode<float>}
  2930. */
  2931. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2932. /**
  2933. * TSL object that represents the shader variable `Shininess`.
  2934. *
  2935. * @tsl
  2936. * @type {PropertyNode<float>}
  2937. */
  2938. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2939. /**
  2940. * TSL object that represents the shader variable `Output`.
  2941. *
  2942. * @tsl
  2943. * @type {PropertyNode<vec4>}
  2944. */
  2945. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2946. /**
  2947. * TSL object that represents the shader variable `dashSize`.
  2948. *
  2949. * @tsl
  2950. * @type {PropertyNode<float>}
  2951. */
  2952. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2953. /**
  2954. * TSL object that represents the shader variable `gapSize`.
  2955. *
  2956. * @tsl
  2957. * @type {PropertyNode<float>}
  2958. */
  2959. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2960. /**
  2961. * TSL object that represents the shader variable `pointWidth`.
  2962. *
  2963. * @tsl
  2964. * @type {PropertyNode<float>}
  2965. */
  2966. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2967. /**
  2968. * TSL object that represents the shader variable `IOR`.
  2969. *
  2970. * @tsl
  2971. * @type {PropertyNode<float>}
  2972. */
  2973. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2974. /**
  2975. * TSL object that represents the shader variable `Transmission`.
  2976. *
  2977. * @tsl
  2978. * @type {PropertyNode<float>}
  2979. */
  2980. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2981. /**
  2982. * TSL object that represents the shader variable `Thickness`.
  2983. *
  2984. * @tsl
  2985. * @type {PropertyNode<float>}
  2986. */
  2987. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2988. /**
  2989. * TSL object that represents the shader variable `AttenuationDistance`.
  2990. *
  2991. * @tsl
  2992. * @type {PropertyNode<float>}
  2993. */
  2994. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2995. /**
  2996. * TSL object that represents the shader variable `AttenuationColor`.
  2997. *
  2998. * @tsl
  2999. * @type {PropertyNode<color>}
  3000. */
  3001. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3002. /**
  3003. * TSL object that represents the shader variable `Dispersion`.
  3004. *
  3005. * @tsl
  3006. * @type {PropertyNode<float>}
  3007. */
  3008. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3009. /**
  3010. * This node can be used to group single instances of {@link UniformNode}
  3011. * and manage them as a uniform buffer.
  3012. *
  3013. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3014. * will be used when defining the {@link UniformNode#groupNode} property.
  3015. *
  3016. * - `objectGroup`: Uniform buffer per object.
  3017. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3018. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3019. *
  3020. * @augments Node
  3021. */
  3022. class UniformGroupNode extends Node {
  3023. static get type() {
  3024. return 'UniformGroupNode';
  3025. }
  3026. /**
  3027. * Constructs a new uniform group node.
  3028. *
  3029. * @param {string} name - The name of the uniform group node.
  3030. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3031. * @param {number} [order=1] - Influences the internal sorting.
  3032. */
  3033. constructor( name, shared = false, order = 1 ) {
  3034. super( 'string' );
  3035. /**
  3036. * The name of the uniform group node.
  3037. *
  3038. * @type {string}
  3039. */
  3040. this.name = name;
  3041. /**
  3042. * Whether this uniform group node is shared or not.
  3043. *
  3044. * @type {boolean}
  3045. * @default false
  3046. */
  3047. this.shared = shared;
  3048. /**
  3049. * Influences the internal sorting.
  3050. * TODO: Add details when this property should be changed.
  3051. *
  3052. * @type {number}
  3053. * @default 1
  3054. */
  3055. this.order = order;
  3056. /**
  3057. * This flag can be used for type testing.
  3058. *
  3059. * @type {boolean}
  3060. * @readonly
  3061. * @default true
  3062. */
  3063. this.isUniformGroup = true;
  3064. }
  3065. serialize( data ) {
  3066. super.serialize( data );
  3067. data.name = this.name;
  3068. data.version = this.version;
  3069. data.shared = this.shared;
  3070. }
  3071. deserialize( data ) {
  3072. super.deserialize( data );
  3073. this.name = data.name;
  3074. this.version = data.version;
  3075. this.shared = data.shared;
  3076. }
  3077. }
  3078. /**
  3079. * TSL function for creating a uniform group node with the given name.
  3080. *
  3081. * @tsl
  3082. * @function
  3083. * @param {string} name - The name of the uniform group node.
  3084. * @returns {UniformGroupNode}
  3085. */
  3086. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3087. /**
  3088. * TSL function for creating a shared uniform group node with the given name and order.
  3089. *
  3090. * @tsl
  3091. * @function
  3092. * @param {string} name - The name of the uniform group node.
  3093. * @param {number} [order=0] - Influences the internal sorting.
  3094. * @returns {UniformGroupNode}
  3095. */
  3096. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3097. /**
  3098. * TSL object that represents a shared uniform group node which is updated once per frame.
  3099. *
  3100. * @tsl
  3101. * @type {UniformGroupNode}
  3102. */
  3103. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3104. /**
  3105. * TSL object that represents a shared uniform group node which is updated once per render.
  3106. *
  3107. * @tsl
  3108. * @type {UniformGroupNode}
  3109. */
  3110. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3111. /**
  3112. * TSL object that represents a uniform group node which is updated once per object.
  3113. *
  3114. * @tsl
  3115. * @type {UniformGroupNode}
  3116. */
  3117. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3118. /**
  3119. * Class for representing a uniform.
  3120. *
  3121. * @augments InputNode
  3122. */
  3123. class UniformNode extends InputNode {
  3124. static get type() {
  3125. return 'UniformNode';
  3126. }
  3127. /**
  3128. * Constructs a new uniform node.
  3129. *
  3130. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3131. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3132. */
  3133. constructor( value, nodeType = null ) {
  3134. super( value, nodeType );
  3135. /**
  3136. * This flag can be used for type testing.
  3137. *
  3138. * @type {boolean}
  3139. * @readonly
  3140. * @default true
  3141. */
  3142. this.isUniformNode = true;
  3143. /**
  3144. * The name or label of the uniform.
  3145. *
  3146. * @type {string}
  3147. * @default ''
  3148. */
  3149. this.name = '';
  3150. /**
  3151. * The uniform group of this uniform. By default, uniforms are
  3152. * managed per object but they might belong to a shared group
  3153. * which is updated per frame or render call.
  3154. *
  3155. * @type {UniformGroupNode}
  3156. */
  3157. this.groupNode = objectGroup;
  3158. }
  3159. /**
  3160. * Sets the {@link UniformNode#name} property.
  3161. *
  3162. * @param {string} name - The name of the uniform.
  3163. * @return {UniformNode} A reference to this node.
  3164. */
  3165. setName( name ) {
  3166. this.name = name;
  3167. return this;
  3168. }
  3169. /**
  3170. * Sets the {@link UniformNode#name} property.
  3171. *
  3172. * @deprecated
  3173. * @param {string} name - The name of the uniform.
  3174. * @return {UniformNode} A reference to this node.
  3175. */
  3176. label( name ) {
  3177. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  3178. return this.setName( name );
  3179. }
  3180. /**
  3181. * Sets the {@link UniformNode#groupNode} property.
  3182. *
  3183. * @param {UniformGroupNode} group - The uniform group.
  3184. * @return {UniformNode} A reference to this node.
  3185. */
  3186. setGroup( group ) {
  3187. this.groupNode = group;
  3188. return this;
  3189. }
  3190. /**
  3191. * Returns the {@link UniformNode#groupNode}.
  3192. *
  3193. * @return {UniformGroupNode} The uniform group.
  3194. */
  3195. getGroup() {
  3196. return this.groupNode;
  3197. }
  3198. /**
  3199. * By default, this method returns the result of {@link Node#getHash} but derived
  3200. * classes might overwrite this method with a different implementation.
  3201. *
  3202. * @param {NodeBuilder} builder - The current node builder.
  3203. * @return {string} The uniform hash.
  3204. */
  3205. getUniformHash( builder ) {
  3206. return this.getHash( builder );
  3207. }
  3208. onUpdate( callback, updateType ) {
  3209. const self = this.getSelf();
  3210. callback = callback.bind( self );
  3211. return super.onUpdate( ( frame ) => {
  3212. const value = callback( frame, self );
  3213. if ( value !== undefined ) {
  3214. this.value = value;
  3215. }
  3216. }, updateType );
  3217. }
  3218. getInputType( builder ) {
  3219. let type = super.getInputType( builder );
  3220. if ( type === 'bool' ) {
  3221. type = 'uint';
  3222. }
  3223. return type;
  3224. }
  3225. generate( builder, output ) {
  3226. const type = this.getNodeType( builder );
  3227. const hash = this.getUniformHash( builder );
  3228. let sharedNode = builder.getNodeFromHash( hash );
  3229. if ( sharedNode === undefined ) {
  3230. builder.setHashNode( this, hash );
  3231. sharedNode = this;
  3232. }
  3233. const sharedNodeType = sharedNode.getInputType( builder );
  3234. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3235. const uniformName = builder.getPropertyName( nodeUniform );
  3236. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3237. //
  3238. let snippet = uniformName;
  3239. if ( type === 'bool' ) {
  3240. // cache to variable
  3241. const nodeData = builder.getDataFromNode( this );
  3242. let propertyName = nodeData.propertyName;
  3243. if ( propertyName === undefined ) {
  3244. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3245. propertyName = builder.getPropertyName( nodeVar );
  3246. nodeData.propertyName = propertyName;
  3247. snippet = builder.format( uniformName, sharedNodeType, type );
  3248. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3249. }
  3250. snippet = propertyName;
  3251. }
  3252. return builder.format( snippet, type, output );
  3253. }
  3254. }
  3255. /**
  3256. * TSL function for creating a uniform node.
  3257. *
  3258. * @tsl
  3259. * @function
  3260. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3261. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3262. * @returns {UniformNode}
  3263. */
  3264. const uniform = ( value, type ) => {
  3265. const nodeType = getConstNodeType( type || value );
  3266. if ( nodeType === value ) {
  3267. // if the value is a type but no having a value
  3268. value = getValueFromType( nodeType );
  3269. }
  3270. // @TODO: get ConstNode from .traverse() in the future
  3271. value = ( value && value.isNode === true ) ? ( value.node && value.node.value ) || value.value : value;
  3272. return nodeObject( new UniformNode( value, nodeType ) );
  3273. };
  3274. /**
  3275. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3276. * ```js
  3277. * const colors = array( [
  3278. * vec3( 1, 0, 0 ),
  3279. * vec3( 0, 1, 0 ),
  3280. * vec3( 0, 0, 1 )
  3281. * ] );
  3282. *
  3283. * const redColor = tintColors.element( 0 );
  3284. *
  3285. * @augments TempNode
  3286. */
  3287. class ArrayNode extends TempNode {
  3288. static get type() {
  3289. return 'ArrayNode';
  3290. }
  3291. /**
  3292. * Constructs a new array node.
  3293. *
  3294. * @param {?string} nodeType - The data type of the elements.
  3295. * @param {number} count - Size of the array.
  3296. * @param {?Array<Node>} [values=null] - Array default values.
  3297. */
  3298. constructor( nodeType, count, values = null ) {
  3299. super( nodeType );
  3300. /**
  3301. * Array size.
  3302. *
  3303. * @type {number}
  3304. */
  3305. this.count = count;
  3306. /**
  3307. * Array default values.
  3308. *
  3309. * @type {?Array<Node>}
  3310. */
  3311. this.values = values;
  3312. /**
  3313. * This flag can be used for type testing.
  3314. *
  3315. * @type {boolean}
  3316. * @readonly
  3317. * @default true
  3318. */
  3319. this.isArrayNode = true;
  3320. }
  3321. /**
  3322. * Returns the number of elements in the node array.
  3323. *
  3324. * @param {NodeBuilder} builder - The current node builder.
  3325. * @return {number} The number of elements in the node array.
  3326. */
  3327. getArrayCount( /*builder*/ ) {
  3328. return this.count;
  3329. }
  3330. /**
  3331. * Returns the node's type.
  3332. *
  3333. * @param {NodeBuilder} builder - The current node builder.
  3334. * @return {string} The type of the node.
  3335. */
  3336. getNodeType( builder ) {
  3337. if ( this.nodeType === null ) {
  3338. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3339. }
  3340. return this.nodeType;
  3341. }
  3342. /**
  3343. * Returns the node's type.
  3344. *
  3345. * @param {NodeBuilder} builder - The current node builder.
  3346. * @return {string} The type of the node.
  3347. */
  3348. getElementType( builder ) {
  3349. return this.getNodeType( builder );
  3350. }
  3351. /**
  3352. * This method builds the output node and returns the resulting array as a shader string.
  3353. *
  3354. * @param {NodeBuilder} builder - The current node builder.
  3355. * @return {string} The generated shader string.
  3356. */
  3357. generate( builder ) {
  3358. const type = this.getNodeType( builder );
  3359. return builder.generateArray( type, this.count, this.values );
  3360. }
  3361. }
  3362. /**
  3363. * TSL function for creating an array node.
  3364. *
  3365. * @tsl
  3366. * @function
  3367. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3368. * or an array containing the default values (e.g., [ vec3() ]).
  3369. * @param {?number} [count] - Size of the array.
  3370. * @returns {ArrayNode}
  3371. */
  3372. const array = ( ...params ) => {
  3373. let node;
  3374. if ( params.length === 1 ) {
  3375. const values = params[ 0 ];
  3376. node = new ArrayNode( null, values.length, values );
  3377. } else {
  3378. const nodeType = params[ 0 ];
  3379. const count = params[ 1 ];
  3380. node = new ArrayNode( nodeType, count );
  3381. }
  3382. return nodeObject( node );
  3383. };
  3384. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3385. /**
  3386. * These node represents an assign operation. Meaning a node is assigned
  3387. * to another node.
  3388. *
  3389. * @augments TempNode
  3390. */
  3391. class AssignNode extends TempNode {
  3392. static get type() {
  3393. return 'AssignNode';
  3394. }
  3395. /**
  3396. * Constructs a new assign node.
  3397. *
  3398. * @param {Node} targetNode - The target node.
  3399. * @param {Node} sourceNode - The source type.
  3400. */
  3401. constructor( targetNode, sourceNode ) {
  3402. super();
  3403. /**
  3404. * The target node.
  3405. *
  3406. * @type {Node}
  3407. */
  3408. this.targetNode = targetNode;
  3409. /**
  3410. * The source node.
  3411. *
  3412. * @type {Node}
  3413. */
  3414. this.sourceNode = sourceNode;
  3415. /**
  3416. * This flag can be used for type testing.
  3417. *
  3418. * @type {boolean}
  3419. * @readonly
  3420. * @default true
  3421. */
  3422. this.isAssignNode = true;
  3423. }
  3424. /**
  3425. * Whether this node is used more than once in context of other nodes. This method
  3426. * is overwritten since it always returns `false` (assigns are unique).
  3427. *
  3428. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3429. */
  3430. hasDependencies() {
  3431. return false;
  3432. }
  3433. getNodeType( builder, output ) {
  3434. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3435. }
  3436. /**
  3437. * Whether a split is required when assigning source to target. This can happen when the component length of
  3438. * target and source data type does not match.
  3439. *
  3440. * @param {NodeBuilder} builder - The current node builder.
  3441. * @return {boolean} Whether a split is required when assigning source to target.
  3442. */
  3443. needsSplitAssign( builder ) {
  3444. const { targetNode } = this;
  3445. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3446. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3447. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3448. return assignDifferentVector;
  3449. }
  3450. return false;
  3451. }
  3452. setup( builder ) {
  3453. const { targetNode, sourceNode } = this;
  3454. const targetProperties = builder.getNodeProperties( targetNode );
  3455. targetProperties.assign = true;
  3456. const properties = builder.getNodeProperties( this );
  3457. properties.sourceNode = sourceNode;
  3458. properties.targetNode = targetNode.context( { assign: true } );
  3459. }
  3460. generate( builder, output ) {
  3461. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3462. const needsSplitAssign = this.needsSplitAssign( builder );
  3463. const target = targetNode.build( builder );
  3464. const targetType = targetNode.getNodeType( builder );
  3465. const source = sourceNode.build( builder, targetType );
  3466. const sourceType = sourceNode.getNodeType( builder );
  3467. const nodeData = builder.getDataFromNode( this );
  3468. //
  3469. let snippet;
  3470. if ( nodeData.initialized === true ) {
  3471. if ( output !== 'void' ) {
  3472. snippet = target;
  3473. }
  3474. } else if ( needsSplitAssign ) {
  3475. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3476. const sourceProperty = builder.getPropertyName( sourceVar );
  3477. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3478. const splitNode = targetNode.node;
  3479. const splitTargetNode = splitNode.node.context( { assign: true } );
  3480. const targetRoot = splitTargetNode.build( builder );
  3481. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3482. const component = splitNode.components[ i ];
  3483. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3484. }
  3485. if ( output !== 'void' ) {
  3486. snippet = target;
  3487. }
  3488. } else {
  3489. snippet = `${ target } = ${ source }`;
  3490. if ( output === 'void' || sourceType === 'void' ) {
  3491. builder.addLineFlowCode( snippet, this );
  3492. if ( output !== 'void' ) {
  3493. snippet = target;
  3494. }
  3495. }
  3496. }
  3497. nodeData.initialized = true;
  3498. return builder.format( snippet, targetType, output );
  3499. }
  3500. }
  3501. /**
  3502. * TSL function for creating an assign node.
  3503. *
  3504. * @tsl
  3505. * @function
  3506. * @param {Node} targetNode - The target node.
  3507. * @param {Node} sourceNode - The source type.
  3508. * @returns {AssignNode}
  3509. */
  3510. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3511. addMethodChaining( 'assign', assign );
  3512. /**
  3513. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3514. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3515. * this logic.
  3516. *
  3517. * @augments TempNode
  3518. */
  3519. class FunctionCallNode extends TempNode {
  3520. static get type() {
  3521. return 'FunctionCallNode';
  3522. }
  3523. /**
  3524. * Constructs a new function call node.
  3525. *
  3526. * @param {?FunctionNode} functionNode - The function node.
  3527. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3528. */
  3529. constructor( functionNode = null, parameters = {} ) {
  3530. super();
  3531. /**
  3532. * The function node.
  3533. *
  3534. * @type {?FunctionNode}
  3535. * @default null
  3536. */
  3537. this.functionNode = functionNode;
  3538. /**
  3539. * The parameters of the function call.
  3540. *
  3541. * @type {Object<string, Node>}
  3542. * @default {}
  3543. */
  3544. this.parameters = parameters;
  3545. }
  3546. /**
  3547. * Sets the parameters of the function call node.
  3548. *
  3549. * @param {Object<string, Node>} parameters - The parameters to set.
  3550. * @return {FunctionCallNode} A reference to this node.
  3551. */
  3552. setParameters( parameters ) {
  3553. this.parameters = parameters;
  3554. return this;
  3555. }
  3556. /**
  3557. * Returns the parameters of the function call node.
  3558. *
  3559. * @return {Object<string, Node>} The parameters of this node.
  3560. */
  3561. getParameters() {
  3562. return this.parameters;
  3563. }
  3564. getNodeType( builder ) {
  3565. return this.functionNode.getNodeType( builder );
  3566. }
  3567. generate( builder ) {
  3568. const params = [];
  3569. const functionNode = this.functionNode;
  3570. const inputs = functionNode.getInputs( builder );
  3571. const parameters = this.parameters;
  3572. const generateInput = ( node, inputNode ) => {
  3573. const type = inputNode.type;
  3574. const pointer = type === 'pointer';
  3575. let output;
  3576. if ( pointer ) output = '&' + node.build( builder );
  3577. else output = node.build( builder, type );
  3578. return output;
  3579. };
  3580. if ( Array.isArray( parameters ) ) {
  3581. if ( parameters.length > inputs.length ) {
  3582. console.error( 'THREE.TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3583. parameters.length = inputs.length;
  3584. } else if ( parameters.length < inputs.length ) {
  3585. console.error( 'THREE.TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3586. while ( parameters.length < inputs.length ) {
  3587. parameters.push( float( 0 ) );
  3588. }
  3589. }
  3590. for ( let i = 0; i < parameters.length; i ++ ) {
  3591. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3592. }
  3593. } else {
  3594. for ( const inputNode of inputs ) {
  3595. const node = parameters[ inputNode.name ];
  3596. if ( node !== undefined ) {
  3597. params.push( generateInput( node, inputNode ) );
  3598. } else {
  3599. console.error( `THREE.TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3600. params.push( generateInput( float( 0 ), inputNode ) );
  3601. }
  3602. }
  3603. }
  3604. const functionName = functionNode.build( builder, 'property' );
  3605. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3606. }
  3607. }
  3608. const call = ( func, ...params ) => {
  3609. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3610. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3611. };
  3612. addMethodChaining( 'call', call );
  3613. const _vectorOperators = {
  3614. '==': 'equal',
  3615. '!=': 'notEqual',
  3616. '<': 'lessThan',
  3617. '>': 'greaterThan',
  3618. '<=': 'lessThanEqual',
  3619. '>=': 'greaterThanEqual',
  3620. '%': 'mod'
  3621. };
  3622. /**
  3623. * This node represents basic mathematical and logical operations like addition,
  3624. * subtraction or comparisons (e.g. `equal()`).
  3625. *
  3626. * @augments TempNode
  3627. */
  3628. class OperatorNode extends TempNode {
  3629. static get type() {
  3630. return 'OperatorNode';
  3631. }
  3632. /**
  3633. * Constructs a new operator node.
  3634. *
  3635. * @param {string} op - The operator.
  3636. * @param {Node} aNode - The first input.
  3637. * @param {Node} bNode - The second input.
  3638. * @param {...Node} params - Additional input parameters.
  3639. */
  3640. constructor( op, aNode, bNode, ...params ) {
  3641. super();
  3642. if ( params.length > 0 ) {
  3643. let finalOp = new OperatorNode( op, aNode, bNode );
  3644. for ( let i = 0; i < params.length - 1; i ++ ) {
  3645. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3646. }
  3647. aNode = finalOp;
  3648. bNode = params[ params.length - 1 ];
  3649. }
  3650. /**
  3651. * The operator.
  3652. *
  3653. * @type {string}
  3654. */
  3655. this.op = op;
  3656. /**
  3657. * The first input.
  3658. *
  3659. * @type {Node}
  3660. */
  3661. this.aNode = aNode;
  3662. /**
  3663. * The second input.
  3664. *
  3665. * @type {Node}
  3666. */
  3667. this.bNode = bNode;
  3668. /**
  3669. * This flag can be used for type testing.
  3670. *
  3671. * @type {boolean}
  3672. * @readonly
  3673. * @default true
  3674. */
  3675. this.isOperatorNode = true;
  3676. }
  3677. /**
  3678. * Returns the operator method name.
  3679. *
  3680. * @param {NodeBuilder} builder - The current node builder.
  3681. * @param {string} output - The output type.
  3682. * @returns {string} The operator method name.
  3683. */
  3684. getOperatorMethod( builder, output ) {
  3685. return builder.getMethod( _vectorOperators[ this.op ], output );
  3686. }
  3687. /**
  3688. * This method is overwritten since the node type is inferred from the operator
  3689. * and the input node types.
  3690. *
  3691. * @param {NodeBuilder} builder - The current node builder.
  3692. * @return {string} The node type.
  3693. */
  3694. getNodeType( builder ) {
  3695. const op = this.op;
  3696. const aNode = this.aNode;
  3697. const bNode = this.bNode;
  3698. const typeA = aNode.getNodeType( builder );
  3699. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3700. if ( typeA === 'void' || typeB === 'void' ) {
  3701. return 'void';
  3702. } else if ( op === '%' ) {
  3703. return typeA;
  3704. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3705. return builder.getIntegerType( typeA );
  3706. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3707. return 'bool';
  3708. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3709. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3710. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3711. } else {
  3712. // Handle matrix operations
  3713. if ( builder.isMatrix( typeA ) ) {
  3714. if ( typeB === 'float' ) {
  3715. return typeA; // matrix * scalar = matrix
  3716. } else if ( builder.isVector( typeB ) ) {
  3717. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3718. } else if ( builder.isMatrix( typeB ) ) {
  3719. return typeA; // matrix * matrix
  3720. }
  3721. } else if ( builder.isMatrix( typeB ) ) {
  3722. if ( typeA === 'float' ) {
  3723. return typeB; // scalar * matrix = matrix
  3724. } else if ( builder.isVector( typeA ) ) {
  3725. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3726. }
  3727. }
  3728. // Handle non-matrix cases
  3729. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3730. // anytype x anytype: use the greater length vector
  3731. return typeB;
  3732. }
  3733. return typeA;
  3734. }
  3735. }
  3736. generate( builder, output ) {
  3737. const op = this.op;
  3738. const { aNode, bNode } = this;
  3739. const type = this.getNodeType( builder );
  3740. let typeA = null;
  3741. let typeB = null;
  3742. if ( type !== 'void' ) {
  3743. typeA = aNode.getNodeType( builder );
  3744. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3745. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3746. if ( builder.isVector( typeA ) ) {
  3747. typeB = typeA;
  3748. } else if ( builder.isVector( typeB ) ) {
  3749. typeA = typeB;
  3750. } else if ( typeA !== typeB ) {
  3751. typeA = typeB = 'float';
  3752. }
  3753. } else if ( op === '>>' || op === '<<' ) {
  3754. typeA = type;
  3755. typeB = builder.changeComponentType( typeB, 'uint' );
  3756. } else if ( op === '%' ) {
  3757. typeA = type;
  3758. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3759. } else if ( builder.isMatrix( typeA ) ) {
  3760. if ( typeB === 'float' ) {
  3761. // Keep matrix type for typeA, but ensure typeB stays float
  3762. typeB = 'float';
  3763. } else if ( builder.isVector( typeB ) ) {
  3764. // matrix x vector
  3765. typeB = builder.getVectorFromMatrix( typeA );
  3766. } else if ( builder.isMatrix( typeB ) ) ; else {
  3767. typeA = typeB = type;
  3768. }
  3769. } else if ( builder.isMatrix( typeB ) ) {
  3770. if ( typeA === 'float' ) {
  3771. // Keep matrix type for typeB, but ensure typeA stays float
  3772. typeA = 'float';
  3773. } else if ( builder.isVector( typeA ) ) {
  3774. // vector x matrix
  3775. typeA = builder.getVectorFromMatrix( typeB );
  3776. } else {
  3777. typeA = typeB = type;
  3778. }
  3779. } else {
  3780. // anytype x anytype
  3781. typeA = typeB = type;
  3782. }
  3783. } else {
  3784. typeA = typeB = type;
  3785. }
  3786. const a = aNode.build( builder, typeA );
  3787. const b = bNode ? bNode.build( builder, typeB ) : null;
  3788. const fnOpSnippet = builder.getFunctionOperator( op );
  3789. if ( output !== 'void' ) {
  3790. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3791. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3792. if ( isGLSL ) {
  3793. if ( builder.isVector( typeA ) ) {
  3794. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3795. } else {
  3796. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3797. }
  3798. } else {
  3799. // WGSL
  3800. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3801. }
  3802. } else if ( op === '%' ) {
  3803. if ( builder.isInteger( typeB ) ) {
  3804. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3805. } else {
  3806. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3807. }
  3808. } else if ( op === '!' || op === '~' ) {
  3809. return builder.format( `(${op}${a})`, typeA, output );
  3810. } else if ( fnOpSnippet ) {
  3811. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3812. } else {
  3813. // Handle matrix operations
  3814. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3815. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3816. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3817. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3818. } else {
  3819. let snippet = `( ${ a } ${ op } ${ b } )`;
  3820. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  3821. snippet = `all${ snippet }`;
  3822. }
  3823. return builder.format( snippet, type, output );
  3824. }
  3825. }
  3826. } else if ( typeA !== 'void' ) {
  3827. if ( fnOpSnippet ) {
  3828. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3829. } else {
  3830. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3831. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3832. } else {
  3833. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3834. }
  3835. }
  3836. }
  3837. }
  3838. serialize( data ) {
  3839. super.serialize( data );
  3840. data.op = this.op;
  3841. }
  3842. deserialize( data ) {
  3843. super.deserialize( data );
  3844. this.op = data.op;
  3845. }
  3846. }
  3847. /**
  3848. * Returns the addition of two or more value.
  3849. *
  3850. * @tsl
  3851. * @function
  3852. * @param {Node} a - The first input.
  3853. * @param {Node} b - The second input.
  3854. * @param {...Node} params - Additional input parameters.
  3855. * @returns {OperatorNode}
  3856. */
  3857. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  3858. /**
  3859. * Returns the subtraction of two or more value.
  3860. *
  3861. * @tsl
  3862. * @function
  3863. * @param {Node} a - The first input.
  3864. * @param {Node} b - The second input.
  3865. * @param {...Node} params - Additional input parameters.
  3866. * @returns {OperatorNode}
  3867. */
  3868. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  3869. /**
  3870. * Returns the multiplication of two or more value.
  3871. *
  3872. * @tsl
  3873. * @function
  3874. * @param {Node} a - The first input.
  3875. * @param {Node} b - The second input.
  3876. * @param {...Node} params - Additional input parameters.
  3877. * @returns {OperatorNode}
  3878. */
  3879. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  3880. /**
  3881. * Returns the division of two or more value.
  3882. *
  3883. * @tsl
  3884. * @function
  3885. * @param {Node} a - The first input.
  3886. * @param {Node} b - The second input.
  3887. * @param {...Node} params - Additional input parameters.
  3888. * @returns {OperatorNode}
  3889. */
  3890. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  3891. /**
  3892. * Computes the remainder of dividing the first node by the second one.
  3893. *
  3894. * @tsl
  3895. * @function
  3896. * @param {Node} a - The first input.
  3897. * @param {Node} b - The second input.
  3898. * @returns {OperatorNode}
  3899. */
  3900. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  3901. /**
  3902. * Checks if two nodes are equal.
  3903. *
  3904. * @tsl
  3905. * @function
  3906. * @param {Node} a - The first input.
  3907. * @param {Node} b - The second input.
  3908. * @returns {OperatorNode}
  3909. */
  3910. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  3911. /**
  3912. * Checks if two nodes are not equal.
  3913. *
  3914. * @tsl
  3915. * @function
  3916. * @param {Node} a - The first input.
  3917. * @param {Node} b - The second input.
  3918. * @returns {OperatorNode}
  3919. */
  3920. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  3921. /**
  3922. * Checks if the first node is less than the second.
  3923. *
  3924. * @tsl
  3925. * @function
  3926. * @param {Node} a - The first input.
  3927. * @param {Node} b - The second input.
  3928. * @returns {OperatorNode}
  3929. */
  3930. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  3931. /**
  3932. * Checks if the first node is greater than the second.
  3933. *
  3934. * @tsl
  3935. * @function
  3936. * @param {Node} a - The first input.
  3937. * @param {Node} b - The second input.
  3938. * @returns {OperatorNode}
  3939. */
  3940. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  3941. /**
  3942. * Checks if the first node is less than or equal to the second.
  3943. *
  3944. * @tsl
  3945. * @function
  3946. * @param {Node} a - The first input.
  3947. * @param {Node} b - The second input.
  3948. * @returns {OperatorNode}
  3949. */
  3950. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  3951. /**
  3952. * Checks if the first node is greater than or equal to the second.
  3953. *
  3954. * @tsl
  3955. * @function
  3956. * @param {Node} a - The first input.
  3957. * @param {Node} b - The second input.
  3958. * @returns {OperatorNode}
  3959. */
  3960. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  3961. /**
  3962. * Performs a logical AND operation on multiple nodes.
  3963. *
  3964. * @tsl
  3965. * @function
  3966. * @param {...Node} nodes - The input nodes to be combined using AND.
  3967. * @returns {OperatorNode}
  3968. */
  3969. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  3970. /**
  3971. * Performs a logical OR operation on multiple nodes.
  3972. *
  3973. * @tsl
  3974. * @function
  3975. * @param {...Node} nodes - The input nodes to be combined using OR.
  3976. * @returns {OperatorNode}
  3977. */
  3978. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  3979. /**
  3980. * Performs logical NOT on a node.
  3981. *
  3982. * @tsl
  3983. * @function
  3984. * @param {Node} value - The value.
  3985. * @returns {OperatorNode}
  3986. */
  3987. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  3988. /**
  3989. * Performs logical XOR on two nodes.
  3990. *
  3991. * @tsl
  3992. * @function
  3993. * @param {Node} a - The first input.
  3994. * @param {Node} b - The second input.
  3995. * @returns {OperatorNode}
  3996. */
  3997. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  3998. /**
  3999. * Performs bitwise AND on two nodes.
  4000. *
  4001. * @tsl
  4002. * @function
  4003. * @param {Node} a - The first input.
  4004. * @param {Node} b - The second input.
  4005. * @returns {OperatorNode}
  4006. */
  4007. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4008. /**
  4009. * Performs bitwise NOT on a node.
  4010. *
  4011. * @tsl
  4012. * @function
  4013. * @param {Node} a - The first input.
  4014. * @param {Node} b - The second input.
  4015. * @returns {OperatorNode}
  4016. */
  4017. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 2 ).setName( 'bitNot' );
  4018. /**
  4019. * Performs bitwise OR on two nodes.
  4020. *
  4021. * @tsl
  4022. * @function
  4023. * @param {Node} a - The first input.
  4024. * @param {Node} b - The second input.
  4025. * @returns {OperatorNode}
  4026. */
  4027. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4028. /**
  4029. * Performs bitwise XOR on two nodes.
  4030. *
  4031. * @tsl
  4032. * @function
  4033. * @param {Node} a - The first input.
  4034. * @param {Node} b - The second input.
  4035. * @returns {OperatorNode}
  4036. */
  4037. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4038. /**
  4039. * Shifts a node to the left.
  4040. *
  4041. * @tsl
  4042. * @function
  4043. * @param {Node} a - The node to shift.
  4044. * @param {Node} b - The value to shift.
  4045. * @returns {OperatorNode}
  4046. */
  4047. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4048. /**
  4049. * Shifts a node to the right.
  4050. *
  4051. * @tsl
  4052. * @function
  4053. * @param {Node} a - The node to shift.
  4054. * @param {Node} b - The value to shift.
  4055. * @returns {OperatorNode}
  4056. */
  4057. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4058. /**
  4059. * Increments a node by 1.
  4060. *
  4061. * @tsl
  4062. * @function
  4063. * @param {Node} a - The node to increment.
  4064. * @returns {OperatorNode}
  4065. */
  4066. const incrementBefore = Fn( ( [ a ] ) => {
  4067. a.addAssign( 1 );
  4068. return a;
  4069. } );
  4070. /**
  4071. * Decrements a node by 1.
  4072. *
  4073. * @tsl
  4074. * @function
  4075. * @param {Node} a - The node to decrement.
  4076. * @returns {OperatorNode}
  4077. */
  4078. const decrementBefore = Fn( ( [ a ] ) => {
  4079. a.subAssign( 1 );
  4080. return a;
  4081. } );
  4082. /**
  4083. * Increments a node by 1 and returns the previous value.
  4084. *
  4085. * @tsl
  4086. * @function
  4087. * @param {Node} a - The node to increment.
  4088. * @returns {OperatorNode}
  4089. */
  4090. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4091. const temp = int( a ).toConst();
  4092. a.addAssign( 1 );
  4093. return temp;
  4094. } );
  4095. /**
  4096. * Decrements a node by 1 and returns the previous value.
  4097. *
  4098. * @tsl
  4099. * @function
  4100. * @param {Node} a - The node to decrement.
  4101. * @returns {OperatorNode}
  4102. */
  4103. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4104. const temp = int( a ).toConst();
  4105. a.subAssign( 1 );
  4106. return temp;
  4107. } );
  4108. addMethodChaining( 'add', add );
  4109. addMethodChaining( 'sub', sub );
  4110. addMethodChaining( 'mul', mul );
  4111. addMethodChaining( 'div', div );
  4112. addMethodChaining( 'mod', mod );
  4113. addMethodChaining( 'equal', equal );
  4114. addMethodChaining( 'notEqual', notEqual );
  4115. addMethodChaining( 'lessThan', lessThan );
  4116. addMethodChaining( 'greaterThan', greaterThan );
  4117. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4118. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4119. addMethodChaining( 'and', and );
  4120. addMethodChaining( 'or', or );
  4121. addMethodChaining( 'not', not );
  4122. addMethodChaining( 'xor', xor );
  4123. addMethodChaining( 'bitAnd', bitAnd );
  4124. addMethodChaining( 'bitNot', bitNot );
  4125. addMethodChaining( 'bitOr', bitOr );
  4126. addMethodChaining( 'bitXor', bitXor );
  4127. addMethodChaining( 'shiftLeft', shiftLeft );
  4128. addMethodChaining( 'shiftRight', shiftRight );
  4129. addMethodChaining( 'incrementBefore', incrementBefore );
  4130. addMethodChaining( 'decrementBefore', decrementBefore );
  4131. addMethodChaining( 'increment', increment );
  4132. addMethodChaining( 'decrement', decrement );
  4133. /**
  4134. * @tsl
  4135. * @function
  4136. * @deprecated since r175. Use {@link mod} instead.
  4137. *
  4138. * @param {Node} a - The first input.
  4139. * @param {Node} b - The second input.
  4140. * @returns {OperatorNode}
  4141. */
  4142. const modInt = ( a, b ) => { // @deprecated, r175
  4143. console.warn( 'THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4144. return mod( int( a ), int( b ) );
  4145. };
  4146. addMethodChaining( 'modInt', modInt );
  4147. /**
  4148. * This node represents a variety of mathematical methods available in shaders.
  4149. * They are divided into three categories:
  4150. *
  4151. * - Methods with one input like `sin`, `cos` or `normalize`.
  4152. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4153. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4154. *
  4155. * @augments TempNode
  4156. */
  4157. class MathNode extends TempNode {
  4158. static get type() {
  4159. return 'MathNode';
  4160. }
  4161. /**
  4162. * Constructs a new math node.
  4163. *
  4164. * @param {string} method - The method name.
  4165. * @param {Node} aNode - The first input.
  4166. * @param {?Node} [bNode=null] - The second input.
  4167. * @param {?Node} [cNode=null] - The third input.
  4168. */
  4169. constructor( method, aNode, bNode = null, cNode = null ) {
  4170. super();
  4171. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4172. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4173. let finalOp = new MathNode( method, aNode, bNode );
  4174. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4175. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4176. }
  4177. aNode = finalOp;
  4178. bNode = arguments[ arguments.length - 1 ];
  4179. cNode = null;
  4180. }
  4181. /**
  4182. * The method name.
  4183. *
  4184. * @type {string}
  4185. */
  4186. this.method = method;
  4187. /**
  4188. * The first input.
  4189. *
  4190. * @type {Node}
  4191. */
  4192. this.aNode = aNode;
  4193. /**
  4194. * The second input.
  4195. *
  4196. * @type {?Node}
  4197. * @default null
  4198. */
  4199. this.bNode = bNode;
  4200. /**
  4201. * The third input.
  4202. *
  4203. * @type {?Node}
  4204. * @default null
  4205. */
  4206. this.cNode = cNode;
  4207. /**
  4208. * This flag can be used for type testing.
  4209. *
  4210. * @type {boolean}
  4211. * @readonly
  4212. * @default true
  4213. */
  4214. this.isMathNode = true;
  4215. }
  4216. /**
  4217. * The input type is inferred from the node types of the input nodes.
  4218. *
  4219. * @param {NodeBuilder} builder - The current node builder.
  4220. * @return {string} The input type.
  4221. */
  4222. getInputType( builder ) {
  4223. const aType = this.aNode.getNodeType( builder );
  4224. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4225. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4226. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4227. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4228. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4229. if ( aLen > bLen && aLen > cLen ) {
  4230. return aType;
  4231. } else if ( bLen > cLen ) {
  4232. return bType;
  4233. } else if ( cLen > aLen ) {
  4234. return cType;
  4235. }
  4236. return aType;
  4237. }
  4238. /**
  4239. * The selected method as well as the input type determine the node type of this node.
  4240. *
  4241. * @param {NodeBuilder} builder - The current node builder.
  4242. * @return {string} The node type.
  4243. */
  4244. getNodeType( builder ) {
  4245. const method = this.method;
  4246. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4247. return 'float';
  4248. } else if ( method === MathNode.CROSS ) {
  4249. return 'vec3';
  4250. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4251. return 'bool';
  4252. } else if ( method === MathNode.EQUALS ) {
  4253. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4254. } else {
  4255. return this.getInputType( builder );
  4256. }
  4257. }
  4258. setup( builder ) {
  4259. const { aNode, bNode, method } = this;
  4260. let outputNode = null;
  4261. if ( method === MathNode.ONE_MINUS ) {
  4262. outputNode = sub( 1.0, aNode );
  4263. } else if ( method === MathNode.RECIPROCAL ) {
  4264. outputNode = div( 1.0, aNode );
  4265. } else if ( method === MathNode.DIFFERENCE ) {
  4266. outputNode = abs( sub( aNode, bNode ) );
  4267. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4268. // dir can be either a direction vector or a normal vector
  4269. // upper-left 3x3 of matrix is assumed to be orthogonal
  4270. let tA = aNode;
  4271. let tB = bNode;
  4272. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4273. tB = vec4( vec3( tB ), 0.0 );
  4274. } else {
  4275. tA = vec4( vec3( tA ), 0.0 );
  4276. }
  4277. const mulNode = mul( tA, tB ).xyz;
  4278. outputNode = normalize( mulNode );
  4279. }
  4280. if ( outputNode !== null ) {
  4281. return outputNode;
  4282. } else {
  4283. return super.setup( builder );
  4284. }
  4285. }
  4286. generate( builder, output ) {
  4287. const properties = builder.getNodeProperties( this );
  4288. if ( properties.outputNode ) {
  4289. return super.generate( builder, output );
  4290. }
  4291. let method = this.method;
  4292. const type = this.getNodeType( builder );
  4293. const inputType = this.getInputType( builder );
  4294. const a = this.aNode;
  4295. const b = this.bNode;
  4296. const c = this.cNode;
  4297. const coordinateSystem = builder.renderer.coordinateSystem;
  4298. if ( method === MathNode.NEGATE ) {
  4299. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4300. } else {
  4301. const params = [];
  4302. if ( method === MathNode.CROSS ) {
  4303. params.push(
  4304. a.build( builder, type ),
  4305. b.build( builder, type )
  4306. );
  4307. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4308. params.push(
  4309. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4310. b.build( builder, inputType )
  4311. );
  4312. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4313. params.push(
  4314. a.build( builder, inputType ),
  4315. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4316. );
  4317. } else if ( method === MathNode.REFRACT ) {
  4318. params.push(
  4319. a.build( builder, inputType ),
  4320. b.build( builder, inputType ),
  4321. c.build( builder, 'float' )
  4322. );
  4323. } else if ( method === MathNode.MIX ) {
  4324. params.push(
  4325. a.build( builder, inputType ),
  4326. b.build( builder, inputType ),
  4327. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4328. );
  4329. } else {
  4330. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4331. method = 'atan2';
  4332. }
  4333. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4334. console.warn( `THREE.TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4335. method = '/*' + method + '*/';
  4336. }
  4337. params.push( a.build( builder, inputType ) );
  4338. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4339. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4340. }
  4341. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4342. }
  4343. }
  4344. serialize( data ) {
  4345. super.serialize( data );
  4346. data.method = this.method;
  4347. }
  4348. deserialize( data ) {
  4349. super.deserialize( data );
  4350. this.method = data.method;
  4351. }
  4352. }
  4353. // 1 input
  4354. MathNode.ALL = 'all';
  4355. MathNode.ANY = 'any';
  4356. MathNode.RADIANS = 'radians';
  4357. MathNode.DEGREES = 'degrees';
  4358. MathNode.EXP = 'exp';
  4359. MathNode.EXP2 = 'exp2';
  4360. MathNode.LOG = 'log';
  4361. MathNode.LOG2 = 'log2';
  4362. MathNode.SQRT = 'sqrt';
  4363. MathNode.INVERSE_SQRT = 'inversesqrt';
  4364. MathNode.FLOOR = 'floor';
  4365. MathNode.CEIL = 'ceil';
  4366. MathNode.NORMALIZE = 'normalize';
  4367. MathNode.FRACT = 'fract';
  4368. MathNode.SIN = 'sin';
  4369. MathNode.COS = 'cos';
  4370. MathNode.TAN = 'tan';
  4371. MathNode.ASIN = 'asin';
  4372. MathNode.ACOS = 'acos';
  4373. MathNode.ATAN = 'atan';
  4374. MathNode.ABS = 'abs';
  4375. MathNode.SIGN = 'sign';
  4376. MathNode.LENGTH = 'length';
  4377. MathNode.NEGATE = 'negate';
  4378. MathNode.ONE_MINUS = 'oneMinus';
  4379. MathNode.DFDX = 'dFdx';
  4380. MathNode.DFDY = 'dFdy';
  4381. MathNode.ROUND = 'round';
  4382. MathNode.RECIPROCAL = 'reciprocal';
  4383. MathNode.TRUNC = 'trunc';
  4384. MathNode.FWIDTH = 'fwidth';
  4385. MathNode.TRANSPOSE = 'transpose';
  4386. MathNode.DETERMINANT = 'determinant';
  4387. MathNode.INVERSE = 'inverse';
  4388. // 2 inputs
  4389. MathNode.BITCAST = 'bitcast';
  4390. MathNode.EQUALS = 'equals';
  4391. MathNode.MIN = 'min';
  4392. MathNode.MAX = 'max';
  4393. MathNode.STEP = 'step';
  4394. MathNode.REFLECT = 'reflect';
  4395. MathNode.DISTANCE = 'distance';
  4396. MathNode.DIFFERENCE = 'difference';
  4397. MathNode.DOT = 'dot';
  4398. MathNode.CROSS = 'cross';
  4399. MathNode.POW = 'pow';
  4400. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4401. // 3 inputs
  4402. MathNode.MIX = 'mix';
  4403. MathNode.CLAMP = 'clamp';
  4404. MathNode.REFRACT = 'refract';
  4405. MathNode.SMOOTHSTEP = 'smoothstep';
  4406. MathNode.FACEFORWARD = 'faceforward';
  4407. // 1 inputs
  4408. /**
  4409. * A small value used to handle floating-point precision errors.
  4410. *
  4411. * @tsl
  4412. * @type {Node<float>}
  4413. */
  4414. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4415. /**
  4416. * Represents infinity.
  4417. *
  4418. * @tsl
  4419. * @type {Node<float>}
  4420. */
  4421. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4422. /**
  4423. * Represents PI.
  4424. *
  4425. * @tsl
  4426. * @type {Node<float>}
  4427. */
  4428. const PI = /*@__PURE__*/ float( Math.PI );
  4429. /**
  4430. * Represents PI * 2.
  4431. *
  4432. * @tsl
  4433. * @type {Node<float>}
  4434. */
  4435. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  4436. /**
  4437. * Returns `true` if all components of `x` are `true`.
  4438. *
  4439. * @tsl
  4440. * @function
  4441. * @param {Node | number} x - The parameter.
  4442. * @returns {Node<bool>}
  4443. */
  4444. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4445. /**
  4446. * Returns `true` if any components of `x` are `true`.
  4447. *
  4448. * @tsl
  4449. * @function
  4450. * @param {Node | number} x - The parameter.
  4451. * @returns {Node<bool>}
  4452. */
  4453. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4454. /**
  4455. * Converts a quantity in degrees to radians.
  4456. *
  4457. * @tsl
  4458. * @function
  4459. * @param {Node | number} x - The input in degrees.
  4460. * @returns {Node}
  4461. */
  4462. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4463. /**
  4464. * Convert a quantity in radians to degrees.
  4465. *
  4466. * @tsl
  4467. * @function
  4468. * @param {Node | number} x - The input in radians.
  4469. * @returns {Node}
  4470. */
  4471. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4472. /**
  4473. * Returns the natural exponentiation of the parameter.
  4474. *
  4475. * @tsl
  4476. * @function
  4477. * @param {Node | number} x - The parameter.
  4478. * @returns {Node}
  4479. */
  4480. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4481. /**
  4482. * Returns 2 raised to the power of the parameter.
  4483. *
  4484. * @tsl
  4485. * @function
  4486. * @param {Node | number} x - The parameter.
  4487. * @returns {Node}
  4488. */
  4489. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4490. /**
  4491. * Returns the natural logarithm of the parameter.
  4492. *
  4493. * @tsl
  4494. * @function
  4495. * @param {Node | number} x - The parameter.
  4496. * @returns {Node}
  4497. */
  4498. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4499. /**
  4500. * Returns the base 2 logarithm of the parameter.
  4501. *
  4502. * @tsl
  4503. * @function
  4504. * @param {Node | number} x - The parameter.
  4505. * @returns {Node}
  4506. */
  4507. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4508. /**
  4509. * Returns the square root of the parameter.
  4510. *
  4511. * @tsl
  4512. * @function
  4513. * @param {Node | number} x - The parameter.
  4514. * @returns {Node}
  4515. */
  4516. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4517. /**
  4518. * Returns the inverse of the square root of the parameter.
  4519. *
  4520. * @tsl
  4521. * @function
  4522. * @param {Node | number} x - The parameter.
  4523. * @returns {Node}
  4524. */
  4525. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4526. /**
  4527. * Finds the nearest integer less than or equal to the parameter.
  4528. *
  4529. * @tsl
  4530. * @function
  4531. * @param {Node | number} x - The parameter.
  4532. * @returns {Node}
  4533. */
  4534. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4535. /**
  4536. * Finds the nearest integer that is greater than or equal to the parameter.
  4537. *
  4538. * @tsl
  4539. * @function
  4540. * @param {Node | number} x - The parameter.
  4541. * @returns {Node}
  4542. */
  4543. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4544. /**
  4545. * Calculates the unit vector in the same direction as the original vector.
  4546. *
  4547. * @tsl
  4548. * @function
  4549. * @param {Node} x - The input vector.
  4550. * @returns {Node}
  4551. */
  4552. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4553. /**
  4554. * Computes the fractional part of the parameter.
  4555. *
  4556. * @tsl
  4557. * @function
  4558. * @param {Node | number} x - The parameter.
  4559. * @returns {Node}
  4560. */
  4561. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4562. /**
  4563. * Returns the sine of the parameter.
  4564. *
  4565. * @tsl
  4566. * @function
  4567. * @param {Node | number} x - The parameter.
  4568. * @returns {Node}
  4569. */
  4570. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4571. /**
  4572. * Returns the cosine of the parameter.
  4573. *
  4574. * @tsl
  4575. * @function
  4576. * @param {Node | number} x - The parameter.
  4577. * @returns {Node}
  4578. */
  4579. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4580. /**
  4581. * Returns the tangent of the parameter.
  4582. *
  4583. * @tsl
  4584. * @function
  4585. * @param {Node | number} x - The parameter.
  4586. * @returns {Node}
  4587. */
  4588. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4589. /**
  4590. * Returns the arcsine of the parameter.
  4591. *
  4592. * @tsl
  4593. * @function
  4594. * @param {Node | number} x - The parameter.
  4595. * @returns {Node}
  4596. */
  4597. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4598. /**
  4599. * Returns the arccosine of the parameter.
  4600. *
  4601. * @tsl
  4602. * @function
  4603. * @param {Node | number} x - The parameter.
  4604. * @returns {Node}
  4605. */
  4606. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4607. /**
  4608. * Returns the arc-tangent of the parameter.
  4609. * If two parameters are provided, the result is `atan2(y/x)`.
  4610. *
  4611. * @tsl
  4612. * @function
  4613. * @param {Node | number} y - The y parameter.
  4614. * @param {?(Node | number)} x - The x parameter.
  4615. * @returns {Node}
  4616. */
  4617. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4618. /**
  4619. * Returns the absolute value of the parameter.
  4620. *
  4621. * @tsl
  4622. * @function
  4623. * @param {Node | number} x - The parameter.
  4624. * @returns {Node}
  4625. */
  4626. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4627. /**
  4628. * Extracts the sign of the parameter.
  4629. *
  4630. * @tsl
  4631. * @function
  4632. * @param {Node | number} x - The parameter.
  4633. * @returns {Node}
  4634. */
  4635. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4636. /**
  4637. * Calculates the length of a vector.
  4638. *
  4639. * @tsl
  4640. * @function
  4641. * @param {Node} x - The parameter.
  4642. * @returns {Node<float>}
  4643. */
  4644. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4645. /**
  4646. * Negates the value of the parameter (-x).
  4647. *
  4648. * @tsl
  4649. * @function
  4650. * @param {Node | number} x - The parameter.
  4651. * @returns {Node}
  4652. */
  4653. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4654. /**
  4655. * Return `1` minus the parameter.
  4656. *
  4657. * @tsl
  4658. * @function
  4659. * @param {Node | number} x - The parameter.
  4660. * @returns {Node}
  4661. */
  4662. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4663. /**
  4664. * Returns the partial derivative of the parameter with respect to x.
  4665. *
  4666. * @tsl
  4667. * @function
  4668. * @param {Node | number} x - The parameter.
  4669. * @returns {Node}
  4670. */
  4671. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4672. /**
  4673. * Returns the partial derivative of the parameter with respect to y.
  4674. *
  4675. * @tsl
  4676. * @function
  4677. * @param {Node | number} x - The parameter.
  4678. * @returns {Node}
  4679. */
  4680. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4681. /**
  4682. * Rounds the parameter to the nearest integer.
  4683. *
  4684. * @tsl
  4685. * @function
  4686. * @param {Node | number} x - The parameter.
  4687. * @returns {Node}
  4688. */
  4689. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4690. /**
  4691. * Returns the reciprocal of the parameter `(1/x)`.
  4692. *
  4693. * @tsl
  4694. * @function
  4695. * @param {Node | number} x - The parameter.
  4696. * @returns {Node}
  4697. */
  4698. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4699. /**
  4700. * Truncates the parameter, removing the fractional part.
  4701. *
  4702. * @tsl
  4703. * @function
  4704. * @param {Node | number} x - The parameter.
  4705. * @returns {Node}
  4706. */
  4707. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4708. /**
  4709. * Returns the sum of the absolute derivatives in x and y.
  4710. *
  4711. * @tsl
  4712. * @function
  4713. * @param {Node | number} x - The parameter.
  4714. * @returns {Node}
  4715. */
  4716. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4717. /**
  4718. * Returns the transpose of a matrix.
  4719. *
  4720. * @tsl
  4721. * @function
  4722. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4723. * @returns {Node}
  4724. */
  4725. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4726. /**
  4727. * Returns the determinant of a matrix.
  4728. *
  4729. * @tsl
  4730. * @function
  4731. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4732. * @returns {Node<float>}
  4733. */
  4734. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  4735. /**
  4736. * Returns the inverse of a matrix.
  4737. *
  4738. * @tsl
  4739. * @function
  4740. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4741. * @returns {Node<mat2|mat3|mat4>}
  4742. */
  4743. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  4744. // 2 inputs
  4745. /**
  4746. * Reinterpret the bit representation of a value in one type as a value in another type.
  4747. *
  4748. * @tsl
  4749. * @function
  4750. * @param {Node | number} x - The parameter.
  4751. * @param {string} y - The new type.
  4752. * @returns {Node}
  4753. */
  4754. const bitcast = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.BITCAST ).setParameterLength( 2 );
  4755. /**
  4756. * Returns `true` if `x` equals `y`.
  4757. *
  4758. * @tsl
  4759. * @function
  4760. * @param {Node | number} x - The first parameter.
  4761. * @param {Node | number} y - The second parameter.
  4762. * @deprecated since r175. Use {@link equal} instead.
  4763. * @returns {Node<bool>}
  4764. */
  4765. const equals = ( x, y ) => { // @deprecated, r172
  4766. console.warn( 'THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4767. return equal( x, y );
  4768. };
  4769. /**
  4770. * Returns the least of the given values.
  4771. *
  4772. * @tsl
  4773. * @function
  4774. * @param {...(Node | number)} values - The values to compare.
  4775. * @returns {Node}
  4776. */
  4777. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4778. /**
  4779. * Returns the greatest of the given values.
  4780. *
  4781. * @tsl
  4782. * @function
  4783. * @param {...(Node | number)} values - The values to compare.
  4784. * @returns {Node}
  4785. */
  4786. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4787. /**
  4788. * Generate a step function by comparing two values.
  4789. *
  4790. * @tsl
  4791. * @function
  4792. * @param {Node | number} x - The y parameter.
  4793. * @param {Node | number} y - The x parameter.
  4794. * @returns {Node}
  4795. */
  4796. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4797. /**
  4798. * Calculates the reflection direction for an incident vector.
  4799. *
  4800. * @tsl
  4801. * @function
  4802. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4803. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4804. * @returns {Node<vec2|vec3|vec4>}
  4805. */
  4806. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  4807. /**
  4808. * Calculates the distance between two points.
  4809. *
  4810. * @tsl
  4811. * @function
  4812. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4813. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4814. * @returns {Node<float>}
  4815. */
  4816. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  4817. /**
  4818. * Calculates the absolute difference between two values.
  4819. *
  4820. * @tsl
  4821. * @function
  4822. * @param {Node | number} x - The first parameter.
  4823. * @param {Node | number} y - The second parameter.
  4824. * @returns {Node}
  4825. */
  4826. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  4827. /**
  4828. * Calculates the dot product of two vectors.
  4829. *
  4830. * @tsl
  4831. * @function
  4832. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4833. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4834. * @returns {Node<float>}
  4835. */
  4836. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  4837. /**
  4838. * Calculates the cross product of two vectors.
  4839. *
  4840. * @tsl
  4841. * @function
  4842. * @param {Node<vec2|vec3>} x - The first vector.
  4843. * @param {Node<vec2|vec3>} y - The second vector.
  4844. * @returns {Node<float|vec3>}
  4845. */
  4846. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  4847. /**
  4848. * Return the value of the first parameter raised to the power of the second one.
  4849. *
  4850. * @tsl
  4851. * @function
  4852. * @param {Node | number} x - The first parameter.
  4853. * @param {Node | number} y - The second parameter.
  4854. * @returns {Node}
  4855. */
  4856. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  4857. /**
  4858. * Returns the square of the parameter.
  4859. *
  4860. * @tsl
  4861. * @function
  4862. * @param {Node | number} x - The first parameter.
  4863. * @returns {Node}
  4864. */
  4865. const pow2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW, 2 ).setParameterLength( 1 );
  4866. /**
  4867. * Returns the cube of the parameter.
  4868. *
  4869. * @tsl
  4870. * @function
  4871. * @param {Node | number} x - The first parameter.
  4872. * @returns {Node}
  4873. */
  4874. const pow3 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW, 3 ).setParameterLength( 1 );
  4875. /**
  4876. * Returns the fourth power of the parameter.
  4877. *
  4878. * @tsl
  4879. * @function
  4880. * @param {Node | number} x - The first parameter.
  4881. * @returns {Node}
  4882. */
  4883. const pow4 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW, 4 ).setParameterLength( 1 );
  4884. /**
  4885. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4886. *
  4887. * @tsl
  4888. * @function
  4889. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4890. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4891. * @returns {Node}
  4892. */
  4893. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  4894. /**
  4895. * Returns the cube root of a number.
  4896. *
  4897. * @tsl
  4898. * @function
  4899. * @param {Node | number} a - The first parameter.
  4900. * @returns {Node}
  4901. */
  4902. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4903. /**
  4904. * Calculate the squared length of a vector.
  4905. *
  4906. * @tsl
  4907. * @function
  4908. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4909. * @returns {Node<float>}
  4910. */
  4911. const lengthSq = ( a ) => dot( a, a );
  4912. /**
  4913. * Linearly interpolates between two values.
  4914. *
  4915. * @tsl
  4916. * @function
  4917. * @param {Node | number} a - The first parameter.
  4918. * @param {Node | number} b - The second parameter.
  4919. * @param {Node | number} t - The interpolation value.
  4920. * @returns {Node}
  4921. */
  4922. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  4923. /**
  4924. * Constrains a value to lie between two further values.
  4925. *
  4926. * @tsl
  4927. * @function
  4928. * @param {Node | number} value - The value to constrain.
  4929. * @param {Node | number} [low=0] - The lower bound.
  4930. * @param {Node | number} [high=1] - The upper bound.
  4931. * @returns {Node}
  4932. */
  4933. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4934. /**
  4935. * Constrains a value between `0` and `1`.
  4936. *
  4937. * @tsl
  4938. * @function
  4939. * @param {Node | number} value - The value to constrain.
  4940. * @returns {Node}
  4941. */
  4942. const saturate = ( value ) => clamp( value );
  4943. /**
  4944. * Calculates the refraction direction for an incident vector.
  4945. *
  4946. * @tsl
  4947. * @function
  4948. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4949. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4950. * @param {Node<float>} eta - The ratio of indices of refraction.
  4951. * @returns {Node<vec2|vec3|vec4>}
  4952. */
  4953. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  4954. /**
  4955. * Performs a Hermite interpolation between two values.
  4956. *
  4957. * @tsl
  4958. * @function
  4959. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4960. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4961. * @param {Node | number} x - The source value for interpolation.
  4962. * @returns {Node}
  4963. */
  4964. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  4965. /**
  4966. * Returns a vector pointing in the same direction as another.
  4967. *
  4968. * @tsl
  4969. * @function
  4970. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4971. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4972. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4973. * @returns {Node<vec2|vec3|vec4>}
  4974. */
  4975. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  4976. /**
  4977. * Returns a random value for the given uv.
  4978. *
  4979. * @tsl
  4980. * @function
  4981. * @param {Node<vec2>} uv - The uv node.
  4982. * @returns {Node<float>}
  4983. */
  4984. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4985. const a = 12.9898, b = 78.233, c = 43758.5453;
  4986. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4987. return fract( sin( sn ).mul( c ) );
  4988. } );
  4989. /**
  4990. * Alias for `mix()` with a different parameter order.
  4991. *
  4992. * @tsl
  4993. * @function
  4994. * @param {Node | number} t - The interpolation value.
  4995. * @param {Node | number} e1 - The first parameter.
  4996. * @param {Node | number} e2 - The second parameter.
  4997. * @returns {Node}
  4998. */
  4999. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5000. /**
  5001. * Alias for `smoothstep()` with a different parameter order.
  5002. *
  5003. * @tsl
  5004. * @function
  5005. * @param {Node | number} x - The source value for interpolation.
  5006. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5007. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5008. * @returns {Node}
  5009. */
  5010. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5011. /**
  5012. * Alias for `step()` with a different parameter order.
  5013. *
  5014. * @tsl
  5015. * @function
  5016. * @param {Node | number} x - The source value for interpolation.
  5017. * @param {Node | number} edge - The edge value.
  5018. * @returns {Node}
  5019. */
  5020. const stepElement = ( x, edge ) => step( edge, x );
  5021. /**
  5022. * Returns the arc-tangent of the quotient of its parameters.
  5023. *
  5024. * @tsl
  5025. * @function
  5026. * @deprecated since r172. Use {@link atan} instead.
  5027. *
  5028. * @param {Node | number} y - The y parameter.
  5029. * @param {Node | number} x - The x parameter.
  5030. * @returns {Node}
  5031. */
  5032. const atan2 = ( y, x ) => { // @deprecated, r172
  5033. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  5034. return atan( y, x );
  5035. };
  5036. // GLSL alias function
  5037. const faceforward = faceForward;
  5038. const inversesqrt = inverseSqrt;
  5039. // Method chaining
  5040. addMethodChaining( 'all', all );
  5041. addMethodChaining( 'any', any );
  5042. addMethodChaining( 'equals', equals );
  5043. addMethodChaining( 'radians', radians );
  5044. addMethodChaining( 'degrees', degrees );
  5045. addMethodChaining( 'exp', exp );
  5046. addMethodChaining( 'exp2', exp2 );
  5047. addMethodChaining( 'log', log );
  5048. addMethodChaining( 'log2', log2 );
  5049. addMethodChaining( 'sqrt', sqrt );
  5050. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5051. addMethodChaining( 'floor', floor );
  5052. addMethodChaining( 'ceil', ceil );
  5053. addMethodChaining( 'normalize', normalize );
  5054. addMethodChaining( 'fract', fract );
  5055. addMethodChaining( 'sin', sin );
  5056. addMethodChaining( 'cos', cos );
  5057. addMethodChaining( 'tan', tan );
  5058. addMethodChaining( 'asin', asin );
  5059. addMethodChaining( 'acos', acos );
  5060. addMethodChaining( 'atan', atan );
  5061. addMethodChaining( 'abs', abs );
  5062. addMethodChaining( 'sign', sign );
  5063. addMethodChaining( 'length', length );
  5064. addMethodChaining( 'lengthSq', lengthSq );
  5065. addMethodChaining( 'negate', negate );
  5066. addMethodChaining( 'oneMinus', oneMinus );
  5067. addMethodChaining( 'dFdx', dFdx );
  5068. addMethodChaining( 'dFdy', dFdy );
  5069. addMethodChaining( 'round', round );
  5070. addMethodChaining( 'reciprocal', reciprocal );
  5071. addMethodChaining( 'trunc', trunc );
  5072. addMethodChaining( 'fwidth', fwidth );
  5073. addMethodChaining( 'atan2', atan2 );
  5074. addMethodChaining( 'min', min$1 );
  5075. addMethodChaining( 'max', max$1 );
  5076. addMethodChaining( 'step', stepElement );
  5077. addMethodChaining( 'reflect', reflect );
  5078. addMethodChaining( 'distance', distance );
  5079. addMethodChaining( 'dot', dot );
  5080. addMethodChaining( 'cross', cross );
  5081. addMethodChaining( 'pow', pow );
  5082. addMethodChaining( 'pow2', pow2 );
  5083. addMethodChaining( 'pow3', pow3 );
  5084. addMethodChaining( 'pow4', pow4 );
  5085. addMethodChaining( 'transformDirection', transformDirection );
  5086. addMethodChaining( 'mix', mixElement );
  5087. addMethodChaining( 'clamp', clamp );
  5088. addMethodChaining( 'refract', refract );
  5089. addMethodChaining( 'smoothstep', smoothstepElement );
  5090. addMethodChaining( 'faceForward', faceForward );
  5091. addMethodChaining( 'difference', difference );
  5092. addMethodChaining( 'saturate', saturate );
  5093. addMethodChaining( 'cbrt', cbrt );
  5094. addMethodChaining( 'transpose', transpose );
  5095. addMethodChaining( 'determinant', determinant );
  5096. addMethodChaining( 'inverse', inverse );
  5097. addMethodChaining( 'rand', rand );
  5098. /**
  5099. * Represents a logical `if/else` statement. Can be used as an alternative
  5100. * to the `If()`/`Else()` syntax.
  5101. *
  5102. * The corresponding TSL `select()` looks like so:
  5103. * ```js
  5104. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5105. * ```
  5106. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5107. * determine the outcome of the entire statement.
  5108. *
  5109. * @augments Node
  5110. */
  5111. class ConditionalNode extends Node {
  5112. static get type() {
  5113. return 'ConditionalNode';
  5114. }
  5115. /**
  5116. * Constructs a new conditional node.
  5117. *
  5118. * @param {Node} condNode - The node that defines the condition.
  5119. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5120. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5121. */
  5122. constructor( condNode, ifNode, elseNode = null ) {
  5123. super();
  5124. /**
  5125. * The node that defines the condition.
  5126. *
  5127. * @type {Node}
  5128. */
  5129. this.condNode = condNode;
  5130. /**
  5131. * The node that is evaluate when the condition ends up `true`.
  5132. *
  5133. * @type {Node}
  5134. */
  5135. this.ifNode = ifNode;
  5136. /**
  5137. * The node that is evaluate when the condition ends up `false`.
  5138. *
  5139. * @type {?Node}
  5140. * @default null
  5141. */
  5142. this.elseNode = elseNode;
  5143. }
  5144. /**
  5145. * This method is overwritten since the node type is inferred from the if/else
  5146. * nodes.
  5147. *
  5148. * @param {NodeBuilder} builder - The current node builder.
  5149. * @return {string} The node type.
  5150. */
  5151. getNodeType( builder ) {
  5152. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5153. if ( ifNode === undefined ) {
  5154. // fallback setup
  5155. builder.flowBuildStage( this, 'setup' );
  5156. return this.getNodeType( builder );
  5157. }
  5158. const ifType = ifNode.getNodeType( builder );
  5159. if ( elseNode !== null ) {
  5160. const elseType = elseNode.getNodeType( builder );
  5161. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5162. return elseType;
  5163. }
  5164. }
  5165. return ifType;
  5166. }
  5167. setup( builder ) {
  5168. const condNode = this.condNode.cache();
  5169. const ifNode = this.ifNode.cache();
  5170. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  5171. //
  5172. const currentNodeBlock = builder.context.nodeBlock;
  5173. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5174. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5175. //
  5176. const isUniformFlow = builder.context.uniformFlow;
  5177. const properties = builder.getNodeProperties( this );
  5178. properties.condNode = condNode;
  5179. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5180. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5181. }
  5182. generate( builder, output ) {
  5183. const type = this.getNodeType( builder );
  5184. const nodeData = builder.getDataFromNode( this );
  5185. if ( nodeData.nodeProperty !== undefined ) {
  5186. return nodeData.nodeProperty;
  5187. }
  5188. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5189. const functionNode = builder.currentFunctionNode;
  5190. const needsOutput = output !== 'void';
  5191. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5192. nodeData.nodeProperty = nodeProperty;
  5193. const nodeSnippet = condNode.build( builder, 'bool' );
  5194. const isUniformFlow = builder.context.uniformFlow;
  5195. if ( isUniformFlow && elseNode !== null ) {
  5196. const ifSnippet = ifNode.build( builder, type );
  5197. const elseSnippet = elseNode.build( builder, type );
  5198. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5199. // TODO: If node property already exists return something else
  5200. return builder.format( mathSnippet, type, output );
  5201. }
  5202. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5203. let ifSnippet = ifNode.build( builder, type );
  5204. if ( ifSnippet ) {
  5205. if ( needsOutput ) {
  5206. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5207. } else {
  5208. ifSnippet = 'return ' + ifSnippet + ';';
  5209. if ( functionNode === null ) {
  5210. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5211. ifSnippet = '// ' + ifSnippet;
  5212. }
  5213. }
  5214. }
  5215. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5216. if ( elseNode !== null ) {
  5217. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5218. let elseSnippet = elseNode.build( builder, type );
  5219. if ( elseSnippet ) {
  5220. if ( needsOutput ) {
  5221. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5222. } else {
  5223. elseSnippet = 'return ' + elseSnippet + ';';
  5224. if ( functionNode === null ) {
  5225. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5226. elseSnippet = '// ' + elseSnippet;
  5227. }
  5228. }
  5229. }
  5230. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5231. } else {
  5232. builder.addFlowCode( '\n\n' );
  5233. }
  5234. return builder.format( nodeProperty, type, output );
  5235. }
  5236. }
  5237. /**
  5238. * TSL function for creating a conditional node.
  5239. *
  5240. * @tsl
  5241. * @function
  5242. * @param {Node} condNode - The node that defines the condition.
  5243. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5244. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5245. * @returns {ConditionalNode}
  5246. */
  5247. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5248. addMethodChaining( 'select', select );
  5249. /**
  5250. * This node can be used as a context management component for another node.
  5251. * {@link NodeBuilder} performs its node building process in a specific context and
  5252. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5253. *
  5254. * ```js
  5255. *node.context( { getUV: () => customCoord } );
  5256. *```
  5257. * @augments Node
  5258. */
  5259. class ContextNode extends Node {
  5260. static get type() {
  5261. return 'ContextNode';
  5262. }
  5263. /**
  5264. * Constructs a new context node.
  5265. *
  5266. * @param {Node} node - The node whose context should be modified.
  5267. * @param {Object} [value={}] - The modified context data.
  5268. */
  5269. constructor( node, value = {} ) {
  5270. super();
  5271. /**
  5272. * This flag can be used for type testing.
  5273. *
  5274. * @type {boolean}
  5275. * @readonly
  5276. * @default true
  5277. */
  5278. this.isContextNode = true;
  5279. /**
  5280. * The node whose context should be modified.
  5281. *
  5282. * @type {Node}
  5283. */
  5284. this.node = node;
  5285. /**
  5286. * The modified context data.
  5287. *
  5288. * @type {Object}
  5289. * @default {}
  5290. */
  5291. this.value = value;
  5292. }
  5293. /**
  5294. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5295. *
  5296. * @return {Node} A reference to {@link ContextNode#node}.
  5297. */
  5298. getScope() {
  5299. return this.node.getScope();
  5300. }
  5301. /**
  5302. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5303. *
  5304. * @param {NodeBuilder} builder - The current node builder.
  5305. * @return {string} The node type.
  5306. */
  5307. getNodeType( builder ) {
  5308. return this.node.getNodeType( builder );
  5309. }
  5310. analyze( builder ) {
  5311. const previousContext = builder.getContext();
  5312. builder.setContext( { ...builder.context, ...this.value } );
  5313. this.node.build( builder );
  5314. builder.setContext( previousContext );
  5315. }
  5316. setup( builder ) {
  5317. const previousContext = builder.getContext();
  5318. builder.setContext( { ...builder.context, ...this.value } );
  5319. this.node.build( builder );
  5320. builder.setContext( previousContext );
  5321. }
  5322. generate( builder, output ) {
  5323. const previousContext = builder.getContext();
  5324. builder.setContext( { ...builder.context, ...this.value } );
  5325. const snippet = this.node.build( builder, output );
  5326. builder.setContext( previousContext );
  5327. return snippet;
  5328. }
  5329. }
  5330. /**
  5331. * TSL function for creating a context node.
  5332. *
  5333. * @tsl
  5334. * @function
  5335. * @param {Node} node - The node whose context should be modified.
  5336. * @param {Object} [value={}] - The modified context data.
  5337. * @returns {ContextNode}
  5338. */
  5339. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5340. /**
  5341. * TSL function for defining a uniformFlow context value for a given node.
  5342. *
  5343. * @tsl
  5344. * @function
  5345. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5346. * @returns {ContextNode}
  5347. */
  5348. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5349. /**
  5350. * TSL function for defining a name for the context value for a given node.
  5351. *
  5352. * @tsl
  5353. * @function
  5354. * @param {Node} node - The node whose context should be modified.
  5355. * @param {string} name - The name to set.
  5356. * @returns {ContextNode}
  5357. */
  5358. const setName = ( node, name ) => context( node, { nodeName: name } );
  5359. /**
  5360. * TSL function for defining a label context value for a given node.
  5361. *
  5362. * @tsl
  5363. * @function
  5364. * @deprecated
  5365. * @param {Node} node - The node whose context should be modified.
  5366. * @param {string} name - The name/label to set.
  5367. * @returns {ContextNode}
  5368. */
  5369. function label( node, name ) {
  5370. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5371. return setName( node, name );
  5372. }
  5373. addMethodChaining( 'context', context );
  5374. addMethodChaining( 'label', label );
  5375. addMethodChaining( 'uniformFlow', uniformFlow );
  5376. addMethodChaining( 'setName', setName );
  5377. /**
  5378. * Class for representing shader variables as nodes. Variables are created from
  5379. * existing nodes like the following:
  5380. *
  5381. * ```js
  5382. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5383. * ```
  5384. *
  5385. * @augments Node
  5386. */
  5387. class VarNode extends Node {
  5388. static get type() {
  5389. return 'VarNode';
  5390. }
  5391. /**
  5392. * Constructs a new variable node.
  5393. *
  5394. * @param {Node} node - The node for which a variable should be created.
  5395. * @param {?string} [name=null] - The name of the variable in the shader.
  5396. * @param {boolean} [readOnly=false] - The read-only flag.
  5397. */
  5398. constructor( node, name = null, readOnly = false ) {
  5399. super();
  5400. /**
  5401. * The node for which a variable should be created.
  5402. *
  5403. * @type {Node}
  5404. */
  5405. this.node = node;
  5406. /**
  5407. * The name of the variable in the shader. If no name is defined,
  5408. * the node system auto-generates one.
  5409. *
  5410. * @type {?string}
  5411. * @default null
  5412. */
  5413. this.name = name;
  5414. /**
  5415. * `VarNode` sets this property to `true` by default.
  5416. *
  5417. * @type {boolean}
  5418. * @default true
  5419. */
  5420. this.global = true;
  5421. /**
  5422. * This flag can be used for type testing.
  5423. *
  5424. * @type {boolean}
  5425. * @readonly
  5426. * @default true
  5427. */
  5428. this.isVarNode = true;
  5429. /**
  5430. *
  5431. * The read-only flag.
  5432. *
  5433. * @type {boolean}
  5434. * @default false
  5435. */
  5436. this.readOnly = readOnly;
  5437. /**
  5438. *
  5439. * Add this flag to the node system to indicate that this node require parents.
  5440. *
  5441. * @type {boolean}
  5442. * @default true
  5443. */
  5444. this.parents = true;
  5445. /**
  5446. * This flag is used to indicate that this node is used for intent.
  5447. *
  5448. * @type {boolean}
  5449. * @default false
  5450. */
  5451. this.intent = false;
  5452. }
  5453. /**
  5454. * Sets the intent flag for this node.
  5455. *
  5456. * This flag is used to indicate that this node is used for intent
  5457. * and should not be built directly. Instead, it is used to indicate that
  5458. * the node should be treated as a variable intent.
  5459. *
  5460. * It's useful for assigning variables without needing creating a new variable node.
  5461. *
  5462. * @param {boolean} value - The value to set for the intent flag.
  5463. * @returns {VarNode} This node.
  5464. */
  5465. setIntent( value ) {
  5466. this.intent = value;
  5467. return this;
  5468. }
  5469. /**
  5470. * Returns the intent flag of this node.
  5471. *
  5472. * @return {boolean} The intent flag.
  5473. */
  5474. getIntent() {
  5475. return this.intent;
  5476. }
  5477. getMemberType( builder, name ) {
  5478. return this.node.getMemberType( builder, name );
  5479. }
  5480. getElementType( builder ) {
  5481. return this.node.getElementType( builder );
  5482. }
  5483. getNodeType( builder ) {
  5484. return this.node.getNodeType( builder );
  5485. }
  5486. getArrayCount( builder ) {
  5487. return this.node.getArrayCount( builder );
  5488. }
  5489. build( ...params ) {
  5490. if ( this.intent === true ) {
  5491. const builder = params[ 0 ];
  5492. const properties = builder.getNodeProperties( this );
  5493. if ( properties.assign !== true ) {
  5494. return this.node.build( ...params );
  5495. }
  5496. }
  5497. return super.build( ...params );
  5498. }
  5499. generate( builder ) {
  5500. const { node, name, readOnly } = this;
  5501. const { renderer } = builder;
  5502. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5503. let isDeterministic = false;
  5504. let shouldTreatAsReadOnly = false;
  5505. if ( readOnly ) {
  5506. isDeterministic = builder.isDeterministic( node );
  5507. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5508. }
  5509. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  5510. const snippet = node.build( builder, vectorType );
  5511. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5512. const propertyName = builder.getPropertyName( nodeVar );
  5513. let declarationPrefix = propertyName;
  5514. if ( shouldTreatAsReadOnly ) {
  5515. if ( isWebGPUBackend ) {
  5516. declarationPrefix = isDeterministic
  5517. ? `const ${ propertyName }`
  5518. : `let ${ propertyName }`;
  5519. } else {
  5520. const count = node.getArrayCount( builder );
  5521. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5522. }
  5523. }
  5524. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5525. return propertyName;
  5526. }
  5527. }
  5528. /**
  5529. * TSL function for creating a var node.
  5530. *
  5531. * @tsl
  5532. * @function
  5533. * @param {Node} node - The node for which a variable should be created.
  5534. * @param {?string} name - The name of the variable in the shader.
  5535. * @returns {VarNode}
  5536. */
  5537. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5538. /**
  5539. * TSL function for creating a var node.
  5540. *
  5541. * @tsl
  5542. * @function
  5543. * @param {Node} node - The node for which a variable should be created.
  5544. * @param {?string} name - The name of the variable in the shader.
  5545. * @returns {VarNode}
  5546. */
  5547. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5548. /**
  5549. * TSL function for creating a const node.
  5550. *
  5551. * @tsl
  5552. * @function
  5553. * @param {Node} node - The node for which a constant should be created.
  5554. * @param {?string} name - The name of the constant in the shader.
  5555. * @returns {VarNode}
  5556. */
  5557. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5558. //
  5559. //
  5560. /**
  5561. * TSL function for creating a var intent node.
  5562. *
  5563. * @tsl
  5564. * @function
  5565. * @param {Node} node - The node for which a variable should be created.
  5566. * @param {?string} name - The name of the variable in the shader.
  5567. * @returns {VarNode}
  5568. */
  5569. const VarIntent = ( node ) => {
  5570. if ( getCurrentStack() === null ) {
  5571. return node;
  5572. }
  5573. return createVar( node ).setIntent( true ).toStack();
  5574. };
  5575. // Method chaining
  5576. addMethodChaining( 'toVar', Var );
  5577. addMethodChaining( 'toConst', Const );
  5578. addMethodChaining( 'toVarIntent', VarIntent );
  5579. /**
  5580. * This node is used to build a sub-build in the node system.
  5581. *
  5582. * @augments Node
  5583. * @param {Node} node - The node to be built in the sub-build.
  5584. * @param {string} name - The name of the sub-build.
  5585. * @param {string|null} [nodeType=null] - The type of the node, if known.
  5586. */
  5587. class SubBuildNode extends Node {
  5588. static get type() {
  5589. return 'SubBuild';
  5590. }
  5591. constructor( node, name, nodeType = null ) {
  5592. super( nodeType );
  5593. /**
  5594. * The node to be built in the sub-build.
  5595. *
  5596. * @type {Node}
  5597. */
  5598. this.node = node;
  5599. /**
  5600. * The name of the sub-build.
  5601. *
  5602. * @type {string}
  5603. */
  5604. this.name = name;
  5605. /**
  5606. * This flag can be used for type testing.
  5607. *
  5608. * @type {boolean}
  5609. * @readonly
  5610. * @default true
  5611. */
  5612. this.isSubBuildNode = true;
  5613. }
  5614. getNodeType( builder ) {
  5615. if ( this.nodeType !== null ) return this.nodeType;
  5616. builder.addSubBuild( this.name );
  5617. const nodeType = this.node.getNodeType( builder );
  5618. builder.removeSubBuild();
  5619. return nodeType;
  5620. }
  5621. build( builder, ...params ) {
  5622. builder.addSubBuild( this.name );
  5623. const data = this.node.build( builder, ...params );
  5624. builder.removeSubBuild();
  5625. return data;
  5626. }
  5627. }
  5628. /**
  5629. * Creates a new sub-build node.
  5630. *
  5631. * @tsl
  5632. * @function
  5633. * @param {Node} node - The node to be built in the sub-build.
  5634. * @param {string} name - The name of the sub-build.
  5635. * @param {string|null} [type=null] - The type of the node, if known.
  5636. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5637. */
  5638. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5639. /**
  5640. * Class for representing shader varyings as nodes. Varyings are create from
  5641. * existing nodes like the following:
  5642. *
  5643. * ```js
  5644. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5645. * ```
  5646. *
  5647. * @augments Node
  5648. */
  5649. class VaryingNode extends Node {
  5650. static get type() {
  5651. return 'VaryingNode';
  5652. }
  5653. /**
  5654. * Constructs a new varying node.
  5655. *
  5656. * @param {Node} node - The node for which a varying should be created.
  5657. * @param {?string} name - The name of the varying in the shader.
  5658. */
  5659. constructor( node, name = null ) {
  5660. super();
  5661. /**
  5662. * The node for which a varying should be created.
  5663. *
  5664. * @type {Node}
  5665. */
  5666. this.node = node;
  5667. /**
  5668. * The name of the varying in the shader. If no name is defined,
  5669. * the node system auto-generates one.
  5670. *
  5671. * @type {?string}
  5672. * @default null
  5673. */
  5674. this.name = name;
  5675. /**
  5676. * This flag can be used for type testing.
  5677. *
  5678. * @type {boolean}
  5679. * @readonly
  5680. * @default true
  5681. */
  5682. this.isVaryingNode = true;
  5683. /**
  5684. * The interpolation type of the varying data.
  5685. *
  5686. * @type {?string}
  5687. * @default null
  5688. */
  5689. this.interpolationType = null;
  5690. /**
  5691. * The interpolation sampling type of varying data.
  5692. *
  5693. * @type {?string}
  5694. * @default null
  5695. */
  5696. this.interpolationSampling = null;
  5697. /**
  5698. * This flag is used for global cache.
  5699. *
  5700. * @type {boolean}
  5701. * @default true
  5702. */
  5703. this.global = true;
  5704. }
  5705. /**
  5706. * Defines the interpolation type of the varying.
  5707. *
  5708. * @param {string} type - The interpolation type.
  5709. * @param {?string} sampling - The interpolation sampling type
  5710. * @return {VaryingNode} A reference to this node.
  5711. */
  5712. setInterpolation( type, sampling = null ) {
  5713. this.interpolationType = type;
  5714. this.interpolationSampling = sampling;
  5715. return this;
  5716. }
  5717. getHash( builder ) {
  5718. return this.name || super.getHash( builder );
  5719. }
  5720. getNodeType( builder ) {
  5721. // VaryingNode is auto type
  5722. return this.node.getNodeType( builder );
  5723. }
  5724. /**
  5725. * This method performs the setup of a varying node with the current node builder.
  5726. *
  5727. * @param {NodeBuilder} builder - The current node builder.
  5728. * @return {NodeVarying} The node varying from the node builder.
  5729. */
  5730. setupVarying( builder ) {
  5731. const properties = builder.getNodeProperties( this );
  5732. let varying = properties.varying;
  5733. if ( varying === undefined ) {
  5734. const name = this.name;
  5735. const type = this.getNodeType( builder );
  5736. const interpolationType = this.interpolationType;
  5737. const interpolationSampling = this.interpolationSampling;
  5738. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5739. properties.node = subBuild( this.node, 'VERTEX' );
  5740. }
  5741. // this property can be used to check if the varying can be optimized for a variable
  5742. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5743. return varying;
  5744. }
  5745. setup( builder ) {
  5746. this.setupVarying( builder );
  5747. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5748. }
  5749. analyze( builder ) {
  5750. this.setupVarying( builder );
  5751. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5752. }
  5753. generate( builder ) {
  5754. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  5755. const properties = builder.getNodeProperties( this );
  5756. const varying = this.setupVarying( builder );
  5757. if ( properties[ propertyKey ] === undefined ) {
  5758. const type = this.getNodeType( builder );
  5759. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5760. // force node run in vertex stage
  5761. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  5762. properties[ propertyKey ] = propertyName;
  5763. }
  5764. return builder.getPropertyName( varying );
  5765. }
  5766. }
  5767. /**
  5768. * TSL function for creating a varying node.
  5769. *
  5770. * @tsl
  5771. * @function
  5772. * @param {Node} node - The node for which a varying should be created.
  5773. * @param {?string} name - The name of the varying in the shader.
  5774. * @returns {VaryingNode}
  5775. */
  5776. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  5777. /**
  5778. * Computes a node in the vertex stage.
  5779. *
  5780. * @tsl
  5781. * @function
  5782. * @param {Node} node - The node which should be executed in the vertex stage.
  5783. * @returns {VaryingNode}
  5784. */
  5785. const vertexStage = ( node ) => varying( node );
  5786. addMethodChaining( 'toVarying', varying );
  5787. addMethodChaining( 'toVertexStage', vertexStage );
  5788. // Deprecated
  5789. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5790. console.warn( 'THREE.TSL: .varying() has been renamed to .toVarying().' );
  5791. return varying( ...params );
  5792. } );
  5793. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5794. console.warn( 'THREE.TSL: .vertexStage() has been renamed to .toVertexStage().' );
  5795. return varying( ...params );
  5796. } );
  5797. /**
  5798. * Converts the given color value from sRGB to linear-sRGB color space.
  5799. *
  5800. * @tsl
  5801. * @function
  5802. * @param {Node<vec3>} color - The sRGB color.
  5803. * @return {Node<vec3>} The linear-sRGB color.
  5804. */
  5805. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5806. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5807. const b = color.mul( 0.0773993808 );
  5808. const factor = color.lessThanEqual( 0.04045 );
  5809. const rgbResult = mix( a, b, factor );
  5810. return rgbResult;
  5811. } ).setLayout( {
  5812. name: 'sRGBTransferEOTF',
  5813. type: 'vec3',
  5814. inputs: [
  5815. { name: 'color', type: 'vec3' }
  5816. ]
  5817. } );
  5818. /**
  5819. * Converts the given color value from linear-sRGB to sRGB color space.
  5820. *
  5821. * @tsl
  5822. * @function
  5823. * @param {Node<vec3>} color - The linear-sRGB color.
  5824. * @return {Node<vec3>} The sRGB color.
  5825. */
  5826. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5827. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  5828. const b = color.mul( 12.92 );
  5829. const factor = color.lessThanEqual( 0.0031308 );
  5830. const rgbResult = mix( a, b, factor );
  5831. return rgbResult;
  5832. } ).setLayout( {
  5833. name: 'sRGBTransferOETF',
  5834. type: 'vec3',
  5835. inputs: [
  5836. { name: 'color', type: 'vec3' }
  5837. ]
  5838. } );
  5839. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  5840. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  5841. /**
  5842. * This node represents a color space conversion. Meaning it converts
  5843. * a color value from a source to a target color space.
  5844. *
  5845. * @augments TempNode
  5846. */
  5847. class ColorSpaceNode extends TempNode {
  5848. static get type() {
  5849. return 'ColorSpaceNode';
  5850. }
  5851. /**
  5852. * Constructs a new color space node.
  5853. *
  5854. * @param {Node} colorNode - Represents the color to convert.
  5855. * @param {string} source - The source color space.
  5856. * @param {string} target - The target color space.
  5857. */
  5858. constructor( colorNode, source, target ) {
  5859. super( 'vec4' );
  5860. /**
  5861. * Represents the color to convert.
  5862. *
  5863. * @type {Node}
  5864. */
  5865. this.colorNode = colorNode;
  5866. /**
  5867. * The source color space.
  5868. *
  5869. * @type {string}
  5870. */
  5871. this.source = source;
  5872. /**
  5873. * The target color space.
  5874. *
  5875. * @type {string}
  5876. */
  5877. this.target = target;
  5878. }
  5879. /**
  5880. * This method resolves the constants `WORKING_COLOR_SPACE` and
  5881. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  5882. * color management and renderer.
  5883. *
  5884. * @param {NodeBuilder} builder - The current node builder.
  5885. * @param {string} colorSpace - The color space to resolve.
  5886. * @return {string} The resolved color space.
  5887. */
  5888. resolveColorSpace( builder, colorSpace ) {
  5889. if ( colorSpace === WORKING_COLOR_SPACE ) {
  5890. return ColorManagement.workingColorSpace;
  5891. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  5892. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  5893. }
  5894. return colorSpace;
  5895. }
  5896. setup( builder ) {
  5897. const { colorNode } = this;
  5898. const source = this.resolveColorSpace( builder, this.source );
  5899. const target = this.resolveColorSpace( builder, this.target );
  5900. let outputNode = colorNode;
  5901. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  5902. return outputNode;
  5903. }
  5904. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  5905. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  5906. }
  5907. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  5908. outputNode = vec4(
  5909. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  5910. outputNode.a
  5911. );
  5912. }
  5913. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  5914. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  5915. }
  5916. return outputNode;
  5917. }
  5918. }
  5919. /**
  5920. * TSL function for converting a given color node from the current working color space to the given color space.
  5921. *
  5922. * @tsl
  5923. * @function
  5924. * @param {Node} node - Represents the node to convert.
  5925. * @param {string} targetColorSpace - The target color space.
  5926. * @returns {ColorSpaceNode}
  5927. */
  5928. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  5929. /**
  5930. * TSL function for converting a given color node from the given color space to the current working color space.
  5931. *
  5932. * @tsl
  5933. * @function
  5934. * @param {Node} node - Represents the node to convert.
  5935. * @param {string} sourceColorSpace - The source color space.
  5936. * @returns {ColorSpaceNode}
  5937. */
  5938. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  5939. /**
  5940. * TSL function for converting a given color node from one color space to another one.
  5941. *
  5942. * @tsl
  5943. * @function
  5944. * @param {Node} node - Represents the node to convert.
  5945. * @param {string} sourceColorSpace - The source color space.
  5946. * @param {string} targetColorSpace - The target color space.
  5947. * @returns {ColorSpaceNode}
  5948. */
  5949. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  5950. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  5951. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  5952. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  5953. /**
  5954. * This class is only relevant if the referenced property is array-like.
  5955. * In this case, `ReferenceElementNode` allows to refer to a specific
  5956. * element inside the data structure via an index.
  5957. *
  5958. * @augments ArrayElementNode
  5959. */
  5960. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  5961. static get type() {
  5962. return 'ReferenceElementNode';
  5963. }
  5964. /**
  5965. * Constructs a new reference element node.
  5966. *
  5967. * @param {ReferenceBaseNode} referenceNode - The reference node.
  5968. * @param {Node} indexNode - The index node that defines the element access.
  5969. */
  5970. constructor( referenceNode, indexNode ) {
  5971. super( referenceNode, indexNode );
  5972. /**
  5973. * Similar to {@link ReferenceBaseNode#reference}, an additional
  5974. * property references to the current node.
  5975. *
  5976. * @type {?ReferenceBaseNode}
  5977. * @default null
  5978. */
  5979. this.referenceNode = referenceNode;
  5980. /**
  5981. * This flag can be used for type testing.
  5982. *
  5983. * @type {boolean}
  5984. * @readonly
  5985. * @default true
  5986. */
  5987. this.isReferenceElementNode = true;
  5988. }
  5989. /**
  5990. * This method is overwritten since the node type is inferred from
  5991. * the uniform type of the reference node.
  5992. *
  5993. * @return {string} The node type.
  5994. */
  5995. getNodeType() {
  5996. return this.referenceNode.uniformType;
  5997. }
  5998. generate( builder ) {
  5999. const snippet = super.generate( builder );
  6000. const arrayType = this.referenceNode.getNodeType();
  6001. const elementType = this.getNodeType();
  6002. return builder.format( snippet, arrayType, elementType );
  6003. }
  6004. };
  6005. /**
  6006. * Base class for nodes which establishes a reference to a property of another object.
  6007. * In this way, the value of the node is automatically linked to the value of
  6008. * referenced object. Reference nodes internally represent the linked value
  6009. * as a uniform.
  6010. *
  6011. * @augments Node
  6012. */
  6013. class ReferenceBaseNode extends Node {
  6014. static get type() {
  6015. return 'ReferenceBaseNode';
  6016. }
  6017. /**
  6018. * Constructs a new reference base node.
  6019. *
  6020. * @param {string} property - The name of the property the node refers to.
  6021. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6022. * @param {?Object} [object=null] - The object the property belongs to.
  6023. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6024. */
  6025. constructor( property, uniformType, object = null, count = null ) {
  6026. super();
  6027. /**
  6028. * The name of the property the node refers to.
  6029. *
  6030. * @type {string}
  6031. */
  6032. this.property = property;
  6033. /**
  6034. * The uniform type that should be used to represent the property value.
  6035. *
  6036. * @type {string}
  6037. */
  6038. this.uniformType = uniformType;
  6039. /**
  6040. * The object the property belongs to.
  6041. *
  6042. * @type {?Object}
  6043. * @default null
  6044. */
  6045. this.object = object;
  6046. /**
  6047. * When the linked property is an array, this parameter defines its length.
  6048. *
  6049. * @type {?number}
  6050. * @default null
  6051. */
  6052. this.count = count;
  6053. /**
  6054. * The property name might have dots so nested properties can be referred.
  6055. * The hierarchy of the names is stored inside this array.
  6056. *
  6057. * @type {Array<string>}
  6058. */
  6059. this.properties = property.split( '.' );
  6060. /**
  6061. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6062. * since the final reference might be updated from calling code.
  6063. *
  6064. * @type {?Object}
  6065. * @default null
  6066. */
  6067. this.reference = object;
  6068. /**
  6069. * The uniform node that holds the value of the reference node.
  6070. *
  6071. * @type {UniformNode}
  6072. * @default null
  6073. */
  6074. this.node = null;
  6075. /**
  6076. * The uniform group of the internal uniform.
  6077. *
  6078. * @type {UniformGroupNode}
  6079. * @default null
  6080. */
  6081. this.group = null;
  6082. /**
  6083. * Overwritten since reference nodes are updated per object.
  6084. *
  6085. * @type {string}
  6086. * @default 'object'
  6087. */
  6088. this.updateType = NodeUpdateType.OBJECT;
  6089. }
  6090. /**
  6091. * Sets the uniform group for this reference node.
  6092. *
  6093. * @param {UniformGroupNode} group - The uniform group to set.
  6094. * @return {ReferenceBaseNode} A reference to this node.
  6095. */
  6096. setGroup( group ) {
  6097. this.group = group;
  6098. return this;
  6099. }
  6100. /**
  6101. * When the referred property is array-like, this method can be used
  6102. * to access elements via an index node.
  6103. *
  6104. * @param {IndexNode} indexNode - indexNode.
  6105. * @return {ReferenceElementNode} A reference to an element.
  6106. */
  6107. element( indexNode ) {
  6108. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  6109. }
  6110. /**
  6111. * Sets the node type which automatically defines the internal
  6112. * uniform type.
  6113. *
  6114. * @param {string} uniformType - The type to set.
  6115. */
  6116. setNodeType( uniformType ) {
  6117. const node = uniform( null, uniformType ).getSelf();
  6118. if ( this.group !== null ) {
  6119. node.setGroup( this.group );
  6120. }
  6121. this.node = node;
  6122. }
  6123. /**
  6124. * This method is overwritten since the node type is inferred from
  6125. * the type of the reference node.
  6126. *
  6127. * @param {NodeBuilder} builder - The current node builder.
  6128. * @return {string} The node type.
  6129. */
  6130. getNodeType( builder ) {
  6131. if ( this.node === null ) {
  6132. this.updateReference( builder );
  6133. this.updateValue();
  6134. }
  6135. return this.node.getNodeType( builder );
  6136. }
  6137. /**
  6138. * Returns the property value from the given referred object.
  6139. *
  6140. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6141. * @return {any} The value.
  6142. */
  6143. getValueFromReference( object = this.reference ) {
  6144. const { properties } = this;
  6145. let value = object[ properties[ 0 ] ];
  6146. for ( let i = 1; i < properties.length; i ++ ) {
  6147. value = value[ properties[ i ] ];
  6148. }
  6149. return value;
  6150. }
  6151. /**
  6152. * Allows to update the reference based on the given state. The state is only
  6153. * evaluated {@link ReferenceBaseNode#object} is not set.
  6154. *
  6155. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6156. * @return {Object} The updated reference.
  6157. */
  6158. updateReference( state ) {
  6159. this.reference = this.object !== null ? this.object : state.object;
  6160. return this.reference;
  6161. }
  6162. /**
  6163. * The output of the reference node is the internal uniform node.
  6164. *
  6165. * @return {UniformNode} The output node.
  6166. */
  6167. setup() {
  6168. this.updateValue();
  6169. return this.node;
  6170. }
  6171. /**
  6172. * Overwritten to update the internal uniform value.
  6173. *
  6174. * @param {NodeFrame} frame - A reference to the current node frame.
  6175. */
  6176. update( /*frame*/ ) {
  6177. this.updateValue();
  6178. }
  6179. /**
  6180. * Retrieves the value from the referred object property and uses it
  6181. * to updated the internal uniform.
  6182. */
  6183. updateValue() {
  6184. if ( this.node === null ) this.setNodeType( this.uniformType );
  6185. const value = this.getValueFromReference();
  6186. if ( Array.isArray( value ) ) {
  6187. this.node.array = value;
  6188. } else {
  6189. this.node.value = value;
  6190. }
  6191. }
  6192. }
  6193. /**
  6194. * TSL function for creating a reference base node.
  6195. *
  6196. * @tsl
  6197. * @function
  6198. * @param {string} name - The name of the property the node refers to.
  6199. * @param {string} type - The uniform type that should be used to represent the property value.
  6200. * @param {Object} object - The object the property belongs to.
  6201. * @returns {ReferenceBaseNode}
  6202. */
  6203. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  6204. /**
  6205. * This node is a special type of reference node which is intended
  6206. * for linking renderer properties with node values.
  6207. * ```js
  6208. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6209. * ```
  6210. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6211. * automatically be updated.
  6212. *
  6213. * @augments ReferenceBaseNode
  6214. */
  6215. class RendererReferenceNode extends ReferenceBaseNode {
  6216. static get type() {
  6217. return 'RendererReferenceNode';
  6218. }
  6219. /**
  6220. * Constructs a new renderer reference node.
  6221. *
  6222. * @param {string} property - The name of the property the node refers to.
  6223. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6224. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6225. * the node refers to the renderer of the current state.
  6226. */
  6227. constructor( property, inputType, renderer = null ) {
  6228. super( property, inputType, renderer );
  6229. /**
  6230. * The renderer the property belongs to. When no renderer is set,
  6231. * the node refers to the renderer of the current state.
  6232. *
  6233. * @type {?Renderer}
  6234. * @default null
  6235. */
  6236. this.renderer = renderer;
  6237. this.setGroup( renderGroup );
  6238. }
  6239. /**
  6240. * Updates the reference based on the given state. The state is only evaluated
  6241. * {@link RendererReferenceNode#renderer} is not set.
  6242. *
  6243. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6244. * @return {Object} The updated reference.
  6245. */
  6246. updateReference( state ) {
  6247. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6248. return this.reference;
  6249. }
  6250. }
  6251. /**
  6252. * TSL function for creating a renderer reference node.
  6253. *
  6254. * @tsl
  6255. * @function
  6256. * @param {string} name - The name of the property the node refers to.
  6257. * @param {string} type - The uniform type that should be used to represent the property value.
  6258. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6259. * the node refers to the renderer of the current state.
  6260. * @returns {RendererReferenceNode}
  6261. */
  6262. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6263. /**
  6264. * This node represents a tone mapping operation.
  6265. *
  6266. * @augments TempNode
  6267. */
  6268. class ToneMappingNode extends TempNode {
  6269. static get type() {
  6270. return 'ToneMappingNode';
  6271. }
  6272. /**
  6273. * Constructs a new tone mapping node.
  6274. *
  6275. * @param {number} toneMapping - The tone mapping type.
  6276. * @param {Node} exposureNode - The tone mapping exposure.
  6277. * @param {Node} [colorNode=null] - The color node to process.
  6278. */
  6279. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6280. super( 'vec3' );
  6281. /**
  6282. * The tone mapping type.
  6283. *
  6284. * @type {number}
  6285. */
  6286. this.toneMapping = toneMapping;
  6287. /**
  6288. * The tone mapping exposure.
  6289. *
  6290. * @type {Node}
  6291. * @default null
  6292. */
  6293. this.exposureNode = exposureNode;
  6294. /**
  6295. * Represents the color to process.
  6296. *
  6297. * @type {?Node}
  6298. * @default null
  6299. */
  6300. this.colorNode = colorNode;
  6301. }
  6302. /**
  6303. * Overwrites the default `customCacheKey()` implementation by including the tone
  6304. * mapping type into the cache key.
  6305. *
  6306. * @return {number} The hash.
  6307. */
  6308. customCacheKey() {
  6309. return hash$1( this.toneMapping );
  6310. }
  6311. setup( builder ) {
  6312. const colorNode = this.colorNode || builder.context.color;
  6313. const toneMapping = this.toneMapping;
  6314. if ( toneMapping === NoToneMapping ) return colorNode;
  6315. let outputNode = null;
  6316. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6317. if ( toneMappingFn !== null ) {
  6318. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6319. } else {
  6320. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6321. outputNode = colorNode;
  6322. }
  6323. return outputNode;
  6324. }
  6325. }
  6326. /**
  6327. * TSL function for creating a tone mapping node.
  6328. *
  6329. * @tsl
  6330. * @function
  6331. * @param {number} mapping - The tone mapping type.
  6332. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6333. * @param {Node<vec3> | Color} color - The color node to process.
  6334. * @returns {ToneMappingNode<vec3>}
  6335. */
  6336. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6337. /**
  6338. * TSL object that represents the global tone mapping exposure of the renderer.
  6339. *
  6340. * @tsl
  6341. * @type {RendererReferenceNode<vec3>}
  6342. */
  6343. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6344. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6345. /**
  6346. * In earlier `three.js` versions it was only possible to define attribute data
  6347. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6348. * on the node level.
  6349. * ```js
  6350. * const geometry = new THREE.PlaneGeometry();
  6351. * const positionAttribute = geometry.getAttribute( 'position' );
  6352. *
  6353. * const colors = [];
  6354. * for ( let i = 0; i < position.count; i ++ ) {
  6355. * colors.push( 1, 0, 0 );
  6356. * }
  6357. *
  6358. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6359. * ```
  6360. * This new approach is especially interesting when geometry data are generated via
  6361. * compute shaders. The below line converts a storage buffer into an attribute node.
  6362. * ```js
  6363. * material.positionNode = positionBuffer.toAttribute();
  6364. * ```
  6365. * @augments InputNode
  6366. */
  6367. class BufferAttributeNode extends InputNode {
  6368. static get type() {
  6369. return 'BufferAttributeNode';
  6370. }
  6371. /**
  6372. * Constructs a new buffer attribute node.
  6373. *
  6374. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6375. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6376. * @param {number} [bufferStride=0] - The buffer stride.
  6377. * @param {number} [bufferOffset=0] - The buffer offset.
  6378. */
  6379. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6380. super( value, bufferType );
  6381. /**
  6382. * This flag can be used for type testing.
  6383. *
  6384. * @type {boolean}
  6385. * @readonly
  6386. * @default true
  6387. */
  6388. this.isBufferNode = true;
  6389. /**
  6390. * The buffer type (e.g. `'vec3'`).
  6391. *
  6392. * @type {?string}
  6393. * @default null
  6394. */
  6395. this.bufferType = bufferType;
  6396. /**
  6397. * The buffer stride.
  6398. *
  6399. * @type {number}
  6400. * @default 0
  6401. */
  6402. this.bufferStride = bufferStride;
  6403. /**
  6404. * The buffer offset.
  6405. *
  6406. * @type {number}
  6407. * @default 0
  6408. */
  6409. this.bufferOffset = bufferOffset;
  6410. /**
  6411. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6412. * if you are planning to update the attribute data per frame.
  6413. *
  6414. * @type {number}
  6415. * @default StaticDrawUsage
  6416. */
  6417. this.usage = StaticDrawUsage;
  6418. /**
  6419. * Whether the attribute is instanced or not.
  6420. *
  6421. * @type {boolean}
  6422. * @default false
  6423. */
  6424. this.instanced = false;
  6425. /**
  6426. * A reference to the buffer attribute.
  6427. *
  6428. * @type {?BufferAttribute}
  6429. * @default null
  6430. */
  6431. this.attribute = null;
  6432. /**
  6433. * `BufferAttributeNode` sets this property to `true` by default.
  6434. *
  6435. * @type {boolean}
  6436. * @default true
  6437. */
  6438. this.global = true;
  6439. if ( value && value.isBufferAttribute === true ) {
  6440. this.attribute = value;
  6441. this.usage = value.usage;
  6442. this.instanced = value.isInstancedBufferAttribute;
  6443. }
  6444. }
  6445. /**
  6446. * This method is overwritten since the attribute data might be shared
  6447. * and thus the hash should be shared as well.
  6448. *
  6449. * @param {NodeBuilder} builder - The current node builder.
  6450. * @return {string} The hash.
  6451. */
  6452. getHash( builder ) {
  6453. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6454. let bufferData = builder.globalCache.getData( this.value );
  6455. if ( bufferData === undefined ) {
  6456. bufferData = {
  6457. node: this
  6458. };
  6459. builder.globalCache.setData( this.value, bufferData );
  6460. }
  6461. return bufferData.node.uuid;
  6462. }
  6463. return this.uuid;
  6464. }
  6465. /**
  6466. * This method is overwritten since the node type is inferred from
  6467. * the buffer attribute.
  6468. *
  6469. * @param {NodeBuilder} builder - The current node builder.
  6470. * @return {string} The node type.
  6471. */
  6472. getNodeType( builder ) {
  6473. if ( this.bufferType === null ) {
  6474. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6475. }
  6476. return this.bufferType;
  6477. }
  6478. /**
  6479. * Depending on which value was passed to the node, `setup()` behaves
  6480. * differently. If no instance of `BufferAttribute` was passed, the method
  6481. * creates an internal attribute and configures it respectively.
  6482. *
  6483. * @param {NodeBuilder} builder - The current node builder.
  6484. */
  6485. setup( builder ) {
  6486. if ( this.attribute !== null ) return;
  6487. const type = this.getNodeType( builder );
  6488. const array = this.value;
  6489. const itemSize = builder.getTypeLength( type );
  6490. const stride = this.bufferStride || itemSize;
  6491. const offset = this.bufferOffset;
  6492. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6493. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6494. buffer.setUsage( this.usage );
  6495. this.attribute = bufferAttribute;
  6496. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6497. }
  6498. /**
  6499. * Generates the code snippet of the buffer attribute node.
  6500. *
  6501. * @param {NodeBuilder} builder - The current node builder.
  6502. * @return {string} The generated code snippet.
  6503. */
  6504. generate( builder ) {
  6505. const nodeType = this.getNodeType( builder );
  6506. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6507. const propertyName = builder.getPropertyName( nodeAttribute );
  6508. let output = null;
  6509. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6510. this.name = propertyName;
  6511. output = propertyName;
  6512. } else {
  6513. const nodeVarying = varying( this );
  6514. output = nodeVarying.build( builder, nodeType );
  6515. }
  6516. return output;
  6517. }
  6518. /**
  6519. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6520. *
  6521. * @param {NodeBuilder} builder - The current node builder.
  6522. * @return {string} The input type.
  6523. */
  6524. getInputType( /*builder*/ ) {
  6525. return 'bufferAttribute';
  6526. }
  6527. /**
  6528. * Sets the `usage` property to the given value.
  6529. *
  6530. * @param {number} value - The usage to set.
  6531. * @return {BufferAttributeNode} A reference to this node.
  6532. */
  6533. setUsage( value ) {
  6534. this.usage = value;
  6535. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6536. this.attribute.usage = value;
  6537. }
  6538. return this;
  6539. }
  6540. /**
  6541. * Sets the `instanced` property to the given value.
  6542. *
  6543. * @param {boolean} value - The value to set.
  6544. * @return {BufferAttributeNode} A reference to this node.
  6545. */
  6546. setInstanced( value ) {
  6547. this.instanced = value;
  6548. return this;
  6549. }
  6550. }
  6551. /**
  6552. * TSL function for creating a buffer attribute node.
  6553. *
  6554. * @tsl
  6555. * @function
  6556. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6557. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6558. * @param {number} [stride=0] - The buffer stride.
  6559. * @param {number} [offset=0] - The buffer offset.
  6560. * @returns {BufferAttributeNode}
  6561. */
  6562. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6563. /**
  6564. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6565. * Use this function if attribute data are updated per frame.
  6566. *
  6567. * @tsl
  6568. * @function
  6569. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6570. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6571. * @param {number} [stride=0] - The buffer stride.
  6572. * @param {number} [offset=0] - The buffer offset.
  6573. * @returns {BufferAttributeNode}
  6574. */
  6575. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6576. /**
  6577. * TSL function for creating a buffer attribute node but with enabled instancing
  6578. *
  6579. * @tsl
  6580. * @function
  6581. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6582. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6583. * @param {number} [stride=0] - The buffer stride.
  6584. * @param {number} [offset=0] - The buffer offset.
  6585. * @returns {BufferAttributeNode}
  6586. */
  6587. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6588. /**
  6589. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6590. *
  6591. * @tsl
  6592. * @function
  6593. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6594. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6595. * @param {number} [stride=0] - The buffer stride.
  6596. * @param {number} [offset=0] - The buffer offset.
  6597. * @returns {BufferAttributeNode}
  6598. */
  6599. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6600. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6601. /**
  6602. * TODO
  6603. *
  6604. * @augments Node
  6605. */
  6606. class ComputeNode extends Node {
  6607. static get type() {
  6608. return 'ComputeNode';
  6609. }
  6610. /**
  6611. * Constructs a new compute node.
  6612. *
  6613. * @param {Node} computeNode - TODO
  6614. * @param {Array<number>} workgroupSize - TODO.
  6615. */
  6616. constructor( computeNode, workgroupSize ) {
  6617. super( 'void' );
  6618. /**
  6619. * This flag can be used for type testing.
  6620. *
  6621. * @type {boolean}
  6622. * @readonly
  6623. * @default true
  6624. */
  6625. this.isComputeNode = true;
  6626. /**
  6627. * TODO
  6628. *
  6629. * @type {Node}
  6630. */
  6631. this.computeNode = computeNode;
  6632. /**
  6633. * TODO
  6634. *
  6635. * @type {Array<number>}
  6636. * @default [ 64 ]
  6637. */
  6638. this.workgroupSize = workgroupSize;
  6639. /**
  6640. * TODO
  6641. *
  6642. * @type {number}
  6643. */
  6644. this.count = null;
  6645. /**
  6646. * TODO
  6647. *
  6648. * @type {number}
  6649. */
  6650. this.version = 1;
  6651. /**
  6652. * The name or label of the uniform.
  6653. *
  6654. * @type {string}
  6655. * @default ''
  6656. */
  6657. this.name = '';
  6658. /**
  6659. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6660. * is executed once per object by default.
  6661. *
  6662. * @type {string}
  6663. * @default 'object'
  6664. */
  6665. this.updateBeforeType = NodeUpdateType.OBJECT;
  6666. /**
  6667. * TODO
  6668. *
  6669. * @type {?Function}
  6670. */
  6671. this.onInitFunction = null;
  6672. }
  6673. setCount( count ) {
  6674. this.count = count;
  6675. return this;
  6676. }
  6677. getCount() {
  6678. return this.count;
  6679. }
  6680. /**
  6681. * Executes the `dispose` event for this node.
  6682. */
  6683. dispose() {
  6684. this.dispatchEvent( { type: 'dispose' } );
  6685. }
  6686. /**
  6687. * Sets the {@link ComputeNode#name} property.
  6688. *
  6689. * @param {string} name - The name of the uniform.
  6690. * @return {ComputeNode} A reference to this node.
  6691. */
  6692. setName( name ) {
  6693. this.name = name;
  6694. return this;
  6695. }
  6696. /**
  6697. * Sets the {@link ComputeNode#name} property.
  6698. *
  6699. * @deprecated
  6700. * @param {string} name - The name of the uniform.
  6701. * @return {ComputeNode} A reference to this node.
  6702. */
  6703. label( name ) {
  6704. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  6705. return this.setName( name );
  6706. }
  6707. /**
  6708. * TODO
  6709. *
  6710. * @param {Function} callback - TODO.
  6711. * @return {ComputeNode} A reference to this node.
  6712. */
  6713. onInit( callback ) {
  6714. this.onInitFunction = callback;
  6715. return this;
  6716. }
  6717. /**
  6718. * The method execute the compute for this node.
  6719. *
  6720. * @param {NodeFrame} frame - A reference to the current node frame.
  6721. */
  6722. updateBefore( { renderer } ) {
  6723. renderer.compute( this );
  6724. }
  6725. setup( builder ) {
  6726. const result = this.computeNode.build( builder );
  6727. if ( result ) {
  6728. const properties = builder.getNodeProperties( this );
  6729. properties.outputComputeNode = result.outputNode;
  6730. result.outputNode = null;
  6731. }
  6732. return result;
  6733. }
  6734. generate( builder, output ) {
  6735. const { shaderStage } = builder;
  6736. if ( shaderStage === 'compute' ) {
  6737. const snippet = this.computeNode.build( builder, 'void' );
  6738. if ( snippet !== '' ) {
  6739. builder.addLineFlowCode( snippet, this );
  6740. }
  6741. } else {
  6742. const properties = builder.getNodeProperties( this );
  6743. const outputComputeNode = properties.outputComputeNode;
  6744. if ( outputComputeNode ) {
  6745. return outputComputeNode.build( builder, output );
  6746. }
  6747. }
  6748. }
  6749. }
  6750. /**
  6751. * TSL function for creating a compute kernel node.
  6752. *
  6753. * @tsl
  6754. * @function
  6755. * @param {Node} node - TODO
  6756. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6757. * @returns {AtomicFunctionNode}
  6758. */
  6759. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  6760. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  6761. console.error( 'THREE.TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  6762. }
  6763. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  6764. const val = workgroupSize[ i ];
  6765. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  6766. console.error( `THREE.TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  6767. }
  6768. }
  6769. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  6770. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  6771. //
  6772. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  6773. };
  6774. /**
  6775. * TSL function for creating a compute node.
  6776. *
  6777. * @tsl
  6778. * @function
  6779. * @param {Node} node - TODO
  6780. * @param {number} count - TODO.
  6781. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6782. * @returns {AtomicFunctionNode}
  6783. */
  6784. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  6785. addMethodChaining( 'compute', compute );
  6786. addMethodChaining( 'computeKernel', computeKernel );
  6787. /**
  6788. * This node can be used as a cache management component for another node.
  6789. * Caching is in general used by default in {@link NodeBuilder} but this node
  6790. * allows the usage of a shared parent cache during the build process.
  6791. *
  6792. * @augments Node
  6793. */
  6794. class CacheNode extends Node {
  6795. static get type() {
  6796. return 'CacheNode';
  6797. }
  6798. /**
  6799. * Constructs a new cache node.
  6800. *
  6801. * @param {Node} node - The node that should be cached.
  6802. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  6803. */
  6804. constructor( node, parent = true ) {
  6805. super();
  6806. /**
  6807. * The node that should be cached.
  6808. *
  6809. * @type {Node}
  6810. */
  6811. this.node = node;
  6812. /**
  6813. * Whether this node refers to a shared parent cache or not.
  6814. *
  6815. * @type {boolean}
  6816. * @default true
  6817. */
  6818. this.parent = parent;
  6819. /**
  6820. * This flag can be used for type testing.
  6821. *
  6822. * @type {boolean}
  6823. * @readonly
  6824. * @default true
  6825. */
  6826. this.isCacheNode = true;
  6827. }
  6828. getNodeType( builder ) {
  6829. const previousCache = builder.getCache();
  6830. const cache = builder.getCacheFromNode( this, this.parent );
  6831. builder.setCache( cache );
  6832. const nodeType = this.node.getNodeType( builder );
  6833. builder.setCache( previousCache );
  6834. return nodeType;
  6835. }
  6836. build( builder, ...params ) {
  6837. const previousCache = builder.getCache();
  6838. const cache = builder.getCacheFromNode( this, this.parent );
  6839. builder.setCache( cache );
  6840. const data = this.node.build( builder, ...params );
  6841. builder.setCache( previousCache );
  6842. return data;
  6843. }
  6844. }
  6845. /**
  6846. * TSL function for creating a cache node.
  6847. *
  6848. * @tsl
  6849. * @function
  6850. * @param {Node} node - The node that should be cached.
  6851. * @param {boolean} [parent] - Whether this node refers to a shared parent cache or not.
  6852. * @returns {CacheNode}
  6853. */
  6854. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  6855. addMethodChaining( 'cache', cache );
  6856. /**
  6857. * The class generates the code of a given node but returns another node in the output.
  6858. * This can be used to call a method or node that does not return a value, i.e.
  6859. * type `void` on an input where returning a value is required. Example:
  6860. *
  6861. * ```js
  6862. * material.colorNode = myColor.bypass( runVoidFn() )
  6863. *```
  6864. *
  6865. * @augments Node
  6866. */
  6867. class BypassNode extends Node {
  6868. static get type() {
  6869. return 'BypassNode';
  6870. }
  6871. /**
  6872. * Constructs a new bypass node.
  6873. *
  6874. * @param {Node} outputNode - The output node.
  6875. * @param {Node} callNode - The call node.
  6876. */
  6877. constructor( outputNode, callNode ) {
  6878. super();
  6879. /**
  6880. * This flag can be used for type testing.
  6881. *
  6882. * @type {boolean}
  6883. * @readonly
  6884. * @default true
  6885. */
  6886. this.isBypassNode = true;
  6887. /**
  6888. * The output node.
  6889. *
  6890. * @type {Node}
  6891. */
  6892. this.outputNode = outputNode;
  6893. /**
  6894. * The call node.
  6895. *
  6896. * @type {Node}
  6897. */
  6898. this.callNode = callNode;
  6899. }
  6900. getNodeType( builder ) {
  6901. return this.outputNode.getNodeType( builder );
  6902. }
  6903. generate( builder ) {
  6904. const snippet = this.callNode.build( builder, 'void' );
  6905. if ( snippet !== '' ) {
  6906. builder.addLineFlowCode( snippet, this );
  6907. }
  6908. return this.outputNode.build( builder );
  6909. }
  6910. }
  6911. /**
  6912. * TSL function for creating a bypass node.
  6913. *
  6914. * @tsl
  6915. * @function
  6916. * @param {Node} outputNode - The output node.
  6917. * @param {Node} callNode - The call node.
  6918. * @returns {BypassNode}
  6919. */
  6920. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  6921. addMethodChaining( 'bypass', bypass );
  6922. /**
  6923. * This node allows to remap a node value from one range into another. E.g a value of
  6924. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  6925. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  6926. *
  6927. * @augments Node
  6928. */
  6929. class RemapNode extends Node {
  6930. static get type() {
  6931. return 'RemapNode';
  6932. }
  6933. /**
  6934. * Constructs a new remap node.
  6935. *
  6936. * @param {Node} node - The node that should be remapped.
  6937. * @param {Node} inLowNode - The source or current lower bound of the range.
  6938. * @param {Node} inHighNode - The source or current upper bound of the range.
  6939. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6940. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6941. */
  6942. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  6943. super();
  6944. /**
  6945. * The node that should be remapped.
  6946. *
  6947. * @type {Node}
  6948. */
  6949. this.node = node;
  6950. /**
  6951. * The source or current lower bound of the range.
  6952. *
  6953. * @type {Node}
  6954. */
  6955. this.inLowNode = inLowNode;
  6956. /**
  6957. * The source or current upper bound of the range.
  6958. *
  6959. * @type {Node}
  6960. */
  6961. this.inHighNode = inHighNode;
  6962. /**
  6963. * The target lower bound of the range.
  6964. *
  6965. * @type {Node}
  6966. * @default float(0)
  6967. */
  6968. this.outLowNode = outLowNode;
  6969. /**
  6970. * The target upper bound of the range.
  6971. *
  6972. * @type {Node}
  6973. * @default float(1)
  6974. */
  6975. this.outHighNode = outHighNode;
  6976. /**
  6977. * Whether the node value should be clamped before
  6978. * remapping it to the target range.
  6979. *
  6980. * @type {boolean}
  6981. * @default true
  6982. */
  6983. this.doClamp = true;
  6984. }
  6985. setup() {
  6986. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  6987. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  6988. if ( doClamp === true ) t = t.clamp();
  6989. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  6990. }
  6991. }
  6992. /**
  6993. * TSL function for creating a remap node.
  6994. *
  6995. * @tsl
  6996. * @function
  6997. * @param {Node} node - The node that should be remapped.
  6998. * @param {Node} inLowNode - The source or current lower bound of the range.
  6999. * @param {Node} inHighNode - The source or current upper bound of the range.
  7000. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7001. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7002. * @returns {RemapNode}
  7003. */
  7004. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7005. /**
  7006. * TSL function for creating a remap node, but with enabled clamping.
  7007. *
  7008. * @tsl
  7009. * @function
  7010. * @param {Node} node - The node that should be remapped.
  7011. * @param {Node} inLowNode - The source or current lower bound of the range.
  7012. * @param {Node} inHighNode - The source or current upper bound of the range.
  7013. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7014. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7015. * @returns {RemapNode}
  7016. */
  7017. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7018. addMethodChaining( 'remap', remap );
  7019. addMethodChaining( 'remapClamp', remapClamp );
  7020. /**
  7021. * This class can be used to implement basic expressions in shader code.
  7022. * Basic examples for that are `return`, `continue` or `discard` statements.
  7023. *
  7024. * @augments Node
  7025. */
  7026. class ExpressionNode extends Node {
  7027. static get type() {
  7028. return 'ExpressionNode';
  7029. }
  7030. /**
  7031. * Constructs a new expression node.
  7032. *
  7033. * @param {string} [snippet=''] - The native code snippet.
  7034. * @param {string} [nodeType='void'] - The node type.
  7035. */
  7036. constructor( snippet = '', nodeType = 'void' ) {
  7037. super( nodeType );
  7038. /**
  7039. * The native code snippet.
  7040. *
  7041. * @type {string}
  7042. * @default ''
  7043. */
  7044. this.snippet = snippet;
  7045. }
  7046. generate( builder, output ) {
  7047. const type = this.getNodeType( builder );
  7048. const snippet = this.snippet;
  7049. if ( type === 'void' ) {
  7050. builder.addLineFlowCode( snippet, this );
  7051. } else {
  7052. return builder.format( snippet, type, output );
  7053. }
  7054. }
  7055. }
  7056. /**
  7057. * TSL function for creating an expression node.
  7058. *
  7059. * @tsl
  7060. * @function
  7061. * @param {string} [snippet] - The native code snippet.
  7062. * @param {?string} [nodeType='void'] - The node type.
  7063. * @returns {ExpressionNode}
  7064. */
  7065. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7066. /**
  7067. * Represents a `discard` shader operation in TSL.
  7068. *
  7069. * @tsl
  7070. * @function
  7071. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7072. * @return {Node} The `discard` expression.
  7073. */
  7074. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7075. /**
  7076. * Represents a `return` shader operation in TSL.
  7077. *
  7078. * @tsl
  7079. * @function
  7080. * @return {ExpressionNode} The `return` expression.
  7081. */
  7082. const Return = () => expression( 'return' ).toStack();
  7083. addMethodChaining( 'discard', Discard );
  7084. /**
  7085. * Normally, tone mapping and color conversion happens automatically
  7086. * before outputting pixel too the default (screen) framebuffer. In certain
  7087. * post processing setups this happens to late because certain effects
  7088. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7089. * to apply tone mapping and color space conversion at an arbitrary point
  7090. * in the effect chain.
  7091. *
  7092. * When applying tone mapping and color space conversion manually with this node,
  7093. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7094. *
  7095. * ```js
  7096. * const postProcessing = new PostProcessing( renderer );
  7097. * postProcessing.outputColorTransform = false;
  7098. *
  7099. * const scenePass = pass( scene, camera );
  7100. * const outputPass = renderOutput( scenePass );
  7101. *
  7102. * postProcessing.outputNode = outputPass;
  7103. * ```
  7104. *
  7105. * @augments TempNode
  7106. */
  7107. class RenderOutputNode extends TempNode {
  7108. static get type() {
  7109. return 'RenderOutputNode';
  7110. }
  7111. /**
  7112. * Constructs a new render output node.
  7113. *
  7114. * @param {Node} colorNode - The color node to process.
  7115. * @param {?number} toneMapping - The tone mapping type.
  7116. * @param {?string} outputColorSpace - The output color space.
  7117. */
  7118. constructor( colorNode, toneMapping, outputColorSpace ) {
  7119. super( 'vec4' );
  7120. /**
  7121. * The color node to process.
  7122. *
  7123. * @type {Node}
  7124. */
  7125. this.colorNode = colorNode;
  7126. /**
  7127. * The tone mapping type.
  7128. *
  7129. * @type {?number}
  7130. */
  7131. this.toneMapping = toneMapping;
  7132. /**
  7133. * The output color space.
  7134. *
  7135. * @type {?string}
  7136. */
  7137. this.outputColorSpace = outputColorSpace;
  7138. /**
  7139. * This flag can be used for type testing.
  7140. *
  7141. * @type {boolean}
  7142. * @readonly
  7143. * @default true
  7144. */
  7145. this.isRenderOutputNode = true;
  7146. }
  7147. setup( { context } ) {
  7148. let outputNode = this.colorNode || context.color;
  7149. // tone mapping
  7150. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  7151. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7152. if ( toneMapping !== NoToneMapping ) {
  7153. outputNode = outputNode.toneMapping( toneMapping );
  7154. }
  7155. // working to output color space
  7156. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7157. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7158. }
  7159. return outputNode;
  7160. }
  7161. }
  7162. /**
  7163. * TSL function for creating a posterize node.
  7164. *
  7165. * @tsl
  7166. * @function
  7167. * @param {Node} color - The color node to process.
  7168. * @param {?number} [toneMapping=null] - The tone mapping type.
  7169. * @param {?string} [outputColorSpace=null] - The output color space.
  7170. * @returns {RenderOutputNode}
  7171. */
  7172. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7173. addMethodChaining( 'renderOutput', renderOutput );
  7174. class DebugNode extends TempNode {
  7175. static get type() {
  7176. return 'DebugNode';
  7177. }
  7178. constructor( node, callback = null ) {
  7179. super();
  7180. this.node = node;
  7181. this.callback = callback;
  7182. }
  7183. getNodeType( builder ) {
  7184. return this.node.getNodeType( builder );
  7185. }
  7186. setup( builder ) {
  7187. return this.node.build( builder );
  7188. }
  7189. analyze( builder ) {
  7190. return this.node.build( builder );
  7191. }
  7192. generate( builder ) {
  7193. const callback = this.callback;
  7194. const snippet = this.node.build( builder );
  7195. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7196. const border = '-'.repeat( title.length );
  7197. let code = '';
  7198. code += '// #' + title + '#\n';
  7199. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7200. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7201. code += '// #' + border + '#\n';
  7202. if ( callback !== null ) {
  7203. callback( builder, code );
  7204. } else {
  7205. console.log( code );
  7206. }
  7207. return snippet;
  7208. }
  7209. }
  7210. /**
  7211. * TSL function for creating a debug node.
  7212. *
  7213. * @tsl
  7214. * @function
  7215. * @param {Node} node - The node to debug.
  7216. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7217. * @returns {DebugNode}
  7218. */
  7219. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7220. addMethodChaining( 'debug', debug );
  7221. // Non-PURE exports list, side-effects are required here.
  7222. // TSL Base Syntax
  7223. function addNodeElement( name/*, nodeElement*/ ) {
  7224. console.warn( 'THREE.TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7225. }
  7226. /**
  7227. * Base class for representing shader attributes as nodes.
  7228. *
  7229. * @augments Node
  7230. */
  7231. class AttributeNode extends Node {
  7232. static get type() {
  7233. return 'AttributeNode';
  7234. }
  7235. /**
  7236. * Constructs a new attribute node.
  7237. *
  7238. * @param {string} attributeName - The name of the attribute.
  7239. * @param {?string} nodeType - The node type.
  7240. */
  7241. constructor( attributeName, nodeType = null ) {
  7242. super( nodeType );
  7243. /**
  7244. * `AttributeNode` sets this property to `true` by default.
  7245. *
  7246. * @type {boolean}
  7247. * @default true
  7248. */
  7249. this.global = true;
  7250. this._attributeName = attributeName;
  7251. }
  7252. getHash( builder ) {
  7253. return this.getAttributeName( builder );
  7254. }
  7255. getNodeType( builder ) {
  7256. let nodeType = this.nodeType;
  7257. if ( nodeType === null ) {
  7258. const attributeName = this.getAttributeName( builder );
  7259. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7260. const attribute = builder.geometry.getAttribute( attributeName );
  7261. nodeType = builder.getTypeFromAttribute( attribute );
  7262. } else {
  7263. nodeType = 'float';
  7264. }
  7265. }
  7266. return nodeType;
  7267. }
  7268. /**
  7269. * Sets the attribute name to the given value. The method can be
  7270. * overwritten in derived classes if the final name must be computed
  7271. * analytically.
  7272. *
  7273. * @param {string} attributeName - The name of the attribute.
  7274. * @return {AttributeNode} A reference to this node.
  7275. */
  7276. setAttributeName( attributeName ) {
  7277. this._attributeName = attributeName;
  7278. return this;
  7279. }
  7280. /**
  7281. * Returns the attribute name of this node. The method can be
  7282. * overwritten in derived classes if the final name must be computed
  7283. * analytically.
  7284. *
  7285. * @param {NodeBuilder} builder - The current node builder.
  7286. * @return {string} The attribute name.
  7287. */
  7288. getAttributeName( /*builder*/ ) {
  7289. return this._attributeName;
  7290. }
  7291. generate( builder ) {
  7292. const attributeName = this.getAttributeName( builder );
  7293. const nodeType = this.getNodeType( builder );
  7294. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7295. if ( geometryAttribute === true ) {
  7296. const attribute = builder.geometry.getAttribute( attributeName );
  7297. const attributeType = builder.getTypeFromAttribute( attribute );
  7298. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7299. if ( builder.shaderStage === 'vertex' ) {
  7300. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7301. } else {
  7302. const nodeVarying = varying( this );
  7303. return nodeVarying.build( builder, nodeType );
  7304. }
  7305. } else {
  7306. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7307. return builder.generateConst( nodeType );
  7308. }
  7309. }
  7310. serialize( data ) {
  7311. super.serialize( data );
  7312. data.global = this.global;
  7313. data._attributeName = this._attributeName;
  7314. }
  7315. deserialize( data ) {
  7316. super.deserialize( data );
  7317. this.global = data.global;
  7318. this._attributeName = data._attributeName;
  7319. }
  7320. }
  7321. /**
  7322. * TSL function for creating an attribute node.
  7323. *
  7324. * @tsl
  7325. * @function
  7326. * @param {string} name - The name of the attribute.
  7327. * @param {?string} [nodeType=null] - The node type.
  7328. * @returns {AttributeNode}
  7329. */
  7330. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7331. /**
  7332. * TSL function for creating an uv attribute node with the given index.
  7333. *
  7334. * @tsl
  7335. * @function
  7336. * @param {number} [index=0] - The uv index.
  7337. * @return {AttributeNode<vec2>} The uv attribute node.
  7338. */
  7339. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7340. /**
  7341. * A node that represents the dimensions of a texture. The texture size is
  7342. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7343. * or `textureSize()`.
  7344. *
  7345. * @augments Node
  7346. */
  7347. class TextureSizeNode extends Node {
  7348. static get type() {
  7349. return 'TextureSizeNode';
  7350. }
  7351. /**
  7352. * Constructs a new texture size node.
  7353. *
  7354. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7355. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7356. */
  7357. constructor( textureNode, levelNode = null ) {
  7358. super( 'uvec2' );
  7359. /**
  7360. * This flag can be used for type testing.
  7361. *
  7362. * @type {boolean}
  7363. * @readonly
  7364. * @default true
  7365. */
  7366. this.isTextureSizeNode = true;
  7367. /**
  7368. * A texture node which size should be retrieved.
  7369. *
  7370. * @type {TextureNode}
  7371. */
  7372. this.textureNode = textureNode;
  7373. /**
  7374. * A level node which defines the requested mip.
  7375. *
  7376. * @type {Node<int>}
  7377. * @default null
  7378. */
  7379. this.levelNode = levelNode;
  7380. }
  7381. generate( builder, output ) {
  7382. const textureProperty = this.textureNode.build( builder, 'property' );
  7383. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7384. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7385. }
  7386. }
  7387. /**
  7388. * TSL function for creating a texture size node.
  7389. *
  7390. * @tsl
  7391. * @function
  7392. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7393. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7394. * @returns {TextureSizeNode}
  7395. */
  7396. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  7397. /**
  7398. * A special type of uniform node that computes the
  7399. * maximum mipmap level for a given texture node.
  7400. *
  7401. * ```js
  7402. * const level = maxMipLevel( textureNode );
  7403. * ```
  7404. *
  7405. * @augments UniformNode
  7406. */
  7407. class MaxMipLevelNode extends UniformNode {
  7408. static get type() {
  7409. return 'MaxMipLevelNode';
  7410. }
  7411. /**
  7412. * Constructs a new max mip level node.
  7413. *
  7414. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7415. */
  7416. constructor( textureNode ) {
  7417. super( 0 );
  7418. /**
  7419. * The texture node to compute the max mip level for.
  7420. *
  7421. * @private
  7422. * @type {TextureNode}
  7423. */
  7424. this._textureNode = textureNode;
  7425. /**
  7426. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  7427. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  7428. *
  7429. * @type {string}
  7430. * @default 'frame'
  7431. */
  7432. this.updateType = NodeUpdateType.FRAME;
  7433. }
  7434. /**
  7435. * The texture node to compute the max mip level for.
  7436. *
  7437. * @readonly
  7438. * @type {TextureNode}
  7439. */
  7440. get textureNode() {
  7441. return this._textureNode;
  7442. }
  7443. /**
  7444. * The texture.
  7445. *
  7446. * @readonly
  7447. * @type {Texture}
  7448. */
  7449. get texture() {
  7450. return this._textureNode.value;
  7451. }
  7452. update() {
  7453. const texture = this.texture;
  7454. const images = texture.images;
  7455. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7456. if ( image && image.width !== undefined ) {
  7457. const { width, height } = image;
  7458. this.value = Math.log2( Math.max( width, height ) );
  7459. }
  7460. }
  7461. }
  7462. /**
  7463. * TSL function for creating a max mip level node.
  7464. *
  7465. * @tsl
  7466. * @function
  7467. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7468. * @returns {MaxMipLevelNode}
  7469. */
  7470. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7471. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  7472. /**
  7473. * This type of uniform node represents a 2D texture.
  7474. *
  7475. * @augments UniformNode
  7476. */
  7477. class TextureNode extends UniformNode {
  7478. static get type() {
  7479. return 'TextureNode';
  7480. }
  7481. /**
  7482. * Constructs a new texture node.
  7483. *
  7484. * @param {Texture} [value=EmptyTexture] - The texture.
  7485. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7486. * @param {?Node<int>} [levelNode=null] - The level node.
  7487. * @param {?Node<float>} [biasNode=null] - The bias node.
  7488. */
  7489. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  7490. super( value );
  7491. /**
  7492. * This flag can be used for type testing.
  7493. *
  7494. * @type {boolean}
  7495. * @readonly
  7496. * @default true
  7497. */
  7498. this.isTextureNode = true;
  7499. /**
  7500. * Represents the texture coordinates.
  7501. *
  7502. * @type {?Node<vec2|vec3>}
  7503. * @default null
  7504. */
  7505. this.uvNode = uvNode;
  7506. /**
  7507. * Represents the mip level that should be selected.
  7508. *
  7509. * @type {?Node<int>}
  7510. * @default null
  7511. */
  7512. this.levelNode = levelNode;
  7513. /**
  7514. * Represents the bias to be applied during level-of-detail computation.
  7515. *
  7516. * @type {?Node<float>}
  7517. * @default null
  7518. */
  7519. this.biasNode = biasNode;
  7520. /**
  7521. * Represents a reference value a texture sample is compared to.
  7522. *
  7523. * @type {?Node<float>}
  7524. * @default null
  7525. */
  7526. this.compareNode = null;
  7527. /**
  7528. * When using texture arrays, the depth node defines the layer to select.
  7529. *
  7530. * @type {?Node<int>}
  7531. * @default null
  7532. */
  7533. this.depthNode = null;
  7534. /**
  7535. * When defined, a texture is sampled using explicit gradients.
  7536. *
  7537. * @type {?Array<Node<vec2>>}
  7538. * @default null
  7539. */
  7540. this.gradNode = null;
  7541. /**
  7542. * Whether texture values should be sampled or fetched.
  7543. *
  7544. * @type {boolean}
  7545. * @default true
  7546. */
  7547. this.sampler = true;
  7548. /**
  7549. * Whether the uv transformation matrix should be
  7550. * automatically updated or not. Use `setUpdateMatrix()`
  7551. * if you want to change the value of the property.
  7552. *
  7553. * @type {boolean}
  7554. * @default false
  7555. */
  7556. this.updateMatrix = false;
  7557. /**
  7558. * By default the `update()` method is not executed. `setUpdateMatrix()`
  7559. * sets the value to `frame` when the uv transformation matrix should
  7560. * automatically be updated.
  7561. *
  7562. * @type {string}
  7563. * @default 'none'
  7564. */
  7565. this.updateType = NodeUpdateType.NONE;
  7566. /**
  7567. * The reference node.
  7568. *
  7569. * @type {?Node}
  7570. * @default null
  7571. */
  7572. this.referenceNode = null;
  7573. /**
  7574. * The texture value is stored in a private property.
  7575. *
  7576. * @private
  7577. * @type {Texture}
  7578. */
  7579. this._value = value;
  7580. /**
  7581. * The uniform node that represents the uv transformation matrix.
  7582. *
  7583. * @private
  7584. * @type {?UniformNode<mat3>}
  7585. */
  7586. this._matrixUniform = null;
  7587. this.setUpdateMatrix( uvNode === null );
  7588. }
  7589. set value( value ) {
  7590. if ( this.referenceNode ) {
  7591. this.referenceNode.value = value;
  7592. } else {
  7593. this._value = value;
  7594. }
  7595. }
  7596. /**
  7597. * The texture value.
  7598. *
  7599. * @type {Texture}
  7600. */
  7601. get value() {
  7602. return this.referenceNode ? this.referenceNode.value : this._value;
  7603. }
  7604. /**
  7605. * Overwritten since the uniform hash is defined by the texture's UUID.
  7606. *
  7607. * @param {NodeBuilder} builder - The current node builder.
  7608. * @return {string} The uniform hash.
  7609. */
  7610. getUniformHash( /*builder*/ ) {
  7611. return this.value.uuid;
  7612. }
  7613. /**
  7614. * Overwritten since the node type is inferred from the texture type.
  7615. *
  7616. * @param {NodeBuilder} builder - The current node builder.
  7617. * @return {string} The node type.
  7618. */
  7619. getNodeType( /*builder*/ ) {
  7620. if ( this.value.isDepthTexture === true ) return 'float';
  7621. if ( this.value.type === UnsignedIntType ) {
  7622. return 'uvec4';
  7623. } else if ( this.value.type === IntType ) {
  7624. return 'ivec4';
  7625. }
  7626. return 'vec4';
  7627. }
  7628. /**
  7629. * Overwrites the default implementation to return a fixed value `'texture'`.
  7630. *
  7631. * @param {NodeBuilder} builder - The current node builder.
  7632. * @return {string} The input type.
  7633. */
  7634. getInputType( /*builder*/ ) {
  7635. return 'texture';
  7636. }
  7637. /**
  7638. * Returns a default uvs based on the current texture's channel.
  7639. *
  7640. * @return {AttributeNode<vec2>} The default uvs.
  7641. */
  7642. getDefaultUV() {
  7643. return uv$1( this.value.channel );
  7644. }
  7645. /**
  7646. * Overwritten to always return the texture reference of the node.
  7647. *
  7648. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  7649. * @return {Texture} The texture reference.
  7650. */
  7651. updateReference( /*state*/ ) {
  7652. return this.value;
  7653. }
  7654. /**
  7655. * Transforms the given uv node with the texture transformation matrix.
  7656. *
  7657. * @param {Node} uvNode - The uv node to transform.
  7658. * @return {Node} The transformed uv node.
  7659. */
  7660. getTransformedUV( uvNode ) {
  7661. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  7662. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  7663. }
  7664. /**
  7665. * Defines whether the uv transformation matrix should automatically be updated or not.
  7666. *
  7667. * @param {boolean} value - The update toggle.
  7668. * @return {TextureNode} A reference to this node.
  7669. */
  7670. setUpdateMatrix( value ) {
  7671. this.updateMatrix = value;
  7672. this.updateType = value ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  7673. return this;
  7674. }
  7675. /**
  7676. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  7677. * to modify the uv node for correct sampling.
  7678. *
  7679. * @param {NodeBuilder} builder - The current node builder.
  7680. * @param {Node} uvNode - The uv node to setup.
  7681. * @return {Node} The updated uv node.
  7682. */
  7683. setupUV( builder, uvNode ) {
  7684. const texture = this.value;
  7685. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  7686. if ( this.sampler ) {
  7687. uvNode = uvNode.flipY();
  7688. } else {
  7689. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  7690. }
  7691. }
  7692. return uvNode;
  7693. }
  7694. /**
  7695. * Setups texture node by preparing the internal nodes for code generation.
  7696. *
  7697. * @param {NodeBuilder} builder - The current node builder.
  7698. */
  7699. setup( builder ) {
  7700. const properties = builder.getNodeProperties( this );
  7701. properties.referenceNode = this.referenceNode;
  7702. //
  7703. const texture = this.value;
  7704. if ( ! texture || texture.isTexture !== true ) {
  7705. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  7706. }
  7707. //
  7708. let uvNode = this.uvNode;
  7709. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  7710. uvNode = builder.context.getUV( this, builder );
  7711. }
  7712. if ( ! uvNode ) uvNode = this.getDefaultUV();
  7713. if ( this.updateMatrix === true ) {
  7714. uvNode = this.getTransformedUV( uvNode );
  7715. }
  7716. uvNode = this.setupUV( builder, uvNode );
  7717. //
  7718. let levelNode = this.levelNode;
  7719. if ( levelNode === null && builder.context.getTextureLevel ) {
  7720. levelNode = builder.context.getTextureLevel( this );
  7721. }
  7722. //
  7723. properties.uvNode = uvNode;
  7724. properties.levelNode = levelNode;
  7725. properties.biasNode = this.biasNode;
  7726. properties.compareNode = this.compareNode;
  7727. properties.gradNode = this.gradNode;
  7728. properties.depthNode = this.depthNode;
  7729. }
  7730. /**
  7731. * Generates the uv code snippet.
  7732. *
  7733. * @param {NodeBuilder} builder - The current node builder.
  7734. * @param {Node} uvNode - The uv node to generate code for.
  7735. * @return {string} The generated code snippet.
  7736. */
  7737. generateUV( builder, uvNode ) {
  7738. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  7739. }
  7740. /**
  7741. * Generates the snippet for the texture sampling.
  7742. *
  7743. * @param {NodeBuilder} builder - The current node builder.
  7744. * @param {string} textureProperty - The texture property.
  7745. * @param {string} uvSnippet - The uv snippet.
  7746. * @param {?string} levelSnippet - The level snippet.
  7747. * @param {?string} biasSnippet - The bias snippet.
  7748. * @param {?string} depthSnippet - The depth snippet.
  7749. * @param {?string} compareSnippet - The compare snippet.
  7750. * @param {?Array<string>} gradSnippet - The grad snippet.
  7751. * @return {string} The generated code snippet.
  7752. */
  7753. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  7754. const texture = this.value;
  7755. let snippet;
  7756. if ( levelSnippet ) {
  7757. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  7758. } else if ( biasSnippet ) {
  7759. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  7760. } else if ( gradSnippet ) {
  7761. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  7762. } else if ( compareSnippet ) {
  7763. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  7764. } else if ( this.sampler === false ) {
  7765. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  7766. } else {
  7767. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  7768. }
  7769. return snippet;
  7770. }
  7771. /**
  7772. * Generates the code snippet of the texture node.
  7773. *
  7774. * @param {NodeBuilder} builder - The current node builder.
  7775. * @param {string} output - The current output.
  7776. * @return {string} The generated code snippet.
  7777. */
  7778. generate( builder, output ) {
  7779. const texture = this.value;
  7780. const properties = builder.getNodeProperties( this );
  7781. const textureProperty = super.generate( builder, 'property' );
  7782. if ( /^sampler/.test( output ) ) {
  7783. return textureProperty + '_sampler';
  7784. } else if ( builder.isReference( output ) ) {
  7785. return textureProperty;
  7786. } else {
  7787. const nodeData = builder.getDataFromNode( this );
  7788. let propertyName = nodeData.propertyName;
  7789. if ( propertyName === undefined ) {
  7790. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  7791. const uvSnippet = this.generateUV( builder, uvNode );
  7792. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  7793. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  7794. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  7795. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  7796. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  7797. const nodeVar = builder.getVarFromNode( this );
  7798. propertyName = builder.getPropertyName( nodeVar );
  7799. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  7800. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  7801. nodeData.snippet = snippet;
  7802. nodeData.propertyName = propertyName;
  7803. }
  7804. let snippet = propertyName;
  7805. const nodeType = this.getNodeType( builder );
  7806. if ( builder.needsToWorkingColorSpace( texture ) ) {
  7807. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  7808. }
  7809. return builder.format( snippet, nodeType, output );
  7810. }
  7811. }
  7812. /**
  7813. * Sets the sampler value.
  7814. *
  7815. * @param {boolean} value - The sampler value to set.
  7816. * @return {TextureNode} A reference to this texture node.
  7817. */
  7818. setSampler( value ) {
  7819. this.sampler = value;
  7820. return this;
  7821. }
  7822. /**
  7823. * Returns the sampler value.
  7824. *
  7825. * @return {boolean} The sampler value.
  7826. */
  7827. getSampler() {
  7828. return this.sampler;
  7829. }
  7830. // @TODO: Move to TSL
  7831. /**
  7832. * @function
  7833. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  7834. *
  7835. * @param {Node} uvNode - The uv node.
  7836. * @return {TextureNode} A texture node representing the texture sample.
  7837. */
  7838. uv( uvNode ) { // @deprecated, r172
  7839. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  7840. return this.sample( uvNode );
  7841. }
  7842. /**
  7843. * Samples the texture with the given uv node.
  7844. *
  7845. * @param {Node} uvNode - The uv node.
  7846. * @return {TextureNode} A texture node representing the texture sample.
  7847. */
  7848. sample( uvNode ) {
  7849. const textureNode = this.clone();
  7850. textureNode.uvNode = nodeObject( uvNode );
  7851. textureNode.referenceNode = this.getSelf();
  7852. return nodeObject( textureNode );
  7853. }
  7854. /**
  7855. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  7856. *
  7857. * @param {Node<uvec2>} uvNode - The uv node.
  7858. * @returns {TextureNode} A texture node representing the texture load.
  7859. */
  7860. load( uvNode ) {
  7861. return this.sample( uvNode ).setSampler( false );
  7862. }
  7863. /**
  7864. * Samples a blurred version of the texture by defining an internal bias.
  7865. *
  7866. * @param {Node<float>} amountNode - How blurred the texture should be.
  7867. * @return {TextureNode} A texture node representing the texture sample.
  7868. */
  7869. blur( amountNode ) {
  7870. const textureNode = this.clone();
  7871. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  7872. textureNode.referenceNode = this.getSelf();
  7873. const map = textureNode.value;
  7874. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  7875. console.warn( 'THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  7876. textureNode.biasNode = null;
  7877. }
  7878. return nodeObject( textureNode );
  7879. }
  7880. /**
  7881. * Samples a specific mip of the texture.
  7882. *
  7883. * @param {Node<int>} levelNode - The mip level to sample.
  7884. * @return {TextureNode} A texture node representing the texture sample.
  7885. */
  7886. level( levelNode ) {
  7887. const textureNode = this.clone();
  7888. textureNode.levelNode = nodeObject( levelNode );
  7889. textureNode.referenceNode = this.getSelf();
  7890. return nodeObject( textureNode );
  7891. }
  7892. /**
  7893. * Returns the texture size of the requested level.
  7894. *
  7895. * @param {Node<int>} levelNode - The level to compute the size for.
  7896. * @return {TextureSizeNode} The texture size.
  7897. */
  7898. size( levelNode ) {
  7899. return textureSize( this, levelNode );
  7900. }
  7901. /**
  7902. * Samples the texture with the given bias.
  7903. *
  7904. * @param {Node<float>} biasNode - The bias node.
  7905. * @return {TextureNode} A texture node representing the texture sample.
  7906. */
  7907. bias( biasNode ) {
  7908. const textureNode = this.clone();
  7909. textureNode.biasNode = nodeObject( biasNode );
  7910. textureNode.referenceNode = this.getSelf();
  7911. return nodeObject( textureNode );
  7912. }
  7913. /**
  7914. * Samples the texture by executing a compare operation.
  7915. *
  7916. * @param {Node<float>} compareNode - The node that defines the compare value.
  7917. * @return {TextureNode} A texture node representing the texture sample.
  7918. */
  7919. compare( compareNode ) {
  7920. const textureNode = this.clone();
  7921. textureNode.compareNode = nodeObject( compareNode );
  7922. textureNode.referenceNode = this.getSelf();
  7923. return nodeObject( textureNode );
  7924. }
  7925. /**
  7926. * Samples the texture using an explicit gradient.
  7927. *
  7928. * @param {Node<vec2>} gradNodeX - The gradX node.
  7929. * @param {Node<vec2>} gradNodeY - The gradY node.
  7930. * @return {TextureNode} A texture node representing the texture sample.
  7931. */
  7932. grad( gradNodeX, gradNodeY ) {
  7933. const textureNode = this.clone();
  7934. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  7935. textureNode.referenceNode = this.getSelf();
  7936. return nodeObject( textureNode );
  7937. }
  7938. /**
  7939. * Samples the texture by defining a depth node.
  7940. *
  7941. * @param {Node<int>} depthNode - The depth node.
  7942. * @return {TextureNode} A texture node representing the texture sample.
  7943. */
  7944. depth( depthNode ) {
  7945. const textureNode = this.clone();
  7946. textureNode.depthNode = nodeObject( depthNode );
  7947. textureNode.referenceNode = this.getSelf();
  7948. return nodeObject( textureNode );
  7949. }
  7950. // --
  7951. serialize( data ) {
  7952. super.serialize( data );
  7953. data.value = this.value.toJSON( data.meta ).uuid;
  7954. data.sampler = this.sampler;
  7955. data.updateMatrix = this.updateMatrix;
  7956. data.updateType = this.updateType;
  7957. }
  7958. deserialize( data ) {
  7959. super.deserialize( data );
  7960. this.value = data.meta.textures[ data.value ];
  7961. this.sampler = data.sampler;
  7962. this.updateMatrix = data.updateMatrix;
  7963. this.updateType = data.updateType;
  7964. }
  7965. /**
  7966. * The update is used to implement the update of the uv transformation matrix.
  7967. */
  7968. update() {
  7969. const texture = this.value;
  7970. const matrixUniform = this._matrixUniform;
  7971. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  7972. if ( texture.matrixAutoUpdate === true ) {
  7973. texture.updateMatrix();
  7974. }
  7975. }
  7976. /**
  7977. * Clones the texture node.
  7978. *
  7979. * @return {TextureNode} The cloned texture node.
  7980. */
  7981. clone() {
  7982. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  7983. newNode.sampler = this.sampler;
  7984. newNode.depthNode = this.depthNode;
  7985. newNode.compareNode = this.compareNode;
  7986. newNode.gradNode = this.gradNode;
  7987. return newNode;
  7988. }
  7989. }
  7990. /**
  7991. * TSL function for creating a texture node.
  7992. *
  7993. * @tsl
  7994. * @function
  7995. * @param {?Texture} value - The texture.
  7996. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7997. * @param {?Node<int>} [levelNode=null] - The level node.
  7998. * @param {?Node<float>} [biasNode=null] - The bias node.
  7999. * @returns {TextureNode}
  8000. */
  8001. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8002. /**
  8003. * TSL function for creating a texture node or sample a texture node already existing.
  8004. *
  8005. * @tsl
  8006. * @function
  8007. * @param {?Texture|TextureNode} [value=EmptyTexture] - The texture.
  8008. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8009. * @param {?Node<int>} [levelNode=null] - The level node.
  8010. * @param {?Node<float>} [biasNode=null] - The bias node.
  8011. * @returns {TextureNode}
  8012. */
  8013. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8014. let textureNode;
  8015. if ( value && value.isTextureNode === true ) {
  8016. textureNode = nodeObject( value.clone() );
  8017. textureNode.referenceNode = value.getSelf(); // Ensure the reference is set to the original node
  8018. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8019. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8020. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8021. } else {
  8022. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8023. }
  8024. return textureNode;
  8025. };
  8026. /**
  8027. * TSL function for creating a uniform texture node.
  8028. *
  8029. * @tsl
  8030. * @function
  8031. * @param {?Texture} value - The texture.
  8032. * @returns {TextureNode}
  8033. */
  8034. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8035. /**
  8036. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8037. *
  8038. * @tsl
  8039. * @function
  8040. * @param {?Texture|TextureNode} [value=EmptyTexture] - The texture.
  8041. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8042. * @param {?Node<int>} [levelNode=null] - The level node.
  8043. * @param {?Node<float>} [biasNode=null] - The bias node.
  8044. * @returns {TextureNode}
  8045. */
  8046. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8047. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8048. /**
  8049. * Converts a texture or texture node to a sampler.
  8050. *
  8051. * @tsl
  8052. * @function
  8053. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8054. * @returns {Node}
  8055. */
  8056. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8057. /**
  8058. * Converts a texture or texture node to a sampler comparison.
  8059. *
  8060. * @tsl
  8061. * @function
  8062. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8063. * @returns {Node}
  8064. */
  8065. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8066. /**
  8067. * A special type of uniform node which represents array-like data
  8068. * as uniform buffers. The access usually happens via `element()`
  8069. * which returns an instance of {@link ArrayElementNode}. For example:
  8070. *
  8071. * ```js
  8072. * const bufferNode = buffer( array, 'mat4', count );
  8073. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8074. * ```
  8075. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8076. * since it handles more input types and automatically cares about buffer paddings.
  8077. *
  8078. * @augments UniformNode
  8079. */
  8080. class BufferNode extends UniformNode {
  8081. static get type() {
  8082. return 'BufferNode';
  8083. }
  8084. /**
  8085. * Constructs a new buffer node.
  8086. *
  8087. * @param {Array<number>} value - Array-like buffer data.
  8088. * @param {string} bufferType - The data type of the buffer.
  8089. * @param {number} [bufferCount=0] - The count of buffer elements.
  8090. */
  8091. constructor( value, bufferType, bufferCount = 0 ) {
  8092. super( value, bufferType );
  8093. /**
  8094. * This flag can be used for type testing.
  8095. *
  8096. * @type {boolean}
  8097. * @readonly
  8098. * @default true
  8099. */
  8100. this.isBufferNode = true;
  8101. /**
  8102. * The data type of the buffer.
  8103. *
  8104. * @type {string}
  8105. */
  8106. this.bufferType = bufferType;
  8107. /**
  8108. * The uniform node that holds the value of the reference node.
  8109. *
  8110. * @type {number}
  8111. * @default 0
  8112. */
  8113. this.bufferCount = bufferCount;
  8114. }
  8115. /**
  8116. * The data type of the buffer elements.
  8117. *
  8118. * @param {NodeBuilder} builder - The current node builder.
  8119. * @return {string} The element type.
  8120. */
  8121. getElementType( builder ) {
  8122. return this.getNodeType( builder );
  8123. }
  8124. /**
  8125. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8126. *
  8127. * @param {NodeBuilder} builder - The current node builder.
  8128. * @return {string} The input type.
  8129. */
  8130. getInputType( /*builder*/ ) {
  8131. return 'buffer';
  8132. }
  8133. }
  8134. /**
  8135. * TSL function for creating a buffer node.
  8136. *
  8137. * @tsl
  8138. * @function
  8139. * @param {Array} value - Array-like buffer data.
  8140. * @param {string} type - The data type of a buffer element.
  8141. * @param {number} count - The count of buffer elements.
  8142. * @returns {BufferNode}
  8143. */
  8144. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  8145. /**
  8146. * Represents the element access on uniform array nodes.
  8147. *
  8148. * @augments ArrayElementNode
  8149. */
  8150. class UniformArrayElementNode extends ArrayElementNode {
  8151. static get type() {
  8152. return 'UniformArrayElementNode';
  8153. }
  8154. /**
  8155. * Constructs a new buffer node.
  8156. *
  8157. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8158. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8159. */
  8160. constructor( uniformArrayNode, indexNode ) {
  8161. super( uniformArrayNode, indexNode );
  8162. /**
  8163. * This flag can be used for type testing.
  8164. *
  8165. * @type {boolean}
  8166. * @readonly
  8167. * @default true
  8168. */
  8169. this.isArrayBufferElementNode = true;
  8170. }
  8171. generate( builder ) {
  8172. const snippet = super.generate( builder );
  8173. const type = this.getNodeType();
  8174. const paddedType = this.node.getPaddedType();
  8175. return builder.format( snippet, paddedType, type );
  8176. }
  8177. }
  8178. /**
  8179. * Similar to {@link BufferNode} this module represents array-like data as
  8180. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8181. * data types in the array (e.g `three.js` primitives) and automatically
  8182. * manage buffer padding. It should be the first choice when working with
  8183. * uniforms buffers.
  8184. * ```js
  8185. * const tintColors = uniformArray( [
  8186. * new Color( 1, 0, 0 ),
  8187. * new Color( 0, 1, 0 ),
  8188. * new Color( 0, 0, 1 )
  8189. * ], 'color' );
  8190. *
  8191. * const redColor = tintColors.element( 0 );
  8192. *
  8193. * @augments BufferNode
  8194. */
  8195. class UniformArrayNode extends BufferNode {
  8196. static get type() {
  8197. return 'UniformArrayNode';
  8198. }
  8199. /**
  8200. * Constructs a new uniform array node.
  8201. *
  8202. * @param {Array<any>} value - Array holding the buffer data.
  8203. * @param {?string} [elementType=null] - The data type of a buffer element.
  8204. */
  8205. constructor( value, elementType = null ) {
  8206. super( null );
  8207. /**
  8208. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8209. * hold number primitives as well as three.js objects like vectors, matrices
  8210. * or colors.
  8211. *
  8212. * @type {Array<any>}
  8213. */
  8214. this.array = value;
  8215. /**
  8216. * The data type of an array element.
  8217. *
  8218. * @type {string}
  8219. */
  8220. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8221. /**
  8222. * The padded type. Uniform buffers must conform to a certain buffer layout
  8223. * so a separate type is computed to ensure correct buffer size.
  8224. *
  8225. * @type {string}
  8226. */
  8227. this.paddedType = this.getPaddedType();
  8228. /**
  8229. * Overwritten since uniform array nodes are updated per render.
  8230. *
  8231. * @type {string}
  8232. * @default 'render'
  8233. */
  8234. this.updateType = NodeUpdateType.RENDER;
  8235. /**
  8236. * This flag can be used for type testing.
  8237. *
  8238. * @type {boolean}
  8239. * @readonly
  8240. * @default true
  8241. */
  8242. this.isArrayBufferNode = true;
  8243. }
  8244. /**
  8245. * This method is overwritten since the node type is inferred from the
  8246. * {@link UniformArrayNode#paddedType}.
  8247. *
  8248. * @param {NodeBuilder} builder - The current node builder.
  8249. * @return {string} The node type.
  8250. */
  8251. getNodeType( /*builder*/ ) {
  8252. return this.paddedType;
  8253. }
  8254. /**
  8255. * The data type of the array elements.
  8256. *
  8257. * @param {NodeBuilder} builder - The current node builder.
  8258. * @return {string} The element type.
  8259. */
  8260. getElementType() {
  8261. return this.elementType;
  8262. }
  8263. /**
  8264. * Returns the padded type based on the element type.
  8265. *
  8266. * @return {string} The padded type.
  8267. */
  8268. getPaddedType() {
  8269. const elementType = this.elementType;
  8270. let paddedType = 'vec4';
  8271. if ( elementType === 'mat2' ) {
  8272. paddedType = 'mat2';
  8273. } else if ( /mat/.test( elementType ) === true ) {
  8274. paddedType = 'mat4';
  8275. } else if ( elementType.charAt( 0 ) === 'i' ) {
  8276. paddedType = 'ivec4';
  8277. } else if ( elementType.charAt( 0 ) === 'u' ) {
  8278. paddedType = 'uvec4';
  8279. }
  8280. return paddedType;
  8281. }
  8282. /**
  8283. * The update makes sure to correctly transfer the data from the (complex) objects
  8284. * in the array to the internal, correctly padded value buffer.
  8285. *
  8286. * @param {NodeFrame} frame - A reference to the current node frame.
  8287. */
  8288. update( /*frame*/ ) {
  8289. const { array, value } = this;
  8290. const elementType = this.elementType;
  8291. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  8292. for ( let i = 0; i < array.length; i ++ ) {
  8293. const index = i * 4;
  8294. value[ index ] = array[ i ];
  8295. }
  8296. } else if ( elementType === 'color' ) {
  8297. for ( let i = 0; i < array.length; i ++ ) {
  8298. const index = i * 4;
  8299. const vector = array[ i ];
  8300. value[ index ] = vector.r;
  8301. value[ index + 1 ] = vector.g;
  8302. value[ index + 2 ] = vector.b || 0;
  8303. //value[ index + 3 ] = vector.a || 0;
  8304. }
  8305. } else if ( elementType === 'mat2' ) {
  8306. for ( let i = 0; i < array.length; i ++ ) {
  8307. const index = i * 4;
  8308. const matrix = array[ i ];
  8309. value[ index ] = matrix.elements[ 0 ];
  8310. value[ index + 1 ] = matrix.elements[ 1 ];
  8311. value[ index + 2 ] = matrix.elements[ 2 ];
  8312. value[ index + 3 ] = matrix.elements[ 3 ];
  8313. }
  8314. } else if ( elementType === 'mat3' ) {
  8315. for ( let i = 0; i < array.length; i ++ ) {
  8316. const index = i * 16;
  8317. const matrix = array[ i ];
  8318. value[ index ] = matrix.elements[ 0 ];
  8319. value[ index + 1 ] = matrix.elements[ 1 ];
  8320. value[ index + 2 ] = matrix.elements[ 2 ];
  8321. value[ index + 4 ] = matrix.elements[ 3 ];
  8322. value[ index + 5 ] = matrix.elements[ 4 ];
  8323. value[ index + 6 ] = matrix.elements[ 5 ];
  8324. value[ index + 8 ] = matrix.elements[ 6 ];
  8325. value[ index + 9 ] = matrix.elements[ 7 ];
  8326. value[ index + 10 ] = matrix.elements[ 8 ];
  8327. value[ index + 15 ] = 1;
  8328. }
  8329. } else if ( elementType === 'mat4' ) {
  8330. for ( let i = 0; i < array.length; i ++ ) {
  8331. const index = i * 16;
  8332. const matrix = array[ i ];
  8333. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  8334. value[ index + i ] = matrix.elements[ i ];
  8335. }
  8336. }
  8337. } else {
  8338. for ( let i = 0; i < array.length; i ++ ) {
  8339. const index = i * 4;
  8340. const vector = array[ i ];
  8341. value[ index ] = vector.x;
  8342. value[ index + 1 ] = vector.y;
  8343. value[ index + 2 ] = vector.z || 0;
  8344. value[ index + 3 ] = vector.w || 0;
  8345. }
  8346. }
  8347. }
  8348. /**
  8349. * Implement the value buffer creation based on the array data.
  8350. *
  8351. * @param {NodeBuilder} builder - A reference to the current node builder.
  8352. * @return {null}
  8353. */
  8354. setup( builder ) {
  8355. const length = this.array.length;
  8356. const elementType = this.elementType;
  8357. let arrayType = Float32Array;
  8358. const paddedType = this.paddedType;
  8359. const paddedElementLength = builder.getTypeLength( paddedType );
  8360. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  8361. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  8362. this.value = new arrayType( length * paddedElementLength );
  8363. this.bufferCount = length;
  8364. this.bufferType = paddedType;
  8365. return super.setup( builder );
  8366. }
  8367. /**
  8368. * Overwrites the default `element()` method to provide element access
  8369. * based on {@link UniformArrayNode}.
  8370. *
  8371. * @param {IndexNode} indexNode - The index node.
  8372. * @return {UniformArrayElementNode}
  8373. */
  8374. element( indexNode ) {
  8375. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  8376. }
  8377. }
  8378. /**
  8379. * TSL function for creating an uniform array node.
  8380. *
  8381. * @tsl
  8382. * @function
  8383. * @param {Array<any>} values - Array-like data.
  8384. * @param {?string} [nodeType] - The data type of the array elements.
  8385. * @returns {UniformArrayNode}
  8386. */
  8387. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  8388. /**
  8389. * The node allows to set values for built-in shader variables. That is
  8390. * required for features like hardware-accelerated vertex clipping.
  8391. *
  8392. * @augments Node
  8393. */
  8394. class BuiltinNode extends Node {
  8395. /**
  8396. * Constructs a new builtin node.
  8397. *
  8398. * @param {string} name - The name of the built-in shader variable.
  8399. */
  8400. constructor( name ) {
  8401. super( 'float' );
  8402. /**
  8403. * The name of the built-in shader variable.
  8404. *
  8405. * @type {string}
  8406. */
  8407. this.name = name;
  8408. /**
  8409. * This flag can be used for type testing.
  8410. *
  8411. * @type {boolean}
  8412. * @readonly
  8413. * @default true
  8414. */
  8415. this.isBuiltinNode = true;
  8416. }
  8417. /**
  8418. * Generates the code snippet of the builtin node.
  8419. *
  8420. * @param {NodeBuilder} builder - The current node builder.
  8421. * @return {string} The generated code snippet.
  8422. */
  8423. generate( /* builder */ ) {
  8424. return this.name;
  8425. }
  8426. }
  8427. /**
  8428. * TSL function for creating a builtin node.
  8429. *
  8430. * @tsl
  8431. * @function
  8432. * @param {string} name - The name of the built-in shader variable.
  8433. * @returns {BuiltinNode}
  8434. */
  8435. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  8436. /**
  8437. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  8438. *
  8439. * @tsl
  8440. * @type {UniformNode<uint>}
  8441. */
  8442. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  8443. /**
  8444. * TSL object that represents the `near` value of the camera used for the current render.
  8445. *
  8446. * @tsl
  8447. * @type {UniformNode<float>}
  8448. */
  8449. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  8450. /**
  8451. * TSL object that represents the `far` value of the camera used for the current render.
  8452. *
  8453. * @tsl
  8454. * @type {UniformNode<float>}
  8455. */
  8456. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  8457. /**
  8458. * TSL object that represents the projection matrix of the camera used for the current render.
  8459. *
  8460. * @tsl
  8461. * @type {UniformNode<mat4>}
  8462. */
  8463. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8464. let cameraProjectionMatrix;
  8465. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8466. const matrices = [];
  8467. for ( const subCamera of camera.cameras ) {
  8468. matrices.push( subCamera.projectionMatrix );
  8469. }
  8470. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  8471. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraProjectionMatrix' );
  8472. } else {
  8473. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  8474. }
  8475. return cameraProjectionMatrix;
  8476. } ).once() )();
  8477. /**
  8478. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  8479. *
  8480. * @tsl
  8481. * @type {UniformNode<mat4>}
  8482. */
  8483. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8484. let cameraProjectionMatrixInverse;
  8485. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8486. const matrices = [];
  8487. for ( const subCamera of camera.cameras ) {
  8488. matrices.push( subCamera.projectionMatrixInverse );
  8489. }
  8490. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  8491. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraProjectionMatrixInverse' );
  8492. } else {
  8493. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  8494. }
  8495. return cameraProjectionMatrixInverse;
  8496. } ).once() )();
  8497. /**
  8498. * TSL object that represents the view matrix of the camera used for the current render.
  8499. *
  8500. * @tsl
  8501. * @type {UniformNode<mat4>}
  8502. */
  8503. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8504. let cameraViewMatrix;
  8505. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8506. const matrices = [];
  8507. for ( const subCamera of camera.cameras ) {
  8508. matrices.push( subCamera.matrixWorldInverse );
  8509. }
  8510. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  8511. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraViewMatrix' );
  8512. } else {
  8513. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  8514. }
  8515. return cameraViewMatrix;
  8516. } ).once() )();
  8517. /**
  8518. * TSL object that represents the world matrix of the camera used for the current render.
  8519. *
  8520. * @tsl
  8521. * @type {UniformNode<mat4>}
  8522. */
  8523. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  8524. /**
  8525. * TSL object that represents the normal matrix of the camera used for the current render.
  8526. *
  8527. * @tsl
  8528. * @type {UniformNode<mat3>}
  8529. */
  8530. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  8531. /**
  8532. * TSL object that represents the position in world space of the camera used for the current render.
  8533. *
  8534. * @tsl
  8535. * @type {UniformNode<vec3>}
  8536. */
  8537. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  8538. const _sphere = /*@__PURE__*/ new Sphere();
  8539. /**
  8540. * This node can be used to access transformation related metrics of 3D objects.
  8541. * Depending on the selected scope, a different metric is represented as a uniform
  8542. * in the shader. The following scopes are supported:
  8543. *
  8544. * - `POSITION`: The object's position in world space.
  8545. * - `VIEW_POSITION`: The object's position in view/camera space.
  8546. * - `DIRECTION`: The object's direction in world space.
  8547. * - `SCALE`: The object's scale in world space.
  8548. * - `WORLD_MATRIX`: The object's matrix in world space.
  8549. *
  8550. * @augments Node
  8551. */
  8552. class Object3DNode extends Node {
  8553. static get type() {
  8554. return 'Object3DNode';
  8555. }
  8556. /**
  8557. * Constructs a new object 3D node.
  8558. *
  8559. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8560. * @param {?Object3D} [object3d=null] - The 3D object.
  8561. */
  8562. constructor( scope, object3d = null ) {
  8563. super();
  8564. /**
  8565. * The node reports a different type of transformation depending on the scope.
  8566. *
  8567. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  8568. */
  8569. this.scope = scope;
  8570. /**
  8571. * The 3D object.
  8572. *
  8573. * @type {?Object3D}
  8574. * @default null
  8575. */
  8576. this.object3d = object3d;
  8577. /**
  8578. * Overwritten since this type of node is updated per object.
  8579. *
  8580. * @type {string}
  8581. * @default 'object'
  8582. */
  8583. this.updateType = NodeUpdateType.OBJECT;
  8584. /**
  8585. * Holds the value of the node as a uniform.
  8586. *
  8587. * @type {UniformNode}
  8588. */
  8589. this.uniformNode = new UniformNode( null );
  8590. }
  8591. /**
  8592. * Overwritten since the node type is inferred from the scope.
  8593. *
  8594. * @return {string} The node type.
  8595. */
  8596. getNodeType() {
  8597. const scope = this.scope;
  8598. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8599. return 'mat4';
  8600. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8601. return 'vec3';
  8602. } else if ( scope === Object3DNode.RADIUS ) {
  8603. return 'float';
  8604. }
  8605. }
  8606. /**
  8607. * Updates the uniform value depending on the scope.
  8608. *
  8609. * @param {NodeFrame} frame - The current node frame.
  8610. */
  8611. update( frame ) {
  8612. const object = this.object3d;
  8613. const uniformNode = this.uniformNode;
  8614. const scope = this.scope;
  8615. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8616. uniformNode.value = object.matrixWorld;
  8617. } else if ( scope === Object3DNode.POSITION ) {
  8618. uniformNode.value = uniformNode.value || new Vector3();
  8619. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8620. } else if ( scope === Object3DNode.SCALE ) {
  8621. uniformNode.value = uniformNode.value || new Vector3();
  8622. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  8623. } else if ( scope === Object3DNode.DIRECTION ) {
  8624. uniformNode.value = uniformNode.value || new Vector3();
  8625. object.getWorldDirection( uniformNode.value );
  8626. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  8627. const camera = frame.camera;
  8628. uniformNode.value = uniformNode.value || new Vector3();
  8629. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8630. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  8631. } else if ( scope === Object3DNode.RADIUS ) {
  8632. const geometry = frame.object.geometry;
  8633. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8634. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8635. uniformNode.value = _sphere.radius;
  8636. }
  8637. }
  8638. /**
  8639. * Generates the code snippet of the uniform node. The node type of the uniform
  8640. * node also depends on the selected scope.
  8641. *
  8642. * @param {NodeBuilder} builder - The current node builder.
  8643. * @return {string} The generated code snippet.
  8644. */
  8645. generate( builder ) {
  8646. const scope = this.scope;
  8647. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8648. this.uniformNode.nodeType = 'mat4';
  8649. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8650. this.uniformNode.nodeType = 'vec3';
  8651. } else if ( scope === Object3DNode.RADIUS ) {
  8652. this.uniformNode.nodeType = 'float';
  8653. }
  8654. return this.uniformNode.build( builder );
  8655. }
  8656. serialize( data ) {
  8657. super.serialize( data );
  8658. data.scope = this.scope;
  8659. }
  8660. deserialize( data ) {
  8661. super.deserialize( data );
  8662. this.scope = data.scope;
  8663. }
  8664. }
  8665. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  8666. Object3DNode.POSITION = 'position';
  8667. Object3DNode.SCALE = 'scale';
  8668. Object3DNode.VIEW_POSITION = 'viewPosition';
  8669. Object3DNode.DIRECTION = 'direction';
  8670. Object3DNode.RADIUS = 'radius';
  8671. /**
  8672. * TSL function for creating an object 3D node that represents the object's direction in world space.
  8673. *
  8674. * @tsl
  8675. * @function
  8676. * @param {?Object3D} [object3d] - The 3D object.
  8677. * @returns {Object3DNode<vec3>}
  8678. */
  8679. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  8680. /**
  8681. * TSL function for creating an object 3D node that represents the object's world matrix.
  8682. *
  8683. * @tsl
  8684. * @function
  8685. * @param {?Object3D} [object3d] - The 3D object.
  8686. * @returns {Object3DNode<mat4>}
  8687. */
  8688. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  8689. /**
  8690. * TSL function for creating an object 3D node that represents the object's position in world space.
  8691. *
  8692. * @tsl
  8693. * @function
  8694. * @param {?Object3D} [object3d] - The 3D object.
  8695. * @returns {Object3DNode<vec3>}
  8696. */
  8697. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  8698. /**
  8699. * TSL function for creating an object 3D node that represents the object's scale in world space.
  8700. *
  8701. * @tsl
  8702. * @function
  8703. * @param {?Object3D} [object3d] - The 3D object.
  8704. * @returns {Object3DNode<vec3>}
  8705. */
  8706. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  8707. /**
  8708. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  8709. *
  8710. * @tsl
  8711. * @function
  8712. * @param {?Object3D} [object3d] - The 3D object.
  8713. * @returns {Object3DNode<vec3>}
  8714. */
  8715. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  8716. /**
  8717. * TSL function for creating an object 3D node that represents the object's radius.
  8718. *
  8719. * @tsl
  8720. * @function
  8721. * @param {?Object3D} [object3d] - The 3D object.
  8722. * @returns {Object3DNode<float>}
  8723. */
  8724. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  8725. /**
  8726. * This type of node is a specialized version of `Object3DNode`
  8727. * with larger set of model related metrics. Unlike `Object3DNode`,
  8728. * `ModelNode` extracts the reference to the 3D object from the
  8729. * current node frame state.
  8730. *
  8731. * @augments Object3DNode
  8732. */
  8733. class ModelNode extends Object3DNode {
  8734. static get type() {
  8735. return 'ModelNode';
  8736. }
  8737. /**
  8738. * Constructs a new object model node.
  8739. *
  8740. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8741. */
  8742. constructor( scope ) {
  8743. super( scope );
  8744. }
  8745. /**
  8746. * Extracts the model reference from the frame state and then
  8747. * updates the uniform value depending on the scope.
  8748. *
  8749. * @param {NodeFrame} frame - The current node frame.
  8750. */
  8751. update( frame ) {
  8752. this.object3d = frame.object;
  8753. super.update( frame );
  8754. }
  8755. }
  8756. /**
  8757. * TSL object that represents the object's direction in world space.
  8758. *
  8759. * @tsl
  8760. * @type {ModelNode<vec3>}
  8761. */
  8762. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  8763. /**
  8764. * TSL object that represents the object's world matrix.
  8765. *
  8766. * @tsl
  8767. * @type {ModelNode<mat4>}
  8768. */
  8769. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  8770. /**
  8771. * TSL object that represents the object's position in world space.
  8772. *
  8773. * @tsl
  8774. * @type {ModelNode<vec3>}
  8775. */
  8776. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  8777. /**
  8778. * TSL object that represents the object's scale in world space.
  8779. *
  8780. * @tsl
  8781. * @type {ModelNode<vec3>}
  8782. */
  8783. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  8784. /**
  8785. * TSL object that represents the object's position in view/camera space.
  8786. *
  8787. * @tsl
  8788. * @type {ModelNode<vec3>}
  8789. */
  8790. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  8791. /**
  8792. * TSL object that represents the object's radius.
  8793. *
  8794. * @tsl
  8795. * @type {ModelNode<float>}
  8796. */
  8797. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  8798. /**
  8799. * TSL object that represents the object's normal matrix.
  8800. *
  8801. * @tsl
  8802. * @type {UniformNode<mat3>}
  8803. */
  8804. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  8805. /**
  8806. * TSL object that represents the object's inverse world matrix.
  8807. *
  8808. * @tsl
  8809. * @type {UniformNode<mat4>}
  8810. */
  8811. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  8812. /**
  8813. * TSL object that represents the object's model view matrix.
  8814. *
  8815. * @tsl
  8816. * @type {Node<mat4>}
  8817. */
  8818. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8819. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  8820. } ).once() )().toVar( 'modelViewMatrix' );
  8821. // GPU Precision
  8822. /**
  8823. * TSL object that represents the object's model view in `mediump` precision.
  8824. *
  8825. * @tsl
  8826. * @type {Node<mat4>}
  8827. */
  8828. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  8829. // CPU Precision
  8830. /**
  8831. * TSL object that represents the object's model view in `highp` precision
  8832. * which is achieved by computing the matrix in JS and not in the shader.
  8833. *
  8834. * @tsl
  8835. * @type {Node<mat4>}
  8836. */
  8837. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8838. builder.context.isHighPrecisionModelViewMatrix = true;
  8839. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  8840. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  8841. } );
  8842. } ).once() )().toVar( 'highpModelViewMatrix' );
  8843. /**
  8844. * TSL object that represents the object's model normal view in `highp` precision
  8845. * which is achieved by computing the matrix in JS and not in the shader.
  8846. *
  8847. * @tsl
  8848. * @type {Node<mat3>}
  8849. */
  8850. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8851. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  8852. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  8853. if ( isHighPrecisionModelViewMatrix !== true ) {
  8854. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  8855. }
  8856. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  8857. } );
  8858. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  8859. /**
  8860. * TSL object that represents the position attribute of the current rendered object.
  8861. *
  8862. * @tsl
  8863. * @type {AttributeNode<vec3>}
  8864. */
  8865. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  8866. /**
  8867. * TSL object that represents the vertex position in local space of the current rendered object.
  8868. *
  8869. * @tsl
  8870. * @type {AttributeNode<vec3>}
  8871. */
  8872. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  8873. /**
  8874. * TSL object that represents the previous vertex position in local space of the current rendered object.
  8875. * Used in context of {@link VelocityNode} for rendering motion vectors.
  8876. *
  8877. * @tsl
  8878. * @type {AttributeNode<vec3>}
  8879. */
  8880. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  8881. /**
  8882. * TSL object that represents the vertex position in world space of the current rendered object.
  8883. *
  8884. * @tsl
  8885. * @type {VaryingNode<vec3>}
  8886. */
  8887. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  8888. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  8889. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  8890. /**
  8891. * TSL object that represents the position world direction of the current rendered object.
  8892. *
  8893. * @tsl
  8894. * @type {Node<vec3>}
  8895. */
  8896. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  8897. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  8898. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  8899. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  8900. /**
  8901. * TSL object that represents the vertex position in view space of the current rendered object.
  8902. *
  8903. * @tsl
  8904. * @type {VaryingNode<vec3>}
  8905. */
  8906. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8907. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  8908. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  8909. /**
  8910. * TSL object that represents the position view direction of the current rendered object.
  8911. *
  8912. * @tsl
  8913. * @type {VaryingNode<vec3>}
  8914. */
  8915. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  8916. /**
  8917. * This node can be used to evaluate whether a primitive is front or back facing.
  8918. *
  8919. * @augments Node
  8920. */
  8921. class FrontFacingNode extends Node {
  8922. static get type() {
  8923. return 'FrontFacingNode';
  8924. }
  8925. /**
  8926. * Constructs a new front facing node.
  8927. */
  8928. constructor() {
  8929. super( 'bool' );
  8930. /**
  8931. * This flag can be used for type testing.
  8932. *
  8933. * @type {boolean}
  8934. * @readonly
  8935. * @default true
  8936. */
  8937. this.isFrontFacingNode = true;
  8938. }
  8939. generate( builder ) {
  8940. if ( builder.shaderStage !== 'fragment' ) return 'true';
  8941. //
  8942. const { renderer, material } = builder;
  8943. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  8944. if ( material.side === BackSide ) {
  8945. return 'false';
  8946. }
  8947. }
  8948. return builder.getFrontFacing();
  8949. }
  8950. }
  8951. /**
  8952. * TSL object that represents whether a primitive is front or back facing
  8953. *
  8954. * @tsl
  8955. * @type {FrontFacingNode<bool>}
  8956. */
  8957. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  8958. /**
  8959. * TSL object that represents the front facing status as a number instead of a bool.
  8960. * `1` means front facing, `-1` means back facing.
  8961. *
  8962. * @tsl
  8963. * @type {Node<float>}
  8964. */
  8965. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  8966. /**
  8967. * Converts a direction vector to a face direction vector based on the material's side.
  8968. *
  8969. * If the material is set to `BackSide`, the direction is inverted.
  8970. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  8971. *
  8972. * @tsl
  8973. * @param {Node<vec3>} direction - The direction vector to convert.
  8974. * @returns {Node<vec3>} The converted direction vector.
  8975. */
  8976. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  8977. const side = material.side;
  8978. if ( side === BackSide ) {
  8979. direction = direction.mul( -1 );
  8980. } else if ( side === DoubleSide ) {
  8981. direction = direction.mul( faceDirection );
  8982. }
  8983. return direction;
  8984. } );
  8985. /**
  8986. * TSL object that represents the normal attribute of the current rendered object in local space.
  8987. *
  8988. * @tsl
  8989. * @type {Node<vec3>}
  8990. */
  8991. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  8992. /**
  8993. * TSL object that represents the vertex normal of the current rendered object in local space.
  8994. *
  8995. * @tsl
  8996. * @type {Node<vec3>}
  8997. */
  8998. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  8999. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  9000. console.warn( 'THREE.TSL: Vertex attribute "normal" not found on geometry.' );
  9001. return vec3( 0, 1, 0 );
  9002. }
  9003. return normalGeometry;
  9004. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  9005. /**
  9006. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  9007. *
  9008. * @tsl
  9009. * @type {Node<vec3>}
  9010. */
  9011. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  9012. /**
  9013. * TSL object that represents the vertex normal of the current rendered object in view space.
  9014. *
  9015. * @tsl
  9016. * @type {Node<vec3>}
  9017. */
  9018. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9019. let node;
  9020. if ( builder.material.flatShading === true ) {
  9021. node = normalFlat;
  9022. } else {
  9023. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  9024. }
  9025. return node;
  9026. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  9027. /**
  9028. * TSL object that represents the vertex normal of the current rendered object in world space.
  9029. *
  9030. * @tsl
  9031. * @type {Node<vec3>}
  9032. */
  9033. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9034. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  9035. if ( builder.material.flatShading !== true ) {
  9036. normal = normal.toVarying( 'v_normalWorldGeometry' );
  9037. }
  9038. return normal.normalize().toVar( 'normalWorldGeometry' );
  9039. }, 'vec3' ).once() )();
  9040. /**
  9041. * TSL object that represents the vertex normal of the current rendered object in view space.
  9042. *
  9043. * @tsl
  9044. * @type {Node<vec3>}
  9045. */
  9046. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  9047. let node;
  9048. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9049. node = normalViewGeometry;
  9050. if ( material.flatShading !== true ) {
  9051. node = directionToFaceDirection( node );
  9052. }
  9053. } else {
  9054. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9055. node = context.setupNormal().context( { getUV: null } );
  9056. }
  9057. return node;
  9058. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  9059. /**
  9060. * TSL object that represents the vertex normal of the current rendered object in world space.
  9061. *
  9062. * @tsl
  9063. * @type {Node<vec3>}
  9064. */
  9065. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  9066. /**
  9067. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  9068. *
  9069. * @tsl
  9070. * @type {Node<vec3>}
  9071. */
  9072. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  9073. let node;
  9074. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9075. node = normalView;
  9076. } else {
  9077. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9078. node = context.setupClearcoatNormal().context( { getUV: null } );
  9079. }
  9080. return node;
  9081. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  9082. /**
  9083. * Transforms the normal with the given matrix.
  9084. *
  9085. * @tsl
  9086. * @function
  9087. * @param {Node<vec3>} normal - The normal.
  9088. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  9089. * @return {Node<vec3>} The transformed normal.
  9090. */
  9091. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  9092. const m = mat3( matrix );
  9093. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  9094. return m.mul( transformedNormal ).xyz;
  9095. } );
  9096. /**
  9097. * Transforms the given normal from local to view space.
  9098. *
  9099. * @tsl
  9100. * @function
  9101. * @param {Node<vec3>} normal - The normal.
  9102. * @param {NodeBuilder} builder - The current node builder.
  9103. * @return {Node<vec3>} The transformed normal.
  9104. */
  9105. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  9106. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  9107. if ( modelNormalViewMatrix !== null ) {
  9108. return modelNormalViewMatrix.transformDirection( normal );
  9109. }
  9110. //
  9111. const transformedNormal = modelNormalMatrix.mul( normal );
  9112. return cameraViewMatrix.transformDirection( transformedNormal );
  9113. } );
  9114. // Deprecated
  9115. /**
  9116. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  9117. *
  9118. * @tsl
  9119. * @type {Node<vec3>}
  9120. * @deprecated since r178. Use `normalView` instead.
  9121. */
  9122. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  9123. console.warn( 'THREE.TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  9124. return normalView;
  9125. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9126. /**
  9127. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  9128. *
  9129. * @tsl
  9130. * @type {Node<vec3>}
  9131. * @deprecated since r178. Use `normalWorld` instead.
  9132. */
  9133. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  9134. console.warn( 'THREE.TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  9135. return normalWorld;
  9136. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9137. /**
  9138. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  9139. *
  9140. * @tsl
  9141. * @type {Node<vec3>}
  9142. * @deprecated since r178. Use `clearcoatNormalView` instead.
  9143. */
  9144. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  9145. console.warn( 'THREE.TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  9146. return clearcoatNormalView;
  9147. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9148. const _e1$1 = /*@__PURE__*/ new Euler();
  9149. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9150. /**
  9151. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  9152. *
  9153. * @tsl
  9154. * @type {UniformNode<float>}
  9155. */
  9156. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  9157. /**
  9158. * TSL object that represents the intensity of environment maps of PBR materials.
  9159. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  9160. *
  9161. * @tsl
  9162. * @type {Node<float>}
  9163. */
  9164. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  9165. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  9166. } );
  9167. /**
  9168. * TSL object that represents the rotation of environment maps.
  9169. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  9170. * rotation of `scene.environment` instead.
  9171. *
  9172. * @tsl
  9173. * @type {Node<mat4>}
  9174. */
  9175. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  9176. return frame.material;
  9177. } ).onObjectUpdate( function ( { material, scene } ) {
  9178. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  9179. if ( rotation ) {
  9180. _e1$1.copy( rotation );
  9181. _m1$1.makeRotationFromEuler( _e1$1 );
  9182. } else {
  9183. _m1$1.identity();
  9184. }
  9185. return _m1$1;
  9186. } );
  9187. /**
  9188. * The reflect vector in view space.
  9189. *
  9190. * @tsl
  9191. * @type {Node<vec3>}
  9192. */
  9193. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  9194. /**
  9195. * The refract vector in view space.
  9196. *
  9197. * @tsl
  9198. * @type {Node<vec3>}
  9199. */
  9200. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  9201. /**
  9202. * Used for sampling cube maps when using cube reflection mapping.
  9203. *
  9204. * @tsl
  9205. * @type {Node<vec3>}
  9206. */
  9207. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9208. /**
  9209. * Used for sampling cube maps when using cube refraction mapping.
  9210. *
  9211. * @tsl
  9212. * @type {Node<vec3>}
  9213. */
  9214. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9215. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  9216. /**
  9217. * This type of uniform node represents a cube texture.
  9218. *
  9219. * @augments TextureNode
  9220. */
  9221. class CubeTextureNode extends TextureNode {
  9222. static get type() {
  9223. return 'CubeTextureNode';
  9224. }
  9225. /**
  9226. * Constructs a new cube texture node.
  9227. *
  9228. * @param {CubeTexture} value - The cube texture.
  9229. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9230. * @param {?Node<int>} [levelNode=null] - The level node.
  9231. * @param {?Node<float>} [biasNode=null] - The bias node.
  9232. */
  9233. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  9234. super( value, uvNode, levelNode, biasNode );
  9235. /**
  9236. * This flag can be used for type testing.
  9237. *
  9238. * @type {boolean}
  9239. * @readonly
  9240. * @default true
  9241. */
  9242. this.isCubeTextureNode = true;
  9243. }
  9244. /**
  9245. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  9246. *
  9247. * @param {NodeBuilder} builder - The current node builder.
  9248. * @return {string} The input type.
  9249. */
  9250. getInputType( /*builder*/ ) {
  9251. return 'cubeTexture';
  9252. }
  9253. /**
  9254. * Returns a default uvs based on the mapping type of the cube texture.
  9255. *
  9256. * @return {Node<vec3>} The default uv attribute.
  9257. */
  9258. getDefaultUV() {
  9259. const texture = this.value;
  9260. if ( texture.mapping === CubeReflectionMapping ) {
  9261. return reflectVector;
  9262. } else if ( texture.mapping === CubeRefractionMapping ) {
  9263. return refractVector;
  9264. } else {
  9265. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  9266. return vec3( 0, 0, 0 );
  9267. }
  9268. }
  9269. /**
  9270. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  9271. * for cube textures. The uv transformation matrix is not applied to cube textures.
  9272. *
  9273. * @param {boolean} value - The update toggle.
  9274. */
  9275. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  9276. /**
  9277. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  9278. * to modify the uv node for correct sampling.
  9279. *
  9280. * @param {NodeBuilder} builder - The current node builder.
  9281. * @param {Node} uvNode - The uv node to setup.
  9282. * @return {Node} The updated uv node.
  9283. */
  9284. setupUV( builder, uvNode ) {
  9285. const texture = this.value;
  9286. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  9287. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  9288. }
  9289. return materialEnvRotation.mul( uvNode );
  9290. }
  9291. /**
  9292. * Generates the uv code snippet.
  9293. *
  9294. * @param {NodeBuilder} builder - The current node builder.
  9295. * @param {Node} cubeUV - The uv node to generate code for.
  9296. * @return {string} The generated code snippet.
  9297. */
  9298. generateUV( builder, cubeUV ) {
  9299. return cubeUV.build( builder, 'vec3' );
  9300. }
  9301. }
  9302. /**
  9303. * TSL function for creating a cube texture node.
  9304. *
  9305. * @tsl
  9306. * @function
  9307. * @param {CubeTexture} value - The cube texture.
  9308. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9309. * @param {?Node<int>} [levelNode=null] - The level node.
  9310. * @param {?Node<float>} [biasNode=null] - The bias node.
  9311. * @returns {CubeTextureNode}
  9312. */
  9313. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  9314. /**
  9315. * TSL function for creating a cube texture uniform node.
  9316. *
  9317. * @tsl
  9318. * @function
  9319. * @param {?CubeTexture|CubeTextureNode} [value=EmptyTexture] - The cube texture.
  9320. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9321. * @param {?Node<int>} [levelNode=null] - The level node.
  9322. * @param {?Node<float>} [biasNode=null] - The bias node.
  9323. * @returns {CubeTextureNode}
  9324. */
  9325. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  9326. let textureNode;
  9327. if ( value && value.isCubeTextureNode === true ) {
  9328. textureNode = nodeObject( value.clone() );
  9329. textureNode.referenceNode = value.getSelf(); // Ensure the reference is set to the original node
  9330. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  9331. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  9332. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  9333. } else {
  9334. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  9335. }
  9336. return textureNode;
  9337. };
  9338. /**
  9339. * TSL function for creating a uniform cube texture node.
  9340. *
  9341. * @tsl
  9342. * @function
  9343. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  9344. * @returns {CubeTextureNode}
  9345. */
  9346. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  9347. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  9348. /**
  9349. * This class is only relevant if the referenced property is array-like.
  9350. * In this case, `ReferenceElementNode` allows to refer to a specific
  9351. * element inside the data structure via an index.
  9352. *
  9353. * @augments ArrayElementNode
  9354. */
  9355. class ReferenceElementNode extends ArrayElementNode {
  9356. static get type() {
  9357. return 'ReferenceElementNode';
  9358. }
  9359. /**
  9360. * Constructs a new reference element node.
  9361. *
  9362. * @param {?ReferenceNode} referenceNode - The reference node.
  9363. * @param {Node} indexNode - The index node that defines the element access.
  9364. */
  9365. constructor( referenceNode, indexNode ) {
  9366. super( referenceNode, indexNode );
  9367. /**
  9368. * Similar to {@link ReferenceNode#reference}, an additional
  9369. * property references to the current node.
  9370. *
  9371. * @type {?ReferenceNode}
  9372. * @default null
  9373. */
  9374. this.referenceNode = referenceNode;
  9375. /**
  9376. * This flag can be used for type testing.
  9377. *
  9378. * @type {boolean}
  9379. * @readonly
  9380. * @default true
  9381. */
  9382. this.isReferenceElementNode = true;
  9383. }
  9384. /**
  9385. * This method is overwritten since the node type is inferred from
  9386. * the uniform type of the reference node.
  9387. *
  9388. * @return {string} The node type.
  9389. */
  9390. getNodeType() {
  9391. return this.referenceNode.uniformType;
  9392. }
  9393. generate( builder ) {
  9394. const snippet = super.generate( builder );
  9395. const arrayType = this.referenceNode.getNodeType();
  9396. const elementType = this.getNodeType();
  9397. return builder.format( snippet, arrayType, elementType );
  9398. }
  9399. }
  9400. /**
  9401. * This type of node establishes a reference to a property of another object.
  9402. * In this way, the value of the node is automatically linked to the value of
  9403. * referenced object. Reference nodes internally represent the linked value
  9404. * as a uniform.
  9405. *
  9406. * @augments Node
  9407. */
  9408. class ReferenceNode extends Node {
  9409. static get type() {
  9410. return 'ReferenceNode';
  9411. }
  9412. /**
  9413. * Constructs a new reference node.
  9414. *
  9415. * @param {string} property - The name of the property the node refers to.
  9416. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  9417. * @param {?Object} [object=null] - The object the property belongs to.
  9418. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  9419. */
  9420. constructor( property, uniformType, object = null, count = null ) {
  9421. super();
  9422. /**
  9423. * The name of the property the node refers to.
  9424. *
  9425. * @type {string}
  9426. */
  9427. this.property = property;
  9428. /**
  9429. * The uniform type that should be used to represent the property value.
  9430. *
  9431. * @type {string}
  9432. */
  9433. this.uniformType = uniformType;
  9434. /**
  9435. * The object the property belongs to.
  9436. *
  9437. * @type {?Object}
  9438. * @default null
  9439. */
  9440. this.object = object;
  9441. /**
  9442. * When the linked property is an array, this parameter defines its length.
  9443. *
  9444. * @type {?number}
  9445. * @default null
  9446. */
  9447. this.count = count;
  9448. /**
  9449. * The property name might have dots so nested properties can be referred.
  9450. * The hierarchy of the names is stored inside this array.
  9451. *
  9452. * @type {Array<string>}
  9453. */
  9454. this.properties = property.split( '.' );
  9455. /**
  9456. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  9457. * since the final reference might be updated from calling code.
  9458. *
  9459. * @type {?Object}
  9460. * @default null
  9461. */
  9462. this.reference = object;
  9463. /**
  9464. * The uniform node that holds the value of the reference node.
  9465. *
  9466. * @type {UniformNode}
  9467. * @default null
  9468. */
  9469. this.node = null;
  9470. /**
  9471. * The uniform group of the internal uniform.
  9472. *
  9473. * @type {UniformGroupNode}
  9474. * @default null
  9475. */
  9476. this.group = null;
  9477. /**
  9478. * An optional label of the internal uniform node.
  9479. *
  9480. * @type {?string}
  9481. * @default null
  9482. */
  9483. this.name = null;
  9484. /**
  9485. * Overwritten since reference nodes are updated per object.
  9486. *
  9487. * @type {string}
  9488. * @default 'object'
  9489. */
  9490. this.updateType = NodeUpdateType.OBJECT;
  9491. }
  9492. /**
  9493. * When the referred property is array-like, this method can be used
  9494. * to access elements via an index node.
  9495. *
  9496. * @param {IndexNode} indexNode - indexNode.
  9497. * @return {ReferenceElementNode} A reference to an element.
  9498. */
  9499. element( indexNode ) {
  9500. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  9501. }
  9502. /**
  9503. * Sets the uniform group for this reference node.
  9504. *
  9505. * @param {UniformGroupNode} group - The uniform group to set.
  9506. * @return {ReferenceNode} A reference to this node.
  9507. */
  9508. setGroup( group ) {
  9509. this.group = group;
  9510. return this;
  9511. }
  9512. /**
  9513. * Sets the name for the internal uniform.
  9514. *
  9515. * @param {string} name - The label to set.
  9516. * @return {ReferenceNode} A reference to this node.
  9517. */
  9518. setName( name ) {
  9519. this.name = name;
  9520. return this;
  9521. }
  9522. /**
  9523. * Sets the label for the internal uniform.
  9524. *
  9525. * @deprecated
  9526. * @param {string} name - The label to set.
  9527. * @return {ReferenceNode} A reference to this node.
  9528. */
  9529. label( name ) {
  9530. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  9531. return this.setName( name );
  9532. }
  9533. /**
  9534. * Sets the node type which automatically defines the internal
  9535. * uniform type.
  9536. *
  9537. * @param {string} uniformType - The type to set.
  9538. */
  9539. setNodeType( uniformType ) {
  9540. let node = null;
  9541. if ( this.count !== null ) {
  9542. node = buffer( null, uniformType, this.count );
  9543. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  9544. node = uniformArray( null, uniformType );
  9545. } else if ( uniformType === 'texture' ) {
  9546. node = texture( null );
  9547. } else if ( uniformType === 'cubeTexture' ) {
  9548. node = cubeTexture( null );
  9549. } else {
  9550. node = uniform( null, uniformType );
  9551. }
  9552. if ( this.group !== null ) {
  9553. node.setGroup( this.group );
  9554. }
  9555. if ( this.name !== null ) node.setName( this.name );
  9556. this.node = node.getSelf();
  9557. }
  9558. /**
  9559. * This method is overwritten since the node type is inferred from
  9560. * the type of the reference node.
  9561. *
  9562. * @param {NodeBuilder} builder - The current node builder.
  9563. * @return {string} The node type.
  9564. */
  9565. getNodeType( builder ) {
  9566. if ( this.node === null ) {
  9567. this.updateReference( builder );
  9568. this.updateValue();
  9569. }
  9570. return this.node.getNodeType( builder );
  9571. }
  9572. /**
  9573. * Returns the property value from the given referred object.
  9574. *
  9575. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  9576. * @return {any} The value.
  9577. */
  9578. getValueFromReference( object = this.reference ) {
  9579. const { properties } = this;
  9580. let value = object[ properties[ 0 ] ];
  9581. for ( let i = 1; i < properties.length; i ++ ) {
  9582. value = value[ properties[ i ] ];
  9583. }
  9584. return value;
  9585. }
  9586. /**
  9587. * Allows to update the reference based on the given state. The state is only
  9588. * evaluated {@link ReferenceNode#object} is not set.
  9589. *
  9590. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9591. * @return {Object} The updated reference.
  9592. */
  9593. updateReference( state ) {
  9594. this.reference = this.object !== null ? this.object : state.object;
  9595. return this.reference;
  9596. }
  9597. /**
  9598. * The output of the reference node is the internal uniform node.
  9599. *
  9600. * @param {NodeBuilder} builder - The current node builder.
  9601. * @return {UniformNode} The output node.
  9602. */
  9603. setup( /* builder */ ) {
  9604. this.updateValue();
  9605. return this.node;
  9606. }
  9607. /**
  9608. * Overwritten to update the internal uniform value.
  9609. *
  9610. * @param {NodeFrame} frame - A reference to the current node frame.
  9611. */
  9612. update( /*frame*/ ) {
  9613. this.updateValue();
  9614. }
  9615. /**
  9616. * Retrieves the value from the referred object property and uses it
  9617. * to updated the internal uniform.
  9618. */
  9619. updateValue() {
  9620. if ( this.node === null ) this.setNodeType( this.uniformType );
  9621. const value = this.getValueFromReference();
  9622. if ( Array.isArray( value ) ) {
  9623. this.node.array = value;
  9624. } else {
  9625. this.node.value = value;
  9626. }
  9627. }
  9628. }
  9629. /**
  9630. * TSL function for creating a reference node.
  9631. *
  9632. * @tsl
  9633. * @function
  9634. * @param {string} name - The name of the property the node refers to.
  9635. * @param {string} type - The uniform type that should be used to represent the property value.
  9636. * @param {?Object} [object] - The object the property belongs to.
  9637. * @returns {ReferenceNode}
  9638. */
  9639. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  9640. /**
  9641. * TSL function for creating a reference node. Use this function if you want need a reference
  9642. * to an array-like property that should be represented as a uniform buffer.
  9643. *
  9644. * @tsl
  9645. * @function
  9646. * @param {string} name - The name of the property the node refers to.
  9647. * @param {string} type - The uniform type that should be used to represent the property value.
  9648. * @param {number} count - The number of value inside the array-like object.
  9649. * @param {Object} object - An array-like object the property belongs to.
  9650. * @returns {ReferenceNode}
  9651. */
  9652. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  9653. /**
  9654. * This node is a special type of reference node which is intended
  9655. * for linking material properties with node values.
  9656. * ```js
  9657. * const opacityNode = materialReference( 'opacity', 'float', material );
  9658. * ```
  9659. * When changing `material.opacity`, the node value of `opacityNode` will
  9660. * automatically be updated.
  9661. *
  9662. * @augments ReferenceNode
  9663. */
  9664. class MaterialReferenceNode extends ReferenceNode {
  9665. static get type() {
  9666. return 'MaterialReferenceNode';
  9667. }
  9668. /**
  9669. * Constructs a new material reference node.
  9670. *
  9671. * @param {string} property - The name of the property the node refers to.
  9672. * @param {string} inputType - The uniform type that should be used to represent the property value.
  9673. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  9674. * the node refers to the material of the current rendered object.
  9675. */
  9676. constructor( property, inputType, material = null ) {
  9677. super( property, inputType, material );
  9678. /**
  9679. * The material the property belongs to. When no material is set,
  9680. * the node refers to the material of the current rendered object.
  9681. *
  9682. * @type {?Material}
  9683. * @default null
  9684. */
  9685. this.material = material;
  9686. /**
  9687. * This flag can be used for type testing.
  9688. *
  9689. * @type {boolean}
  9690. * @readonly
  9691. * @default true
  9692. */
  9693. this.isMaterialReferenceNode = true;
  9694. }
  9695. /**
  9696. * Updates the reference based on the given state. The state is only evaluated
  9697. * {@link MaterialReferenceNode#material} is not set.
  9698. *
  9699. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9700. * @return {Object} The updated reference.
  9701. */
  9702. updateReference( state ) {
  9703. this.reference = this.material !== null ? this.material : state.material;
  9704. return this.reference;
  9705. }
  9706. }
  9707. /**
  9708. * TSL function for creating a material reference node.
  9709. *
  9710. * @tsl
  9711. * @function
  9712. * @param {string} name - The name of the property the node refers to.
  9713. * @param {string} type - The uniform type that should be used to represent the property value.
  9714. * @param {?Material} [material=null] - The material the property belongs to.
  9715. * When no material is set, the node refers to the material of the current rendered object.
  9716. * @returns {MaterialReferenceNode}
  9717. */
  9718. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  9719. // Normal Mapping Without Precomputed Tangents
  9720. // http://www.thetenthplanet.de/archives/1180
  9721. const uv = uv$1();
  9722. const q0 = positionView.dFdx();
  9723. const q1 = positionView.dFdy();
  9724. const st0 = uv.dFdx();
  9725. const st1 = uv.dFdy();
  9726. const N = normalView;
  9727. const q1perp = q1.cross( N );
  9728. const q0perp = N.cross( q0 );
  9729. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  9730. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  9731. const det = T.dot( T ).max( B.dot( B ) );
  9732. const scale = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  9733. /**
  9734. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  9735. * Useful for normal mapping without precomputed tangents.
  9736. *
  9737. * Reference: http://www.thetenthplanet.de/archives/1180
  9738. *
  9739. * @tsl
  9740. * @type {Node<vec3>}
  9741. */
  9742. const tangentViewFrame = /*@__PURE__*/ T.mul( scale ).toVar( 'tangentViewFrame' );
  9743. /**
  9744. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  9745. * Complements the tangentViewFrame for constructing the tangent space basis.
  9746. *
  9747. * Reference: http://www.thetenthplanet.de/archives/1180
  9748. *
  9749. * @tsl
  9750. * @type {Node<vec3>}
  9751. */
  9752. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale ).toVar( 'bitangentViewFrame' );
  9753. /**
  9754. * TSL object that represents the tangent attribute of the current rendered object.
  9755. *
  9756. * @tsl
  9757. * @type {Node<vec4>}
  9758. */
  9759. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  9760. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  9761. builder.geometry.computeTangents();
  9762. }
  9763. return attribute( 'tangent', 'vec4' );
  9764. } )();
  9765. /**
  9766. * TSL object that represents the vertex tangent in local space of the current rendered object.
  9767. *
  9768. * @tsl
  9769. * @type {Node<vec3>}
  9770. */
  9771. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  9772. /**
  9773. * TSL object that represents the vertex tangent in view space of the current rendered object.
  9774. *
  9775. * @tsl
  9776. * @type {Node<vec3>}
  9777. */
  9778. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  9779. let node;
  9780. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  9781. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  9782. } else {
  9783. node = tangentViewFrame;
  9784. }
  9785. if ( material.flatShading !== true ) {
  9786. node = directionToFaceDirection( node );
  9787. }
  9788. return node;
  9789. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  9790. /**
  9791. * TSL object that represents the vertex tangent in world space of the current rendered object.
  9792. *
  9793. * @tsl
  9794. * @type {Node<vec3>}
  9795. */
  9796. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  9797. /**
  9798. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  9799. *
  9800. * @tsl
  9801. * @private
  9802. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  9803. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  9804. * @returns {Node<vec3>} The bitangent node.
  9805. */
  9806. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  9807. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  9808. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  9809. bitangent = bitangent.toVarying( varyingName );
  9810. }
  9811. return bitangent;
  9812. } ).once( [ 'NORMAL' ] );
  9813. /**
  9814. * TSL object that represents the bitangent attribute of the current rendered object.
  9815. *
  9816. * @tsl
  9817. * @type {Node<vec3>}
  9818. */
  9819. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  9820. /**
  9821. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  9822. *
  9823. * @tsl
  9824. * @type {Node<vec3>}
  9825. */
  9826. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  9827. /**
  9828. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  9829. *
  9830. * @tsl
  9831. * @type {Node<vec3>}
  9832. */
  9833. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  9834. let node;
  9835. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  9836. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  9837. } else {
  9838. node = bitangentViewFrame;
  9839. }
  9840. if ( material.flatShading !== true ) {
  9841. node = directionToFaceDirection( node );
  9842. }
  9843. return node;
  9844. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  9845. /**
  9846. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  9847. *
  9848. * @tsl
  9849. * @type {Node<vec3>}
  9850. */
  9851. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  9852. /**
  9853. * TSL object that represents the TBN matrix in view space.
  9854. *
  9855. * @tsl
  9856. * @type {Node<mat3>}
  9857. */
  9858. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  9859. /**
  9860. * TSL object that represents the parallax direction.
  9861. *
  9862. * @tsl
  9863. * @type {Node<mat3>}
  9864. */
  9865. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  9866. /**
  9867. * TSL function for computing parallax uv coordinates.
  9868. *
  9869. * @tsl
  9870. * @function
  9871. * @param {Node<vec2>} uv - A uv node.
  9872. * @param {Node<vec2>} scale - A scale node.
  9873. * @returns {Node<vec2>} Parallax uv coordinates.
  9874. */
  9875. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  9876. /**
  9877. * TSL function for computing bent normals.
  9878. *
  9879. * @tsl
  9880. * @function
  9881. * @returns {Node<vec3>} Bent normals.
  9882. */
  9883. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  9884. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  9885. let bentNormal = anisotropyB.cross( positionViewDirection );
  9886. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  9887. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  9888. return bentNormal;
  9889. } ).once() )();
  9890. /**
  9891. * This class can be used for applying normals maps to materials.
  9892. *
  9893. * ```js
  9894. * material.normalNode = normalMap( texture( normalTex ) );
  9895. * ```
  9896. *
  9897. * @augments TempNode
  9898. */
  9899. class NormalMapNode extends TempNode {
  9900. static get type() {
  9901. return 'NormalMapNode';
  9902. }
  9903. /**
  9904. * Constructs a new normal map node.
  9905. *
  9906. * @param {Node<vec3>} node - Represents the normal map data.
  9907. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  9908. */
  9909. constructor( node, scaleNode = null ) {
  9910. super( 'vec3' );
  9911. /**
  9912. * Represents the normal map data.
  9913. *
  9914. * @type {Node<vec3>}
  9915. */
  9916. this.node = node;
  9917. /**
  9918. * Controls the intensity of the effect.
  9919. *
  9920. * @type {?Node<vec2>}
  9921. * @default null
  9922. */
  9923. this.scaleNode = scaleNode;
  9924. /**
  9925. * The normal map type.
  9926. *
  9927. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  9928. * @default TangentSpaceNormalMap
  9929. */
  9930. this.normalMapType = TangentSpaceNormalMap;
  9931. }
  9932. setup( { material } ) {
  9933. const { normalMapType, scaleNode } = this;
  9934. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  9935. if ( scaleNode !== null ) {
  9936. let scale = scaleNode;
  9937. if ( material.flatShading === true ) {
  9938. scale = directionToFaceDirection( scale );
  9939. }
  9940. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  9941. }
  9942. let output = null;
  9943. if ( normalMapType === ObjectSpaceNormalMap ) {
  9944. output = transformNormalToView( normalMap );
  9945. } else if ( normalMapType === TangentSpaceNormalMap ) {
  9946. output = TBNViewMatrix.mul( normalMap ).normalize();
  9947. } else {
  9948. console.error( `THREE.NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  9949. output = normalView; // Fallback to default normal view
  9950. }
  9951. return output;
  9952. }
  9953. }
  9954. /**
  9955. * TSL function for creating a normal map node.
  9956. *
  9957. * @tsl
  9958. * @function
  9959. * @param {Node<vec3>} node - Represents the normal map data.
  9960. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  9961. * @returns {NormalMapNode}
  9962. */
  9963. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  9964. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  9965. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  9966. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  9967. // It's used to preserve the same TextureNode instance
  9968. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  9969. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  9970. return vec2(
  9971. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  9972. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  9973. ).mul( bumpScale );
  9974. } );
  9975. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9976. const perturbNormalArb = Fn( ( inputs ) => {
  9977. const { surf_pos, surf_norm, dHdxy } = inputs;
  9978. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  9979. const vSigmaX = surf_pos.dFdx().normalize();
  9980. const vSigmaY = surf_pos.dFdy().normalize();
  9981. const vN = surf_norm; // normalized
  9982. const R1 = vSigmaY.cross( vN );
  9983. const R2 = vN.cross( vSigmaX );
  9984. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  9985. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  9986. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  9987. } );
  9988. /**
  9989. * This class can be used for applying bump maps to materials.
  9990. *
  9991. * ```js
  9992. * material.normalNode = bumpMap( texture( bumpTex ) );
  9993. * ```
  9994. *
  9995. * @augments TempNode
  9996. */
  9997. class BumpMapNode extends TempNode {
  9998. static get type() {
  9999. return 'BumpMapNode';
  10000. }
  10001. /**
  10002. * Constructs a new bump map node.
  10003. *
  10004. * @param {Node<float>} textureNode - Represents the bump map data.
  10005. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10006. */
  10007. constructor( textureNode, scaleNode = null ) {
  10008. super( 'vec3' );
  10009. /**
  10010. * Represents the bump map data.
  10011. *
  10012. * @type {Node<float>}
  10013. */
  10014. this.textureNode = textureNode;
  10015. /**
  10016. * Controls the intensity of the bump effect.
  10017. *
  10018. * @type {?Node<float>}
  10019. * @default null
  10020. */
  10021. this.scaleNode = scaleNode;
  10022. }
  10023. setup() {
  10024. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  10025. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  10026. return perturbNormalArb( {
  10027. surf_pos: positionView,
  10028. surf_norm: normalView,
  10029. dHdxy
  10030. } );
  10031. }
  10032. }
  10033. /**
  10034. * TSL function for creating a bump map node.
  10035. *
  10036. * @tsl
  10037. * @function
  10038. * @param {Node<float>} textureNode - Represents the bump map data.
  10039. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10040. * @returns {BumpMapNode}
  10041. */
  10042. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  10043. const _propertyCache = new Map();
  10044. /**
  10045. * This class should simplify the node access to material properties.
  10046. * It internal uses reference nodes to make sure changes to material
  10047. * properties are automatically reflected to predefined TSL objects
  10048. * like e.g. `materialColor`.
  10049. *
  10050. * @augments Node
  10051. */
  10052. class MaterialNode extends Node {
  10053. static get type() {
  10054. return 'MaterialNode';
  10055. }
  10056. /**
  10057. * Constructs a new material node.
  10058. *
  10059. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  10060. */
  10061. constructor( scope ) {
  10062. super();
  10063. /**
  10064. * The scope defines what material property is referred by the node.
  10065. *
  10066. * @type {string}
  10067. */
  10068. this.scope = scope;
  10069. }
  10070. /**
  10071. * Returns a cached reference node for the given property and type.
  10072. *
  10073. * @param {string} property - The name of the material property.
  10074. * @param {string} type - The uniform type of the property.
  10075. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10076. */
  10077. getCache( property, type ) {
  10078. let node = _propertyCache.get( property );
  10079. if ( node === undefined ) {
  10080. node = materialReference( property, type );
  10081. _propertyCache.set( property, node );
  10082. }
  10083. return node;
  10084. }
  10085. /**
  10086. * Returns a float-typed material reference node for the given property name.
  10087. *
  10088. * @param {string} property - The name of the material property.
  10089. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  10090. */
  10091. getFloat( property ) {
  10092. return this.getCache( property, 'float' );
  10093. }
  10094. /**
  10095. * Returns a color-typed material reference node for the given property name.
  10096. *
  10097. * @param {string} property - The name of the material property.
  10098. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  10099. */
  10100. getColor( property ) {
  10101. return this.getCache( property, 'color' );
  10102. }
  10103. /**
  10104. * Returns a texture-typed material reference node for the given property name.
  10105. *
  10106. * @param {string} property - The name of the material property.
  10107. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10108. */
  10109. getTexture( property ) {
  10110. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  10111. }
  10112. /**
  10113. * The node setup is done depending on the selected scope. Multiple material properties
  10114. * might be grouped into a single node composition if they logically belong together.
  10115. *
  10116. * @param {NodeBuilder} builder - The current node builder.
  10117. * @return {Node} The node representing the selected scope.
  10118. */
  10119. setup( builder ) {
  10120. const material = builder.context.material;
  10121. const scope = this.scope;
  10122. let node = null;
  10123. if ( scope === MaterialNode.COLOR ) {
  10124. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  10125. if ( material.map && material.map.isTexture === true ) {
  10126. node = colorNode.mul( this.getTexture( 'map' ) );
  10127. } else {
  10128. node = colorNode;
  10129. }
  10130. } else if ( scope === MaterialNode.OPACITY ) {
  10131. const opacityNode = this.getFloat( scope );
  10132. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  10133. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  10134. } else {
  10135. node = opacityNode;
  10136. }
  10137. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  10138. if ( material.specularMap && material.specularMap.isTexture === true ) {
  10139. node = this.getTexture( 'specular' ).r;
  10140. } else {
  10141. node = float( 1 );
  10142. }
  10143. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  10144. const specularIntensityNode = this.getFloat( scope );
  10145. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  10146. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  10147. } else {
  10148. node = specularIntensityNode;
  10149. }
  10150. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  10151. const specularColorNode = this.getColor( scope );
  10152. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  10153. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  10154. } else {
  10155. node = specularColorNode;
  10156. }
  10157. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  10158. const roughnessNode = this.getFloat( scope );
  10159. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  10160. node = roughnessNode.mul( this.getTexture( scope ).g );
  10161. } else {
  10162. node = roughnessNode;
  10163. }
  10164. } else if ( scope === MaterialNode.METALNESS ) {
  10165. const metalnessNode = this.getFloat( scope );
  10166. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  10167. node = metalnessNode.mul( this.getTexture( scope ).b );
  10168. } else {
  10169. node = metalnessNode;
  10170. }
  10171. } else if ( scope === MaterialNode.EMISSIVE ) {
  10172. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  10173. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  10174. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  10175. node = emissiveNode.mul( this.getTexture( scope ) );
  10176. } else {
  10177. node = emissiveNode;
  10178. }
  10179. } else if ( scope === MaterialNode.NORMAL ) {
  10180. if ( material.normalMap ) {
  10181. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  10182. node.normalMapType = material.normalMapType;
  10183. } else if ( material.bumpMap ) {
  10184. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  10185. } else {
  10186. node = normalView;
  10187. }
  10188. } else if ( scope === MaterialNode.CLEARCOAT ) {
  10189. const clearcoatNode = this.getFloat( scope );
  10190. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  10191. node = clearcoatNode.mul( this.getTexture( scope ).r );
  10192. } else {
  10193. node = clearcoatNode;
  10194. }
  10195. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  10196. const clearcoatRoughnessNode = this.getFloat( scope );
  10197. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  10198. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  10199. } else {
  10200. node = clearcoatRoughnessNode;
  10201. }
  10202. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  10203. if ( material.clearcoatNormalMap ) {
  10204. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  10205. } else {
  10206. node = normalView;
  10207. }
  10208. } else if ( scope === MaterialNode.SHEEN ) {
  10209. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  10210. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  10211. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  10212. } else {
  10213. node = sheenNode;
  10214. }
  10215. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  10216. const sheenRoughnessNode = this.getFloat( scope );
  10217. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  10218. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  10219. } else {
  10220. node = sheenRoughnessNode;
  10221. }
  10222. node = node.clamp( 0.07, 1.0 );
  10223. } else if ( scope === MaterialNode.ANISOTROPY ) {
  10224. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  10225. const anisotropyPolar = this.getTexture( scope );
  10226. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  10227. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  10228. } else {
  10229. node = materialAnisotropyVector;
  10230. }
  10231. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  10232. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  10233. if ( material.iridescenceThicknessMap ) {
  10234. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  10235. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  10236. } else {
  10237. node = iridescenceThicknessMaximum;
  10238. }
  10239. } else if ( scope === MaterialNode.TRANSMISSION ) {
  10240. const transmissionNode = this.getFloat( scope );
  10241. if ( material.transmissionMap ) {
  10242. node = transmissionNode.mul( this.getTexture( scope ).r );
  10243. } else {
  10244. node = transmissionNode;
  10245. }
  10246. } else if ( scope === MaterialNode.THICKNESS ) {
  10247. const thicknessNode = this.getFloat( scope );
  10248. if ( material.thicknessMap ) {
  10249. node = thicknessNode.mul( this.getTexture( scope ).g );
  10250. } else {
  10251. node = thicknessNode;
  10252. }
  10253. } else if ( scope === MaterialNode.IOR ) {
  10254. node = this.getFloat( scope );
  10255. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  10256. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  10257. } else if ( scope === MaterialNode.AO ) {
  10258. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  10259. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  10260. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  10261. } else {
  10262. const outputType = this.getNodeType( builder );
  10263. node = this.getCache( scope, outputType );
  10264. }
  10265. return node;
  10266. }
  10267. }
  10268. MaterialNode.ALPHA_TEST = 'alphaTest';
  10269. MaterialNode.COLOR = 'color';
  10270. MaterialNode.OPACITY = 'opacity';
  10271. MaterialNode.SHININESS = 'shininess';
  10272. MaterialNode.SPECULAR = 'specular';
  10273. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  10274. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  10275. MaterialNode.SPECULAR_COLOR = 'specularColor';
  10276. MaterialNode.REFLECTIVITY = 'reflectivity';
  10277. MaterialNode.ROUGHNESS = 'roughness';
  10278. MaterialNode.METALNESS = 'metalness';
  10279. MaterialNode.NORMAL = 'normal';
  10280. MaterialNode.CLEARCOAT = 'clearcoat';
  10281. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  10282. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  10283. MaterialNode.EMISSIVE = 'emissive';
  10284. MaterialNode.ROTATION = 'rotation';
  10285. MaterialNode.SHEEN = 'sheen';
  10286. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  10287. MaterialNode.ANISOTROPY = 'anisotropy';
  10288. MaterialNode.IRIDESCENCE = 'iridescence';
  10289. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  10290. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  10291. MaterialNode.IOR = 'ior';
  10292. MaterialNode.TRANSMISSION = 'transmission';
  10293. MaterialNode.THICKNESS = 'thickness';
  10294. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  10295. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  10296. MaterialNode.LINE_SCALE = 'scale';
  10297. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  10298. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  10299. MaterialNode.LINE_WIDTH = 'linewidth';
  10300. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  10301. MaterialNode.POINT_SIZE = 'size';
  10302. MaterialNode.DISPERSION = 'dispersion';
  10303. MaterialNode.LIGHT_MAP = 'light';
  10304. MaterialNode.AO = 'ao';
  10305. /**
  10306. * TSL object that represents alpha test of the current material.
  10307. *
  10308. * @tsl
  10309. * @type {Node<float>}
  10310. */
  10311. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  10312. /**
  10313. * TSL object that represents the diffuse color of the current material.
  10314. * The value is composed via `color` * `map`.
  10315. *
  10316. * @tsl
  10317. * @type {Node<vec3>}
  10318. */
  10319. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  10320. /**
  10321. * TSL object that represents the shininess of the current material.
  10322. *
  10323. * @tsl
  10324. * @type {Node<float>}
  10325. */
  10326. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  10327. /**
  10328. * TSL object that represents the emissive color of the current material.
  10329. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  10330. *
  10331. * @tsl
  10332. * @type {Node<vec3>}
  10333. */
  10334. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  10335. /**
  10336. * TSL object that represents the opacity of the current material.
  10337. * The value is composed via `opacity` * `alphaMap`.
  10338. *
  10339. * @tsl
  10340. * @type {Node<float>}
  10341. */
  10342. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  10343. /**
  10344. * TSL object that represents the specular of the current material.
  10345. *
  10346. * @tsl
  10347. * @type {Node<vec3>}
  10348. */
  10349. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  10350. /**
  10351. * TSL object that represents the specular intensity of the current material.
  10352. * The value is composed via `specularIntensity` * `specularMap.a`.
  10353. *
  10354. * @tsl
  10355. * @type {Node<float>}
  10356. */
  10357. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  10358. /**
  10359. * TSL object that represents the specular color of the current material.
  10360. * The value is composed via `specularColor` * `specularMap.rgb`.
  10361. *
  10362. * @tsl
  10363. * @type {Node<vec3>}
  10364. */
  10365. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  10366. /**
  10367. * TSL object that represents the specular strength of the current material.
  10368. * The value is composed via `specularMap.r`.
  10369. *
  10370. * @tsl
  10371. * @type {Node<float>}
  10372. */
  10373. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  10374. /**
  10375. * TSL object that represents the reflectivity of the current material.
  10376. *
  10377. * @tsl
  10378. * @type {Node<float>}
  10379. */
  10380. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  10381. /**
  10382. * TSL object that represents the roughness of the current material.
  10383. * The value is composed via `roughness` * `roughnessMap.g`.
  10384. *
  10385. * @tsl
  10386. * @type {Node<float>}
  10387. */
  10388. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  10389. /**
  10390. * TSL object that represents the metalness of the current material.
  10391. * The value is composed via `metalness` * `metalnessMap.b`.
  10392. *
  10393. * @tsl
  10394. * @type {Node<float>}
  10395. */
  10396. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  10397. /**
  10398. * TSL object that represents the normal of the current material.
  10399. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  10400. *
  10401. * @tsl
  10402. * @type {Node<vec3>}
  10403. */
  10404. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  10405. /**
  10406. * TSL object that represents the clearcoat of the current material.
  10407. * The value is composed via `clearcoat` * `clearcoatMap.r`
  10408. *
  10409. * @tsl
  10410. * @type {Node<float>}
  10411. */
  10412. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  10413. /**
  10414. * TSL object that represents the clearcoat roughness of the current material.
  10415. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  10416. *
  10417. * @tsl
  10418. * @type {Node<float>}
  10419. */
  10420. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  10421. /**
  10422. * TSL object that represents the clearcoat normal of the current material.
  10423. * The value will be either `clearcoatNormalMap` or `normalView`.
  10424. *
  10425. * @tsl
  10426. * @type {Node<vec3>}
  10427. */
  10428. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  10429. /**
  10430. * TSL object that represents the rotation of the current sprite material.
  10431. *
  10432. * @tsl
  10433. * @type {Node<float>}
  10434. */
  10435. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  10436. /**
  10437. * TSL object that represents the sheen color of the current material.
  10438. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  10439. *
  10440. * @tsl
  10441. * @type {Node<vec3>}
  10442. */
  10443. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  10444. /**
  10445. * TSL object that represents the sheen roughness of the current material.
  10446. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  10447. *
  10448. * @tsl
  10449. * @type {Node<float>}
  10450. */
  10451. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  10452. /**
  10453. * TSL object that represents the anisotropy of the current material.
  10454. *
  10455. * @tsl
  10456. * @type {Node<vec2>}
  10457. */
  10458. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  10459. /**
  10460. * TSL object that represents the iridescence of the current material.
  10461. *
  10462. * @tsl
  10463. * @type {Node<float>}
  10464. */
  10465. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  10466. /**
  10467. * TSL object that represents the iridescence IOR of the current material.
  10468. *
  10469. * @tsl
  10470. * @type {Node<float>}
  10471. */
  10472. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  10473. /**
  10474. * TSL object that represents the iridescence thickness of the current material.
  10475. *
  10476. * @tsl
  10477. * @type {Node<float>}
  10478. */
  10479. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  10480. /**
  10481. * TSL object that represents the transmission of the current material.
  10482. * The value is composed via `transmission` * `transmissionMap.r`.
  10483. *
  10484. * @tsl
  10485. * @type {Node<float>}
  10486. */
  10487. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  10488. /**
  10489. * TSL object that represents the thickness of the current material.
  10490. * The value is composed via `thickness` * `thicknessMap.g`.
  10491. *
  10492. * @tsl
  10493. * @type {Node<float>}
  10494. */
  10495. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  10496. /**
  10497. * TSL object that represents the IOR of the current material.
  10498. *
  10499. * @tsl
  10500. * @type {Node<float>}
  10501. */
  10502. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  10503. /**
  10504. * TSL object that represents the attenuation distance of the current material.
  10505. *
  10506. * @tsl
  10507. * @type {Node<float>}
  10508. */
  10509. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  10510. /**
  10511. * TSL object that represents the attenuation color of the current material.
  10512. *
  10513. * @tsl
  10514. * @type {Node<vec3>}
  10515. */
  10516. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  10517. /**
  10518. * TSL object that represents the scale of the current dashed line material.
  10519. *
  10520. * @tsl
  10521. * @type {Node<float>}
  10522. */
  10523. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  10524. /**
  10525. * TSL object that represents the dash size of the current dashed line material.
  10526. *
  10527. * @tsl
  10528. * @type {Node<float>}
  10529. */
  10530. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  10531. /**
  10532. * TSL object that represents the gap size of the current dashed line material.
  10533. *
  10534. * @tsl
  10535. * @type {Node<float>}
  10536. */
  10537. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  10538. /**
  10539. * TSL object that represents the line width of the current line material.
  10540. *
  10541. * @tsl
  10542. * @type {Node<float>}
  10543. */
  10544. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  10545. /**
  10546. * TSL object that represents the dash offset of the current line material.
  10547. *
  10548. * @tsl
  10549. * @type {Node<float>}
  10550. */
  10551. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  10552. /**
  10553. * TSL object that represents the point size of the current points material.
  10554. *
  10555. * @tsl
  10556. * @type {Node<float>}
  10557. */
  10558. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  10559. /**
  10560. * TSL object that represents the dispersion of the current material.
  10561. *
  10562. * @tsl
  10563. * @type {Node<float>}
  10564. */
  10565. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  10566. /**
  10567. * TSL object that represents the light map of the current material.
  10568. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  10569. *
  10570. * @tsl
  10571. * @type {Node<vec3>}
  10572. */
  10573. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  10574. /**
  10575. * TSL object that represents the ambient occlusion map of the current material.
  10576. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  10577. *
  10578. * @tsl
  10579. * @type {Node<float>}
  10580. */
  10581. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  10582. /**
  10583. * TSL object that represents the anisotropy vector of the current material.
  10584. *
  10585. * @tsl
  10586. * @type {Node<vec2>}
  10587. */
  10588. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  10589. return frame.material;
  10590. } ).onRenderUpdate( function ( { material } ) {
  10591. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  10592. } );
  10593. /**
  10594. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  10595. *
  10596. * @tsl
  10597. * @type {VaryingNode<vec4>}
  10598. */
  10599. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  10600. return builder.context.setupModelViewProjection();
  10601. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  10602. /**
  10603. * This class represents shader indices of different types. The following predefined node
  10604. * objects cover frequent use cases:
  10605. *
  10606. * - `vertexIndex`: The index of a vertex within a mesh.
  10607. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  10608. * - `drawIndex`: The index of a draw call.
  10609. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  10610. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  10611. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  10612. *
  10613. * @augments Node
  10614. */
  10615. class IndexNode extends Node {
  10616. static get type() {
  10617. return 'IndexNode';
  10618. }
  10619. /**
  10620. * Constructs a new index node.
  10621. *
  10622. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  10623. */
  10624. constructor( scope ) {
  10625. super( 'uint' );
  10626. /**
  10627. * The scope of the index node.
  10628. *
  10629. * @type {string}
  10630. */
  10631. this.scope = scope;
  10632. /**
  10633. * This flag can be used for type testing.
  10634. *
  10635. * @type {boolean}
  10636. * @readonly
  10637. * @default true
  10638. */
  10639. this.isIndexNode = true;
  10640. }
  10641. generate( builder ) {
  10642. const nodeType = this.getNodeType( builder );
  10643. const scope = this.scope;
  10644. let propertyName;
  10645. if ( scope === IndexNode.VERTEX ) {
  10646. propertyName = builder.getVertexIndex();
  10647. } else if ( scope === IndexNode.INSTANCE ) {
  10648. propertyName = builder.getInstanceIndex();
  10649. } else if ( scope === IndexNode.DRAW ) {
  10650. propertyName = builder.getDrawIndex();
  10651. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  10652. propertyName = builder.getInvocationLocalIndex();
  10653. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  10654. propertyName = builder.getInvocationSubgroupIndex();
  10655. } else if ( scope === IndexNode.SUBGROUP ) {
  10656. propertyName = builder.getSubgroupIndex();
  10657. } else {
  10658. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  10659. }
  10660. let output;
  10661. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  10662. output = propertyName;
  10663. } else {
  10664. const nodeVarying = varying( this );
  10665. output = nodeVarying.build( builder, nodeType );
  10666. }
  10667. return output;
  10668. }
  10669. }
  10670. IndexNode.VERTEX = 'vertex';
  10671. IndexNode.INSTANCE = 'instance';
  10672. IndexNode.SUBGROUP = 'subgroup';
  10673. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  10674. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  10675. IndexNode.DRAW = 'draw';
  10676. /**
  10677. * TSL object that represents the index of a vertex within a mesh.
  10678. *
  10679. * @tsl
  10680. * @type {IndexNode}
  10681. */
  10682. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  10683. /**
  10684. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  10685. *
  10686. * @tsl
  10687. * @type {IndexNode}
  10688. */
  10689. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  10690. /**
  10691. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  10692. *
  10693. * @tsl
  10694. * @type {IndexNode}
  10695. */
  10696. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  10697. /**
  10698. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  10699. *
  10700. * @tsl
  10701. * @type {IndexNode}
  10702. */
  10703. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  10704. /**
  10705. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  10706. *
  10707. * @tsl
  10708. * @type {IndexNode}
  10709. */
  10710. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  10711. /**
  10712. * TSL object that represents the index of a draw call.
  10713. *
  10714. * @tsl
  10715. * @type {IndexNode}
  10716. */
  10717. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  10718. /**
  10719. * This node implements the vertex shader logic which is required
  10720. * when rendering 3D objects via instancing. The code makes sure
  10721. * vertex positions, normals and colors can be modified via instanced
  10722. * data.
  10723. *
  10724. * @augments Node
  10725. */
  10726. class InstanceNode extends Node {
  10727. static get type() {
  10728. return 'InstanceNode';
  10729. }
  10730. /**
  10731. * Constructs a new instance node.
  10732. *
  10733. * @param {number} count - The number of instances.
  10734. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  10735. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  10736. */
  10737. constructor( count, instanceMatrix, instanceColor = null ) {
  10738. super( 'void' );
  10739. /**
  10740. * The number of instances.
  10741. *
  10742. * @type {number}
  10743. */
  10744. this.count = count;
  10745. /**
  10746. * Instanced buffer attribute representing the transformation of instances.
  10747. *
  10748. * @type {InstancedBufferAttribute}
  10749. */
  10750. this.instanceMatrix = instanceMatrix;
  10751. /**
  10752. * Instanced buffer attribute representing the color of instances.
  10753. *
  10754. * @type {InstancedBufferAttribute}
  10755. */
  10756. this.instanceColor = instanceColor;
  10757. /**
  10758. * The node that represents the instance matrix data.
  10759. *
  10760. * @type {?Node}
  10761. */
  10762. this.instanceMatrixNode = null;
  10763. /**
  10764. * The node that represents the instance color data.
  10765. *
  10766. * @type {?Node}
  10767. * @default null
  10768. */
  10769. this.instanceColorNode = null;
  10770. /**
  10771. * The update type is set to `frame` since an update
  10772. * of instanced buffer data must be checked per frame.
  10773. *
  10774. * @type {string}
  10775. * @default 'frame'
  10776. */
  10777. this.updateType = NodeUpdateType.FRAME;
  10778. /**
  10779. * A reference to a buffer that is used by `instanceMatrixNode`.
  10780. *
  10781. * @type {?InstancedInterleavedBuffer}
  10782. */
  10783. this.buffer = null;
  10784. /**
  10785. * A reference to a buffer that is used by `instanceColorNode`.
  10786. *
  10787. * @type {?InstancedBufferAttribute}
  10788. */
  10789. this.bufferColor = null;
  10790. }
  10791. /**
  10792. * Setups the internal buffers and nodes and assigns the transformed vertex data
  10793. * to predefined node variables for accumulation. That follows the same patterns
  10794. * like with morph and skinning nodes.
  10795. *
  10796. * @param {NodeBuilder} builder - The current node builder.
  10797. */
  10798. setup( builder ) {
  10799. const { count, instanceMatrix, instanceColor } = this;
  10800. let { instanceMatrixNode, instanceColorNode } = this;
  10801. if ( instanceMatrixNode === null ) {
  10802. // 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.
  10803. if ( count <= 1000 ) {
  10804. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  10805. } else {
  10806. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  10807. this.buffer = buffer;
  10808. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  10809. const instanceBuffers = [
  10810. // F.Signature -> bufferAttribute( array, type, stride, offset )
  10811. bufferFn( buffer, 'vec4', 16, 0 ),
  10812. bufferFn( buffer, 'vec4', 16, 4 ),
  10813. bufferFn( buffer, 'vec4', 16, 8 ),
  10814. bufferFn( buffer, 'vec4', 16, 12 )
  10815. ];
  10816. instanceMatrixNode = mat4( ...instanceBuffers );
  10817. }
  10818. this.instanceMatrixNode = instanceMatrixNode;
  10819. }
  10820. if ( instanceColor && instanceColorNode === null ) {
  10821. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  10822. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  10823. this.bufferColor = buffer;
  10824. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  10825. this.instanceColorNode = instanceColorNode;
  10826. }
  10827. // POSITION
  10828. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  10829. positionLocal.assign( instancePosition );
  10830. // NORMAL
  10831. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  10832. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  10833. // ASSIGNS
  10834. normalLocal.assign( instanceNormal );
  10835. }
  10836. // COLOR
  10837. if ( this.instanceColorNode !== null ) {
  10838. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  10839. }
  10840. }
  10841. /**
  10842. * Checks if the internal buffers required an update.
  10843. *
  10844. * @param {NodeFrame} frame - The current node frame.
  10845. */
  10846. update( /*frame*/ ) {
  10847. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  10848. this.buffer.version = this.instanceMatrix.version;
  10849. }
  10850. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  10851. this.bufferColor.version = this.instanceColor.version;
  10852. }
  10853. }
  10854. }
  10855. /**
  10856. * TSL function for creating an instance node.
  10857. *
  10858. * @tsl
  10859. * @function
  10860. * @param {number} count - The number of instances.
  10861. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  10862. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  10863. * @returns {InstanceNode}
  10864. */
  10865. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  10866. /**
  10867. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  10868. * It allows an easier setup of the instance node.
  10869. *
  10870. * @augments InstanceNode
  10871. */
  10872. class InstancedMeshNode extends InstanceNode {
  10873. static get type() {
  10874. return 'InstancedMeshNode';
  10875. }
  10876. /**
  10877. * Constructs a new instanced mesh node.
  10878. *
  10879. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  10880. */
  10881. constructor( instancedMesh ) {
  10882. const { count, instanceMatrix, instanceColor } = instancedMesh;
  10883. super( count, instanceMatrix, instanceColor );
  10884. /**
  10885. * A reference to the instanced mesh.
  10886. *
  10887. * @type {InstancedMesh}
  10888. */
  10889. this.instancedMesh = instancedMesh;
  10890. }
  10891. }
  10892. /**
  10893. * TSL function for creating an instanced mesh node.
  10894. *
  10895. * @tsl
  10896. * @function
  10897. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  10898. * @returns {InstancedMeshNode}
  10899. */
  10900. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  10901. /**
  10902. * This node implements the vertex shader logic which is required
  10903. * when rendering 3D objects via batching. `BatchNode` must be used
  10904. * with instances of {@link BatchedMesh}.
  10905. *
  10906. * @augments Node
  10907. */
  10908. class BatchNode extends Node {
  10909. static get type() {
  10910. return 'BatchNode';
  10911. }
  10912. /**
  10913. * Constructs a new batch node.
  10914. *
  10915. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  10916. */
  10917. constructor( batchMesh ) {
  10918. super( 'void' );
  10919. /**
  10920. * A reference to batched mesh.
  10921. *
  10922. * @type {BatchedMesh}
  10923. */
  10924. this.batchMesh = batchMesh;
  10925. /**
  10926. * The batching index node.
  10927. *
  10928. * @type {?IndexNode}
  10929. * @default null
  10930. */
  10931. this.batchingIdNode = null;
  10932. }
  10933. /**
  10934. * Setups the internal buffers and nodes and assigns the transformed vertex data
  10935. * to predefined node variables for accumulation. That follows the same patterns
  10936. * like with morph and skinning nodes.
  10937. *
  10938. * @param {NodeBuilder} builder - The current node builder.
  10939. */
  10940. setup( builder ) {
  10941. if ( this.batchingIdNode === null ) {
  10942. if ( builder.getDrawIndex() === null ) {
  10943. this.batchingIdNode = instanceIndex;
  10944. } else {
  10945. this.batchingIdNode = drawIndex;
  10946. }
  10947. }
  10948. const getIndirectIndex = Fn( ( [ id ] ) => {
  10949. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  10950. const x = int( id ).mod( size );
  10951. const y = int( id ).div( size );
  10952. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  10953. } ).setLayout( {
  10954. name: 'getIndirectIndex',
  10955. type: 'uint',
  10956. inputs: [
  10957. { name: 'id', type: 'int' }
  10958. ]
  10959. } );
  10960. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  10961. const matricesTexture = this.batchMesh._matricesTexture;
  10962. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  10963. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  10964. const x = j.mod( size );
  10965. const y = j.div( size );
  10966. const batchingMatrix = mat4(
  10967. textureLoad( matricesTexture, ivec2( x, y ) ),
  10968. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  10969. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  10970. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  10971. );
  10972. const colorsTexture = this.batchMesh._colorsTexture;
  10973. if ( colorsTexture !== null ) {
  10974. const getBatchingColor = Fn( ( [ id ] ) => {
  10975. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  10976. const j = id;
  10977. const x = j.mod( size );
  10978. const y = j.div( size );
  10979. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  10980. } ).setLayout( {
  10981. name: 'getBatchingColor',
  10982. type: 'vec3',
  10983. inputs: [
  10984. { name: 'id', type: 'int' }
  10985. ]
  10986. } );
  10987. const color = getBatchingColor( indirectId );
  10988. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  10989. }
  10990. const bm = mat3( batchingMatrix );
  10991. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  10992. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  10993. const batchingNormal = bm.mul( transformedNormal ).xyz;
  10994. normalLocal.assign( batchingNormal );
  10995. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  10996. tangentLocal.mulAssign( bm );
  10997. }
  10998. }
  10999. }
  11000. /**
  11001. * TSL function for creating a batch node.
  11002. *
  11003. * @tsl
  11004. * @function
  11005. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11006. * @returns {BatchNode}
  11007. */
  11008. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  11009. /**
  11010. * This class enables element access on instances of {@link StorageBufferNode}.
  11011. * In most cases, it is indirectly used when accessing elements with the
  11012. * {@link StorageBufferNode#element} method.
  11013. *
  11014. * ```js
  11015. * const position = positionStorage.element( instanceIndex );
  11016. * ```
  11017. *
  11018. * @augments ArrayElementNode
  11019. */
  11020. class StorageArrayElementNode extends ArrayElementNode {
  11021. static get type() {
  11022. return 'StorageArrayElementNode';
  11023. }
  11024. /**
  11025. * Constructs storage buffer element node.
  11026. *
  11027. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11028. * @param {Node} indexNode - The index node that defines the element access.
  11029. */
  11030. constructor( storageBufferNode, indexNode ) {
  11031. super( storageBufferNode, indexNode );
  11032. /**
  11033. * This flag can be used for type testing.
  11034. *
  11035. * @type {boolean}
  11036. * @readonly
  11037. * @default true
  11038. */
  11039. this.isStorageArrayElementNode = true;
  11040. }
  11041. /**
  11042. * The storage buffer node.
  11043. *
  11044. * @param {Node} value
  11045. * @type {StorageBufferNode}
  11046. */
  11047. set storageBufferNode( value ) {
  11048. this.node = value;
  11049. }
  11050. get storageBufferNode() {
  11051. return this.node;
  11052. }
  11053. getMemberType( builder, name ) {
  11054. const structTypeNode = this.storageBufferNode.structTypeNode;
  11055. if ( structTypeNode ) {
  11056. return structTypeNode.getMemberType( builder, name );
  11057. }
  11058. return 'void';
  11059. }
  11060. setup( builder ) {
  11061. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11062. if ( this.node.isPBO === true ) {
  11063. builder.setupPBO( this.node );
  11064. }
  11065. }
  11066. return super.setup( builder );
  11067. }
  11068. generate( builder, output ) {
  11069. let snippet;
  11070. const isAssignContext = builder.context.assign;
  11071. //
  11072. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11073. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11074. snippet = builder.generatePBO( this );
  11075. } else {
  11076. snippet = this.node.build( builder );
  11077. }
  11078. } else {
  11079. snippet = super.generate( builder );
  11080. }
  11081. if ( isAssignContext !== true ) {
  11082. const type = this.getNodeType( builder );
  11083. snippet = builder.format( snippet, type, output );
  11084. }
  11085. return snippet;
  11086. }
  11087. }
  11088. /**
  11089. * TSL function for creating a storage element node.
  11090. *
  11091. * @tsl
  11092. * @function
  11093. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11094. * @param {Node} indexNode - The index node that defines the element access.
  11095. * @returns {StorageArrayElementNode}
  11096. */
  11097. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11098. /**
  11099. * This node is used in context of compute shaders and allows to define a
  11100. * storage buffer for data. A typical workflow is to create instances of
  11101. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11102. * setup up a compute shader that writes into the buffers and then convert
  11103. * the storage buffers to attribute nodes for rendering.
  11104. *
  11105. * ```js
  11106. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11107. *
  11108. * const computeInit = Fn( () => { // the compute shader
  11109. *
  11110. * const position = positionBuffer.element( instanceIndex );
  11111. *
  11112. * // compute position data
  11113. *
  11114. * position.x = 1;
  11115. * position.y = 1;
  11116. * position.z = 1;
  11117. *
  11118. * } )().compute( particleCount );
  11119. *
  11120. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11121. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11122. *
  11123. * renderer.computeAsync( computeInit );
  11124. *
  11125. * ```
  11126. *
  11127. * @augments BufferNode
  11128. */
  11129. class StorageBufferNode extends BufferNode {
  11130. static get type() {
  11131. return 'StorageBufferNode';
  11132. }
  11133. /**
  11134. * Constructs a new storage buffer node.
  11135. *
  11136. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11137. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11138. * @param {number} [bufferCount=0] - The buffer count.
  11139. */
  11140. constructor( value, bufferType = null, bufferCount = 0 ) {
  11141. let nodeType, structTypeNode = null;
  11142. if ( bufferType && bufferType.isStruct ) {
  11143. nodeType = 'struct';
  11144. structTypeNode = bufferType.layout;
  11145. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11146. bufferCount = value.count;
  11147. }
  11148. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11149. nodeType = getTypeFromLength( value.itemSize );
  11150. bufferCount = value.count;
  11151. } else {
  11152. nodeType = bufferType;
  11153. }
  11154. super( value, nodeType, bufferCount );
  11155. /**
  11156. * This flag can be used for type testing.
  11157. *
  11158. * @type {boolean}
  11159. * @readonly
  11160. * @default true
  11161. */
  11162. this.isStorageBufferNode = true;
  11163. /**
  11164. * The buffer struct type.
  11165. *
  11166. * @type {?StructTypeNode}
  11167. * @default null
  11168. */
  11169. this.structTypeNode = structTypeNode;
  11170. /**
  11171. * The access type of the texture node.
  11172. *
  11173. * @type {string}
  11174. * @default 'readWrite'
  11175. */
  11176. this.access = NodeAccess.READ_WRITE;
  11177. /**
  11178. * Whether the node is atomic or not.
  11179. *
  11180. * @type {boolean}
  11181. * @default false
  11182. */
  11183. this.isAtomic = false;
  11184. /**
  11185. * Whether the node represents a PBO or not.
  11186. * Only relevant for WebGL.
  11187. *
  11188. * @type {boolean}
  11189. * @default false
  11190. */
  11191. this.isPBO = false;
  11192. /**
  11193. * A reference to the internal buffer attribute node.
  11194. *
  11195. * @type {?BufferAttributeNode}
  11196. * @default null
  11197. */
  11198. this._attribute = null;
  11199. /**
  11200. * A reference to the internal varying node.
  11201. *
  11202. * @type {?VaryingNode}
  11203. * @default null
  11204. */
  11205. this._varying = null;
  11206. /**
  11207. * `StorageBufferNode` sets this property to `true` by default.
  11208. *
  11209. * @type {boolean}
  11210. * @default true
  11211. */
  11212. this.global = true;
  11213. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11214. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11215. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11216. else value.isStorageBufferAttribute = true;
  11217. }
  11218. }
  11219. /**
  11220. * This method is overwritten since the buffer data might be shared
  11221. * and thus the hash should be shared as well.
  11222. *
  11223. * @param {NodeBuilder} builder - The current node builder.
  11224. * @return {string} The hash.
  11225. */
  11226. getHash( builder ) {
  11227. if ( this.bufferCount === 0 ) {
  11228. let bufferData = builder.globalCache.getData( this.value );
  11229. if ( bufferData === undefined ) {
  11230. bufferData = {
  11231. node: this
  11232. };
  11233. builder.globalCache.setData( this.value, bufferData );
  11234. }
  11235. return bufferData.node.uuid;
  11236. }
  11237. return this.uuid;
  11238. }
  11239. /**
  11240. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  11241. *
  11242. * @param {NodeBuilder} builder - The current node builder.
  11243. * @return {string} The input type.
  11244. */
  11245. getInputType( /*builder*/ ) {
  11246. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  11247. }
  11248. /**
  11249. * Enables element access with the given index node.
  11250. *
  11251. * @param {IndexNode} indexNode - The index node.
  11252. * @return {StorageArrayElementNode} A node representing the element access.
  11253. */
  11254. element( indexNode ) {
  11255. return storageElement( this, indexNode );
  11256. }
  11257. /**
  11258. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  11259. *
  11260. * @param {boolean} value - The value so set.
  11261. * @return {StorageBufferNode} A reference to this node.
  11262. */
  11263. setPBO( value ) {
  11264. this.isPBO = value;
  11265. return this;
  11266. }
  11267. /**
  11268. * Returns the `isPBO` value.
  11269. *
  11270. * @return {boolean} Whether the node represents a PBO or not.
  11271. */
  11272. getPBO() {
  11273. return this.isPBO;
  11274. }
  11275. /**
  11276. * Defines the node access.
  11277. *
  11278. * @param {string} value - The node access.
  11279. * @return {StorageBufferNode} A reference to this node.
  11280. */
  11281. setAccess( value ) {
  11282. this.access = value;
  11283. return this;
  11284. }
  11285. /**
  11286. * Convenience method for configuring a read-only node access.
  11287. *
  11288. * @return {StorageBufferNode} A reference to this node.
  11289. */
  11290. toReadOnly() {
  11291. return this.setAccess( NodeAccess.READ_ONLY );
  11292. }
  11293. /**
  11294. * Defines whether the node is atomic or not.
  11295. *
  11296. * @param {boolean} value - The atomic flag.
  11297. * @return {StorageBufferNode} A reference to this node.
  11298. */
  11299. setAtomic( value ) {
  11300. this.isAtomic = value;
  11301. return this;
  11302. }
  11303. /**
  11304. * Convenience method for making this node atomic.
  11305. *
  11306. * @return {StorageBufferNode} A reference to this node.
  11307. */
  11308. toAtomic() {
  11309. return this.setAtomic( true );
  11310. }
  11311. /**
  11312. * Returns attribute data for this storage buffer node.
  11313. *
  11314. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  11315. */
  11316. getAttributeData() {
  11317. if ( this._attribute === null ) {
  11318. this._attribute = bufferAttribute( this.value );
  11319. this._varying = varying( this._attribute );
  11320. }
  11321. return {
  11322. attribute: this._attribute,
  11323. varying: this._varying
  11324. };
  11325. }
  11326. /**
  11327. * This method is overwritten since the node type from the availability of storage buffers
  11328. * and the attribute data.
  11329. *
  11330. * @param {NodeBuilder} builder - The current node builder.
  11331. * @return {string} The node type.
  11332. */
  11333. getNodeType( builder ) {
  11334. if ( this.structTypeNode !== null ) {
  11335. return this.structTypeNode.getNodeType( builder );
  11336. }
  11337. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11338. return super.getNodeType( builder );
  11339. }
  11340. const { attribute } = this.getAttributeData();
  11341. return attribute.getNodeType( builder );
  11342. }
  11343. /**
  11344. * Returns the type of a member of the struct.
  11345. *
  11346. * @param {NodeBuilder} builder - The current node builder.
  11347. * @param {string} name - The name of the member.
  11348. * @return {string} The type of the member.
  11349. */
  11350. getMemberType( builder, name ) {
  11351. if ( this.structTypeNode !== null ) {
  11352. return this.structTypeNode.getMemberType( builder, name );
  11353. }
  11354. return 'void';
  11355. }
  11356. /**
  11357. * Generates the code snippet of the storage buffer node.
  11358. *
  11359. * @param {NodeBuilder} builder - The current node builder.
  11360. * @return {string} The generated code snippet.
  11361. */
  11362. generate( builder ) {
  11363. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  11364. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11365. return super.generate( builder );
  11366. }
  11367. const { attribute, varying } = this.getAttributeData();
  11368. const output = varying.build( builder );
  11369. builder.registerTransform( output, attribute );
  11370. return output;
  11371. }
  11372. }
  11373. /**
  11374. * TSL function for creating a storage buffer node.
  11375. *
  11376. * @tsl
  11377. * @function
  11378. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11379. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  11380. * @param {number} [count=0] - The buffer count.
  11381. * @returns {StorageBufferNode}
  11382. */
  11383. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  11384. /**
  11385. * @tsl
  11386. * @function
  11387. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  11388. *
  11389. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11390. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  11391. * @param {number} count - The buffer count.
  11392. * @returns {StorageBufferNode}
  11393. */
  11394. const storageObject = ( value, type, count ) => { // @deprecated, r171
  11395. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  11396. return storage( value, type, count ).setPBO( true );
  11397. };
  11398. const _frameId = new WeakMap();
  11399. /**
  11400. * This node implements the vertex transformation shader logic which is required
  11401. * for skinning/skeletal animation.
  11402. *
  11403. * @augments Node
  11404. */
  11405. class SkinningNode extends Node {
  11406. static get type() {
  11407. return 'SkinningNode';
  11408. }
  11409. /**
  11410. * Constructs a new skinning node.
  11411. *
  11412. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11413. */
  11414. constructor( skinnedMesh ) {
  11415. super( 'void' );
  11416. /**
  11417. * The skinned mesh.
  11418. *
  11419. * @type {SkinnedMesh}
  11420. */
  11421. this.skinnedMesh = skinnedMesh;
  11422. /**
  11423. * The update type overwritten since skinning nodes are updated per object.
  11424. *
  11425. * @type {string}
  11426. */
  11427. this.updateType = NodeUpdateType.OBJECT;
  11428. //
  11429. /**
  11430. * The skin index attribute.
  11431. *
  11432. * @type {AttributeNode}
  11433. */
  11434. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  11435. /**
  11436. * The skin weight attribute.
  11437. *
  11438. * @type {AttributeNode}
  11439. */
  11440. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  11441. /**
  11442. * The bind matrix node.
  11443. *
  11444. * @type {Node<mat4>}
  11445. */
  11446. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  11447. /**
  11448. * The bind matrix inverse node.
  11449. *
  11450. * @type {Node<mat4>}
  11451. */
  11452. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  11453. /**
  11454. * The bind matrices as a uniform buffer node.
  11455. *
  11456. * @type {Node}
  11457. */
  11458. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11459. /**
  11460. * The current vertex position in local space.
  11461. *
  11462. * @type {Node<vec3>}
  11463. */
  11464. this.positionNode = positionLocal;
  11465. /**
  11466. * The result of vertex position in local space.
  11467. *
  11468. * @type {Node<vec3>}
  11469. */
  11470. this.toPositionNode = positionLocal;
  11471. /**
  11472. * The previous bind matrices as a uniform buffer node.
  11473. * Required for computing motion vectors.
  11474. *
  11475. * @type {?Node}
  11476. * @default null
  11477. */
  11478. this.previousBoneMatricesNode = null;
  11479. }
  11480. /**
  11481. * Transforms the given vertex position via skinning.
  11482. *
  11483. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11484. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  11485. * @return {Node<vec3>} The transformed vertex position.
  11486. */
  11487. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  11488. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11489. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11490. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11491. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11492. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11493. // POSITION
  11494. const skinVertex = bindMatrixNode.mul( position );
  11495. const skinned = add(
  11496. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  11497. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  11498. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  11499. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  11500. );
  11501. return bindMatrixInverseNode.mul( skinned ).xyz;
  11502. }
  11503. /**
  11504. * Transforms the given vertex normal via skinning.
  11505. *
  11506. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11507. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  11508. * @return {Node<vec3>} The transformed vertex normal.
  11509. */
  11510. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  11511. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11512. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11513. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11514. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11515. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11516. // NORMAL
  11517. let skinMatrix = add(
  11518. skinWeightNode.x.mul( boneMatX ),
  11519. skinWeightNode.y.mul( boneMatY ),
  11520. skinWeightNode.z.mul( boneMatZ ),
  11521. skinWeightNode.w.mul( boneMatW )
  11522. );
  11523. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  11524. return skinMatrix.transformDirection( normal ).xyz;
  11525. }
  11526. /**
  11527. * Computes the transformed/skinned vertex position of the previous frame.
  11528. *
  11529. * @param {NodeBuilder} builder - The current node builder.
  11530. * @return {Node<vec3>} The skinned position from the previous frame.
  11531. */
  11532. getPreviousSkinnedPosition( builder ) {
  11533. const skinnedMesh = builder.object;
  11534. if ( this.previousBoneMatricesNode === null ) {
  11535. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  11536. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11537. }
  11538. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  11539. }
  11540. /**
  11541. * Returns `true` if bone matrices from the previous frame are required. Relevant
  11542. * when computing motion vectors with {@link VelocityNode}.
  11543. *
  11544. * @param {NodeBuilder} builder - The current node builder.
  11545. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  11546. */
  11547. needsPreviousBoneMatrices( builder ) {
  11548. const mrt = builder.renderer.getMRT();
  11549. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  11550. }
  11551. /**
  11552. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  11553. *
  11554. * @param {NodeBuilder} builder - The current node builder.
  11555. * @return {Node<vec3>} The transformed vertex position.
  11556. */
  11557. setup( builder ) {
  11558. if ( this.needsPreviousBoneMatrices( builder ) ) {
  11559. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  11560. }
  11561. const skinPosition = this.getSkinnedPosition();
  11562. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  11563. //
  11564. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11565. const skinNormal = this.getSkinnedNormal();
  11566. normalLocal.assign( skinNormal );
  11567. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11568. tangentLocal.assign( skinNormal );
  11569. }
  11570. }
  11571. return skinPosition;
  11572. }
  11573. /**
  11574. * Generates the code snippet of the skinning node.
  11575. *
  11576. * @param {NodeBuilder} builder - The current node builder.
  11577. * @param {string} output - The current output.
  11578. * @return {string} The generated code snippet.
  11579. */
  11580. generate( builder, output ) {
  11581. if ( output !== 'void' ) {
  11582. return super.generate( builder, output );
  11583. }
  11584. }
  11585. /**
  11586. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  11587. *
  11588. * @param {NodeFrame} frame - The current node frame.
  11589. */
  11590. update( frame ) {
  11591. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  11592. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  11593. _frameId.set( skeleton, frame.frameId );
  11594. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  11595. skeleton.update();
  11596. }
  11597. }
  11598. /**
  11599. * TSL function for creating a skinning node.
  11600. *
  11601. * @tsl
  11602. * @function
  11603. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11604. * @returns {SkinningNode}
  11605. */
  11606. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  11607. /**
  11608. * TSL function for computing skinning.
  11609. *
  11610. * @tsl
  11611. * @function
  11612. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11613. * @param {Node<vec3>} [toPosition=null] - The target position.
  11614. * @returns {SkinningNode}
  11615. */
  11616. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  11617. const node = new SkinningNode( skinnedMesh );
  11618. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11619. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11620. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11621. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  11622. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  11623. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  11624. node.toPositionNode = toPosition;
  11625. return nodeObject( node );
  11626. };
  11627. /**
  11628. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  11629. * ```js
  11630. * Loop( count, ( { i } ) => {
  11631. *
  11632. * } );
  11633. * ```
  11634. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  11635. * ```js
  11636. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  11637. *
  11638. * } );
  11639. *```
  11640. * Nested loops can be defined in a compacted form:
  11641. * ```js
  11642. * Loop( 10, 5, ( { i, j } ) => {
  11643. *
  11644. * } );
  11645. * ```
  11646. * Loops that should run backwards can be defined like so:
  11647. * ```js
  11648. * Loop( { start: 10 }, () => {} );
  11649. * ```
  11650. * It is possible to execute with boolean values, similar to the `while` syntax.
  11651. * ```js
  11652. * const value = float( 0 ).toVar();
  11653. *
  11654. * Loop( value.lessThan( 10 ), () => {
  11655. *
  11656. * value.addAssign( 1 );
  11657. *
  11658. * } );
  11659. * ```
  11660. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  11661. * @augments Node
  11662. */
  11663. class LoopNode extends Node {
  11664. static get type() {
  11665. return 'LoopNode';
  11666. }
  11667. /**
  11668. * Constructs a new loop node.
  11669. *
  11670. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  11671. */
  11672. constructor( params = [] ) {
  11673. super();
  11674. this.params = params;
  11675. }
  11676. /**
  11677. * Returns a loop variable name based on an index. The pattern is
  11678. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  11679. *
  11680. * @param {number} index - The index.
  11681. * @return {string} The loop variable name.
  11682. */
  11683. getVarName( index ) {
  11684. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  11685. }
  11686. /**
  11687. * Returns properties about this node.
  11688. *
  11689. * @param {NodeBuilder} builder - The current node builder.
  11690. * @return {Object} The node properties.
  11691. */
  11692. getProperties( builder ) {
  11693. const properties = builder.getNodeProperties( this );
  11694. if ( properties.stackNode !== undefined ) return properties;
  11695. //
  11696. const inputs = {};
  11697. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  11698. const param = this.params[ i ];
  11699. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  11700. const type = ( param.isNode !== true && param.type ) || 'int';
  11701. inputs[ name ] = expression( name, type );
  11702. }
  11703. const stack = builder.addStack(); // TODO: cache() it
  11704. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder );
  11705. properties.stackNode = stack;
  11706. const baseParam = this.params[ 0 ];
  11707. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  11708. properties.updateNode = Fn( this.params[ 0 ].update )( inputs );
  11709. }
  11710. builder.removeStack();
  11711. return properties;
  11712. }
  11713. /**
  11714. * This method is overwritten since the node type is inferred based on the loop configuration.
  11715. *
  11716. * @param {NodeBuilder} builder - The current node builder.
  11717. * @return {string} The node type.
  11718. */
  11719. getNodeType( builder ) {
  11720. const { returnsNode } = this.getProperties( builder );
  11721. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  11722. }
  11723. setup( builder ) {
  11724. // setup properties
  11725. this.getProperties( builder );
  11726. }
  11727. generate( builder ) {
  11728. const properties = this.getProperties( builder );
  11729. const params = this.params;
  11730. const stackNode = properties.stackNode;
  11731. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  11732. const param = params[ i ];
  11733. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  11734. if ( param.isNode ) {
  11735. if ( param.getNodeType( builder ) === 'bool' ) {
  11736. isWhile = true;
  11737. type = 'bool';
  11738. end = param.build( builder, type );
  11739. } else {
  11740. type = 'int';
  11741. name = this.getVarName( i );
  11742. start = '0';
  11743. end = param.build( builder, type );
  11744. condition = '<';
  11745. }
  11746. } else {
  11747. type = param.type || 'int';
  11748. name = param.name || this.getVarName( i );
  11749. start = param.start;
  11750. end = param.end;
  11751. condition = param.condition;
  11752. update = param.update;
  11753. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  11754. else if ( start && start.isNode ) start = start.build( builder, type );
  11755. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  11756. else if ( end && end.isNode ) end = end.build( builder, type );
  11757. if ( start !== undefined && end === undefined ) {
  11758. start = start + ' - 1';
  11759. end = '0';
  11760. condition = '>=';
  11761. } else if ( end !== undefined && start === undefined ) {
  11762. start = '0';
  11763. condition = '<';
  11764. }
  11765. if ( condition === undefined ) {
  11766. if ( Number( start ) > Number( end ) ) {
  11767. condition = '>=';
  11768. } else {
  11769. condition = '<';
  11770. }
  11771. }
  11772. }
  11773. let loopSnippet;
  11774. if ( isWhile ) {
  11775. loopSnippet = `while ( ${ end } )`;
  11776. } else {
  11777. const internalParam = { start, end};
  11778. //
  11779. const startSnippet = internalParam.start;
  11780. const endSnippet = internalParam.end;
  11781. let updateSnippet;
  11782. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  11783. if ( update !== undefined && update !== null ) {
  11784. switch ( typeof update ) {
  11785. case 'function':
  11786. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  11787. const snippet = flow.code.replace( /\t|;/g, '' );
  11788. updateSnippet = snippet;
  11789. break;
  11790. case 'number':
  11791. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  11792. break;
  11793. case 'string':
  11794. updateSnippet = name + ' ' + update;
  11795. break;
  11796. default:
  11797. if ( update.isNode ) {
  11798. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  11799. } else {
  11800. console.error( 'THREE.TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  11801. updateSnippet = 'break /* invalid update */';
  11802. }
  11803. }
  11804. } else {
  11805. if ( type === 'int' || type === 'uint' ) {
  11806. update = condition.includes( '<' ) ? '++' : '--';
  11807. } else {
  11808. update = deltaOperator() + ' 1.';
  11809. }
  11810. updateSnippet = name + ' ' + update;
  11811. }
  11812. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  11813. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  11814. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  11815. }
  11816. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  11817. }
  11818. const stackSnippet = stackNode.build( builder, 'void' );
  11819. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  11820. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  11821. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  11822. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  11823. }
  11824. builder.addFlowTab();
  11825. return returnsSnippet;
  11826. }
  11827. }
  11828. /**
  11829. * TSL function for creating a loop node.
  11830. *
  11831. * @tsl
  11832. * @function
  11833. * @param {...any} params - A list of parameters.
  11834. * @returns {LoopNode}
  11835. */
  11836. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).toStack();
  11837. /**
  11838. * TSL function for creating a `Continue()` expression.
  11839. *
  11840. * @tsl
  11841. * @function
  11842. * @returns {ExpressionNode}
  11843. */
  11844. const Continue = () => expression( 'continue' ).toStack();
  11845. /**
  11846. * TSL function for creating a `Break()` expression.
  11847. *
  11848. * @tsl
  11849. * @function
  11850. * @returns {ExpressionNode}
  11851. */
  11852. const Break = () => expression( 'break' ).toStack();
  11853. const _morphTextures = /*@__PURE__*/ new WeakMap();
  11854. const _morphVec4 = /*@__PURE__*/ new Vector4();
  11855. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  11856. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  11857. const y = texelIndex.div( width );
  11858. const x = texelIndex.sub( y.mul( width ) );
  11859. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  11860. return bufferAttrib.mul( influence );
  11861. } );
  11862. function getEntry( geometry ) {
  11863. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  11864. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  11865. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  11866. // instead of using attributes, the WebGL 2 code path encodes morph targets
  11867. // into an array of data textures. Each layer represents a single morph target.
  11868. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11869. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11870. let entry = _morphTextures.get( geometry );
  11871. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  11872. if ( entry !== undefined ) entry.texture.dispose();
  11873. const morphTargets = geometry.morphAttributes.position || [];
  11874. const morphNormals = geometry.morphAttributes.normal || [];
  11875. const morphColors = geometry.morphAttributes.color || [];
  11876. let vertexDataCount = 0;
  11877. if ( hasMorphPosition === true ) vertexDataCount = 1;
  11878. if ( hasMorphNormals === true ) vertexDataCount = 2;
  11879. if ( hasMorphColors === true ) vertexDataCount = 3;
  11880. let width = geometry.attributes.position.count * vertexDataCount;
  11881. let height = 1;
  11882. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  11883. if ( width > maxTextureSize ) {
  11884. height = Math.ceil( width / maxTextureSize );
  11885. width = maxTextureSize;
  11886. }
  11887. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  11888. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  11889. bufferTexture.type = FloatType;
  11890. bufferTexture.needsUpdate = true;
  11891. // fill buffer
  11892. const vertexDataStride = vertexDataCount * 4;
  11893. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  11894. const morphTarget = morphTargets[ i ];
  11895. const morphNormal = morphNormals[ i ];
  11896. const morphColor = morphColors[ i ];
  11897. const offset = width * height * 4 * i;
  11898. for ( let j = 0; j < morphTarget.count; j ++ ) {
  11899. const stride = j * vertexDataStride;
  11900. if ( hasMorphPosition === true ) {
  11901. _morphVec4.fromBufferAttribute( morphTarget, j );
  11902. buffer[ offset + stride + 0 ] = _morphVec4.x;
  11903. buffer[ offset + stride + 1 ] = _morphVec4.y;
  11904. buffer[ offset + stride + 2 ] = _morphVec4.z;
  11905. buffer[ offset + stride + 3 ] = 0;
  11906. }
  11907. if ( hasMorphNormals === true ) {
  11908. _morphVec4.fromBufferAttribute( morphNormal, j );
  11909. buffer[ offset + stride + 4 ] = _morphVec4.x;
  11910. buffer[ offset + stride + 5 ] = _morphVec4.y;
  11911. buffer[ offset + stride + 6 ] = _morphVec4.z;
  11912. buffer[ offset + stride + 7 ] = 0;
  11913. }
  11914. if ( hasMorphColors === true ) {
  11915. _morphVec4.fromBufferAttribute( morphColor, j );
  11916. buffer[ offset + stride + 8 ] = _morphVec4.x;
  11917. buffer[ offset + stride + 9 ] = _morphVec4.y;
  11918. buffer[ offset + stride + 10 ] = _morphVec4.z;
  11919. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  11920. }
  11921. }
  11922. }
  11923. entry = {
  11924. count: morphTargetsCount,
  11925. texture: bufferTexture,
  11926. stride: vertexDataCount,
  11927. size: new Vector2( width, height )
  11928. };
  11929. _morphTextures.set( geometry, entry );
  11930. function disposeTexture() {
  11931. bufferTexture.dispose();
  11932. _morphTextures.delete( geometry );
  11933. geometry.removeEventListener( 'dispose', disposeTexture );
  11934. }
  11935. geometry.addEventListener( 'dispose', disposeTexture );
  11936. }
  11937. return entry;
  11938. }
  11939. /**
  11940. * This node implements the vertex transformation shader logic which is required
  11941. * for morph target animation.
  11942. *
  11943. * @augments Node
  11944. */
  11945. class MorphNode extends Node {
  11946. static get type() {
  11947. return 'MorphNode';
  11948. }
  11949. /**
  11950. * Constructs a new morph node.
  11951. *
  11952. * @param {Mesh} mesh - The mesh holding the morph targets.
  11953. */
  11954. constructor( mesh ) {
  11955. super( 'void' );
  11956. /**
  11957. * The mesh holding the morph targets.
  11958. *
  11959. * @type {Mesh}
  11960. */
  11961. this.mesh = mesh;
  11962. /**
  11963. * A uniform node which represents the morph base influence value.
  11964. *
  11965. * @type {UniformNode<float>}
  11966. */
  11967. this.morphBaseInfluence = uniform( 1 );
  11968. /**
  11969. * The update type overwritten since morph nodes are updated per object.
  11970. *
  11971. * @type {string}
  11972. */
  11973. this.updateType = NodeUpdateType.OBJECT;
  11974. }
  11975. /**
  11976. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  11977. *
  11978. * @param {NodeBuilder} builder - The current node builder.
  11979. */
  11980. setup( builder ) {
  11981. const { geometry } = builder;
  11982. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  11983. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  11984. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11985. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11986. // nodes
  11987. const { texture: bufferMap, stride, size } = getEntry( geometry );
  11988. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  11989. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  11990. const width = int( size.width );
  11991. Loop( morphTargetsCount, ( { i } ) => {
  11992. const influence = float( 0 ).toVar();
  11993. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  11994. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  11995. } else {
  11996. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  11997. }
  11998. If( influence.notEqual( 0 ), () => {
  11999. if ( hasMorphPosition === true ) {
  12000. positionLocal.addAssign( getMorph( {
  12001. bufferMap,
  12002. influence,
  12003. stride,
  12004. width,
  12005. depth: i,
  12006. offset: int( 0 )
  12007. } ) );
  12008. }
  12009. if ( hasMorphNormals === true ) {
  12010. normalLocal.addAssign( getMorph( {
  12011. bufferMap,
  12012. influence,
  12013. stride,
  12014. width,
  12015. depth: i,
  12016. offset: int( 1 )
  12017. } ) );
  12018. }
  12019. } );
  12020. } );
  12021. }
  12022. /**
  12023. * Updates the state of the morphed mesh by updating the base influence.
  12024. *
  12025. * @param {NodeFrame} frame - The current node frame.
  12026. */
  12027. update( /*frame*/ ) {
  12028. const morphBaseInfluence = this.morphBaseInfluence;
  12029. if ( this.mesh.geometry.morphTargetsRelative ) {
  12030. morphBaseInfluence.value = 1;
  12031. } else {
  12032. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  12033. }
  12034. }
  12035. }
  12036. /**
  12037. * TSL function for creating a morph node.
  12038. *
  12039. * @tsl
  12040. * @function
  12041. * @param {Mesh} mesh - The mesh holding the morph targets.
  12042. * @returns {MorphNode}
  12043. */
  12044. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  12045. /**
  12046. * Base class for lighting nodes.
  12047. *
  12048. * @augments Node
  12049. */
  12050. class LightingNode extends Node {
  12051. static get type() {
  12052. return 'LightingNode';
  12053. }
  12054. /**
  12055. * Constructs a new lighting node.
  12056. */
  12057. constructor() {
  12058. super( 'vec3' );
  12059. /**
  12060. * This flag can be used for type testing.
  12061. *
  12062. * @type {boolean}
  12063. * @readonly
  12064. * @default true
  12065. */
  12066. this.isLightingNode = true;
  12067. }
  12068. }
  12069. /**
  12070. * A generic class that can be used by nodes which contribute
  12071. * ambient occlusion to the scene. E.g. an ambient occlusion map
  12072. * node can be used as input for this module. Used in {@link NodeMaterial}.
  12073. *
  12074. * @augments LightingNode
  12075. */
  12076. class AONode extends LightingNode {
  12077. static get type() {
  12078. return 'AONode';
  12079. }
  12080. /**
  12081. * Constructs a new AO node.
  12082. *
  12083. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  12084. */
  12085. constructor( aoNode = null ) {
  12086. super();
  12087. /**
  12088. * The ambient occlusion node.
  12089. *
  12090. * @type {?Node<float>}
  12091. * @default null
  12092. */
  12093. this.aoNode = aoNode;
  12094. }
  12095. setup( builder ) {
  12096. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  12097. }
  12098. }
  12099. /**
  12100. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  12101. * by adding lighting specific context data. It represents the runtime context of
  12102. * {@link LightsNode}.
  12103. *
  12104. * @augments ContextNode
  12105. */
  12106. class LightingContextNode extends ContextNode {
  12107. static get type() {
  12108. return 'LightingContextNode';
  12109. }
  12110. /**
  12111. * Constructs a new lighting context node.
  12112. *
  12113. * @param {LightsNode} lightsNode - The lights node.
  12114. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  12115. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  12116. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  12117. */
  12118. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  12119. super( lightsNode );
  12120. /**
  12121. * The current lighting model.
  12122. *
  12123. * @type {?LightingModel}
  12124. * @default null
  12125. */
  12126. this.lightingModel = lightingModel;
  12127. /**
  12128. * A backdrop node.
  12129. *
  12130. * @type {?Node<vec3>}
  12131. * @default null
  12132. */
  12133. this.backdropNode = backdropNode;
  12134. /**
  12135. * A backdrop alpha node.
  12136. *
  12137. * @type {?Node<float>}
  12138. * @default null
  12139. */
  12140. this.backdropAlphaNode = backdropAlphaNode;
  12141. this._value = null;
  12142. }
  12143. /**
  12144. * Returns a lighting context object.
  12145. *
  12146. * @return {{
  12147. * radiance: Node<vec3>,
  12148. * irradiance: Node<vec3>,
  12149. * iblIrradiance: Node<vec3>,
  12150. * ambientOcclusion: Node<float>,
  12151. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  12152. * backdrop: Node<vec3>,
  12153. * backdropAlpha: Node<float>
  12154. * }} The lighting context object.
  12155. */
  12156. getContext() {
  12157. const { backdropNode, backdropAlphaNode } = this;
  12158. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  12159. directSpecular = vec3().toVar( 'directSpecular' ),
  12160. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  12161. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  12162. const reflectedLight = {
  12163. directDiffuse,
  12164. directSpecular,
  12165. indirectDiffuse,
  12166. indirectSpecular
  12167. };
  12168. const context = {
  12169. radiance: vec3().toVar( 'radiance' ),
  12170. irradiance: vec3().toVar( 'irradiance' ),
  12171. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  12172. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  12173. reflectedLight,
  12174. backdrop: backdropNode,
  12175. backdropAlpha: backdropAlphaNode
  12176. };
  12177. return context;
  12178. }
  12179. setup( builder ) {
  12180. this.value = this._value || ( this._value = this.getContext() );
  12181. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  12182. return super.setup( builder );
  12183. }
  12184. }
  12185. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  12186. /**
  12187. * A generic class that can be used by nodes which contribute
  12188. * irradiance to the scene. E.g. a light map node can be used
  12189. * as input for this module. Used in {@link NodeMaterial}.
  12190. *
  12191. * @augments LightingNode
  12192. */
  12193. class IrradianceNode extends LightingNode {
  12194. static get type() {
  12195. return 'IrradianceNode';
  12196. }
  12197. /**
  12198. * Constructs a new irradiance node.
  12199. *
  12200. * @param {Node<vec3>} node - A node contributing irradiance.
  12201. */
  12202. constructor( node ) {
  12203. super();
  12204. /**
  12205. * A node contributing irradiance.
  12206. *
  12207. * @type {Node<vec3>}
  12208. */
  12209. this.node = node;
  12210. }
  12211. setup( builder ) {
  12212. builder.context.irradiance.addAssign( this.node );
  12213. }
  12214. }
  12215. let screenSizeVec, viewportVec;
  12216. /**
  12217. * This node provides a collection of screen related metrics.
  12218. * Depending on {@link ScreenNode#scope}, the nodes can represent
  12219. * resolution or viewport data as well as fragment or uv coordinates.
  12220. *
  12221. * @augments Node
  12222. */
  12223. class ScreenNode extends Node {
  12224. static get type() {
  12225. return 'ScreenNode';
  12226. }
  12227. /**
  12228. * Constructs a new screen node.
  12229. *
  12230. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  12231. */
  12232. constructor( scope ) {
  12233. super();
  12234. /**
  12235. * The node represents different metric depending on which scope is selected.
  12236. *
  12237. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  12238. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  12239. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  12240. * - `ScreenNode.UV`: Normalized coordinates.
  12241. *
  12242. * @type {('coordinate'|'viewport'|'size'|'uv')}
  12243. */
  12244. this.scope = scope;
  12245. /**
  12246. * This flag can be used for type testing.
  12247. *
  12248. * @type {boolean}
  12249. * @readonly
  12250. * @default true
  12251. */
  12252. this.isViewportNode = true;
  12253. }
  12254. /**
  12255. * This method is overwritten since the node type depends on the selected scope.
  12256. *
  12257. * @return {('vec2'|'vec4')} The node type.
  12258. */
  12259. getNodeType() {
  12260. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  12261. else return 'vec2';
  12262. }
  12263. /**
  12264. * This method is overwritten since the node's update type depends on the selected scope.
  12265. *
  12266. * @return {NodeUpdateType} The update type.
  12267. */
  12268. getUpdateType() {
  12269. let updateType = NodeUpdateType.NONE;
  12270. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  12271. updateType = NodeUpdateType.RENDER;
  12272. }
  12273. this.updateType = updateType;
  12274. return updateType;
  12275. }
  12276. /**
  12277. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  12278. * from the current renderer.
  12279. *
  12280. * @param {NodeFrame} frame - A reference to the current node frame.
  12281. */
  12282. update( { renderer } ) {
  12283. const renderTarget = renderer.getRenderTarget();
  12284. if ( this.scope === ScreenNode.VIEWPORT ) {
  12285. if ( renderTarget !== null ) {
  12286. viewportVec.copy( renderTarget.viewport );
  12287. } else {
  12288. renderer.getViewport( viewportVec );
  12289. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  12290. }
  12291. } else {
  12292. if ( renderTarget !== null ) {
  12293. screenSizeVec.width = renderTarget.width;
  12294. screenSizeVec.height = renderTarget.height;
  12295. } else {
  12296. renderer.getDrawingBufferSize( screenSizeVec );
  12297. }
  12298. }
  12299. }
  12300. setup( /*builder*/ ) {
  12301. const scope = this.scope;
  12302. let output = null;
  12303. if ( scope === ScreenNode.SIZE ) {
  12304. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  12305. } else if ( scope === ScreenNode.VIEWPORT ) {
  12306. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  12307. } else {
  12308. output = vec2( screenCoordinate.div( screenSize ) );
  12309. }
  12310. return output;
  12311. }
  12312. generate( builder ) {
  12313. if ( this.scope === ScreenNode.COORDINATE ) {
  12314. let coord = builder.getFragCoord();
  12315. if ( builder.isFlipY() ) {
  12316. // follow webgpu standards
  12317. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  12318. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  12319. }
  12320. return coord;
  12321. }
  12322. return super.generate( builder );
  12323. }
  12324. }
  12325. ScreenNode.COORDINATE = 'coordinate';
  12326. ScreenNode.VIEWPORT = 'viewport';
  12327. ScreenNode.SIZE = 'size';
  12328. ScreenNode.UV = 'uv';
  12329. // Screen
  12330. /**
  12331. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  12332. *
  12333. * @tsl
  12334. * @type {ScreenNode<vec2>}
  12335. */
  12336. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  12337. /**
  12338. * TSL object that represents the screen resolution in physical pixel units.
  12339. *
  12340. * @tsl
  12341. * @type {ScreenNode<vec2>}
  12342. */
  12343. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  12344. /**
  12345. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  12346. *
  12347. * @tsl
  12348. * @type {ScreenNode<vec2>}
  12349. */
  12350. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  12351. // Viewport
  12352. /**
  12353. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  12354. *
  12355. * @tsl
  12356. * @type {ScreenNode<vec4>}
  12357. */
  12358. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  12359. /**
  12360. * TSL object that represents the viewport resolution in physical pixel units.
  12361. *
  12362. * @tsl
  12363. * @type {ScreenNode<vec2>}
  12364. */
  12365. const viewportSize = viewport.zw;
  12366. /**
  12367. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  12368. *
  12369. * @tsl
  12370. * @type {ScreenNode<vec2>}
  12371. */
  12372. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  12373. /**
  12374. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  12375. *
  12376. * @tsl
  12377. * @type {ScreenNode<vec2>}
  12378. */
  12379. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  12380. // Deprecated
  12381. /**
  12382. * @deprecated since r169. Use {@link screenSize} instead.
  12383. */
  12384. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  12385. console.warn( 'THREE.TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  12386. return screenSize;
  12387. }, 'vec2' ).once() )();
  12388. const _size$4 = /*@__PURE__*/ new Vector2();
  12389. /**
  12390. * A special type of texture node which represents the data of the current viewport
  12391. * as a texture. The module extracts data from the current bound framebuffer with
  12392. * a copy operation so no extra render pass is required to produce the texture data
  12393. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  12394. * variety of effects like refractive or transmissive materials.
  12395. *
  12396. * @augments TextureNode
  12397. */
  12398. class ViewportTextureNode extends TextureNode {
  12399. static get type() {
  12400. return 'ViewportTextureNode';
  12401. }
  12402. /**
  12403. * Constructs a new viewport texture node.
  12404. *
  12405. * @param {Node} [uvNode=screenUV] - The uv node.
  12406. * @param {?Node} [levelNode=null] - The level node.
  12407. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12408. */
  12409. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  12410. let defaultFramebuffer = null;
  12411. if ( framebufferTexture === null ) {
  12412. defaultFramebuffer = new FramebufferTexture();
  12413. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  12414. framebufferTexture = defaultFramebuffer;
  12415. } else {
  12416. defaultFramebuffer = framebufferTexture;
  12417. }
  12418. super( framebufferTexture, uvNode, levelNode );
  12419. /**
  12420. * Whether to generate mipmaps or not.
  12421. *
  12422. * @type {boolean}
  12423. * @default false
  12424. */
  12425. this.generateMipmaps = false;
  12426. /**
  12427. * The reference framebuffer texture. This is used to store the framebuffer texture
  12428. * for the current render target. If the render target changes, a new framebuffer texture
  12429. * is created automatically.
  12430. *
  12431. * @type {FramebufferTexture}
  12432. * @default null
  12433. */
  12434. this.defaultFramebuffer = defaultFramebuffer;
  12435. /**
  12436. * This flag can be used for type testing.
  12437. *
  12438. * @type {boolean}
  12439. * @readonly
  12440. * @default true
  12441. */
  12442. this.isOutputTextureNode = true;
  12443. /**
  12444. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node renders the
  12445. * scene once per render in its {@link ViewportTextureNode#updateBefore} method.
  12446. *
  12447. * @type {string}
  12448. * @default 'frame'
  12449. */
  12450. this.updateBeforeType = NodeUpdateType.RENDER;
  12451. /**
  12452. * The framebuffer texture for the current renderer context.
  12453. *
  12454. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  12455. * @private
  12456. */
  12457. this._textures = new WeakMap();
  12458. }
  12459. getFrameBufferTexture( reference = null ) {
  12460. const defaultFramebuffer = this.referenceNode ? this.referenceNode.defaultFramebuffer : this.defaultFramebuffer;
  12461. if ( reference === null ) {
  12462. return defaultFramebuffer;
  12463. }
  12464. if ( this._textures.has( reference ) === false ) {
  12465. const framebufferTexture = defaultFramebuffer.clone();
  12466. this._textures.set( reference, framebufferTexture );
  12467. }
  12468. return this._textures.get( reference );
  12469. }
  12470. updateBefore( frame ) {
  12471. const renderer = frame.renderer;
  12472. const renderTarget = renderer.getRenderTarget();
  12473. if ( renderTarget === null ) {
  12474. renderer.getDrawingBufferSize( _size$4 );
  12475. } else {
  12476. _size$4.set( renderTarget.width, renderTarget.height );
  12477. }
  12478. //
  12479. const framebufferTexture = this.getFrameBufferTexture( renderTarget );
  12480. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  12481. framebufferTexture.image.width = _size$4.width;
  12482. framebufferTexture.image.height = _size$4.height;
  12483. framebufferTexture.needsUpdate = true;
  12484. }
  12485. //
  12486. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  12487. framebufferTexture.generateMipmaps = this.generateMipmaps;
  12488. renderer.copyFramebufferToTexture( framebufferTexture );
  12489. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  12490. this.value = framebufferTexture;
  12491. }
  12492. clone() {
  12493. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  12494. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  12495. return viewportTextureNode;
  12496. }
  12497. }
  12498. /**
  12499. * TSL function for creating a viewport texture node.
  12500. *
  12501. * @tsl
  12502. * @function
  12503. * @param {?Node} [uvNode=screenUV] - The uv node.
  12504. * @param {?Node} [levelNode=null] - The level node.
  12505. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12506. * @returns {ViewportTextureNode}
  12507. */
  12508. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  12509. /**
  12510. * TSL function for creating a viewport texture node with enabled mipmap generation.
  12511. *
  12512. * @tsl
  12513. * @function
  12514. * @param {?Node} [uvNode=screenUV] - The uv node.
  12515. * @param {?Node} [levelNode=null] - The level node.
  12516. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12517. * @returns {ViewportTextureNode}
  12518. */
  12519. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  12520. let sharedDepthbuffer = null;
  12521. /**
  12522. * Represents the depth of the current viewport as a texture. This module
  12523. * can be used in combination with viewport texture to achieve effects
  12524. * that require depth evaluation.
  12525. *
  12526. * @augments ViewportTextureNode
  12527. */
  12528. class ViewportDepthTextureNode extends ViewportTextureNode {
  12529. static get type() {
  12530. return 'ViewportDepthTextureNode';
  12531. }
  12532. /**
  12533. * Constructs a new viewport depth texture node.
  12534. *
  12535. * @param {Node} [uvNode=screenUV] - The uv node.
  12536. * @param {?Node} [levelNode=null] - The level node.
  12537. */
  12538. constructor( uvNode = screenUV, levelNode = null ) {
  12539. if ( sharedDepthbuffer === null ) {
  12540. sharedDepthbuffer = new DepthTexture();
  12541. }
  12542. super( uvNode, levelNode, sharedDepthbuffer );
  12543. }
  12544. }
  12545. /**
  12546. * TSL function for a viewport depth texture node.
  12547. *
  12548. * @tsl
  12549. * @function
  12550. * @param {?Node} [uvNode=screenUV] - The uv node.
  12551. * @param {?Node} [levelNode=null] - The level node.
  12552. * @returns {ViewportDepthTextureNode}
  12553. */
  12554. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  12555. /**
  12556. * This node offers a collection of features in context of the depth logic in the fragment shader.
  12557. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  12558. * fragment or for depth evaluation purposes.
  12559. *
  12560. * @augments Node
  12561. */
  12562. class ViewportDepthNode extends Node {
  12563. static get type() {
  12564. return 'ViewportDepthNode';
  12565. }
  12566. /**
  12567. * Constructs a new viewport depth node.
  12568. *
  12569. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  12570. * @param {?Node} [valueNode=null] - The value node.
  12571. */
  12572. constructor( scope, valueNode = null ) {
  12573. super( 'float' );
  12574. /**
  12575. * The node behaves differently depending on which scope is selected.
  12576. *
  12577. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  12578. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  12579. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  12580. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  12581. *
  12582. * @type {('depth'|'depthBase'|'linearDepth')}
  12583. */
  12584. this.scope = scope;
  12585. /**
  12586. * Can be used to define a custom depth value.
  12587. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  12588. *
  12589. * @type {?Node}
  12590. * @default null
  12591. */
  12592. this.valueNode = valueNode;
  12593. /**
  12594. * This flag can be used for type testing.
  12595. *
  12596. * @type {boolean}
  12597. * @readonly
  12598. * @default true
  12599. */
  12600. this.isViewportDepthNode = true;
  12601. }
  12602. generate( builder ) {
  12603. const { scope } = this;
  12604. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12605. return builder.getFragDepth();
  12606. }
  12607. return super.generate( builder );
  12608. }
  12609. setup( { camera } ) {
  12610. const { scope } = this;
  12611. const value = this.valueNode;
  12612. let node = null;
  12613. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12614. if ( value !== null ) {
  12615. node = depthBase().assign( value );
  12616. }
  12617. } else if ( scope === ViewportDepthNode.DEPTH ) {
  12618. if ( camera.isPerspectiveCamera ) {
  12619. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  12620. } else {
  12621. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12622. }
  12623. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  12624. if ( value !== null ) {
  12625. if ( camera.isPerspectiveCamera ) {
  12626. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  12627. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  12628. } else {
  12629. node = value;
  12630. }
  12631. } else {
  12632. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12633. }
  12634. }
  12635. return node;
  12636. }
  12637. }
  12638. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  12639. ViewportDepthNode.DEPTH = 'depth';
  12640. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  12641. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  12642. /**
  12643. * TSL function for converting a viewZ value to an orthographic depth value.
  12644. *
  12645. * @tsl
  12646. * @function
  12647. * @param {Node<float>} viewZ - The viewZ node.
  12648. * @param {Node<float>} near - The camera's near value.
  12649. * @param {Node<float>} far - The camera's far value.
  12650. * @returns {Node<float>}
  12651. */
  12652. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  12653. /**
  12654. * TSL function for converting an orthographic depth value to a viewZ value.
  12655. *
  12656. * @tsl
  12657. * @function
  12658. * @param {Node<float>} depth - The orthographic depth.
  12659. * @param {Node<float>} near - The camera's near value.
  12660. * @param {Node<float>} far - The camera's far value.
  12661. * @returns {Node<float>}
  12662. */
  12663. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  12664. /**
  12665. * TSL function for converting a viewZ value to a perspective depth value.
  12666. *
  12667. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  12668. *
  12669. * @tsl
  12670. * @function
  12671. * @param {Node<float>} viewZ - The viewZ node.
  12672. * @param {Node<float>} near - The camera's near value.
  12673. * @param {Node<float>} far - The camera's far value.
  12674. * @returns {Node<float>}
  12675. */
  12676. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  12677. /**
  12678. * TSL function for converting a perspective depth value to a viewZ value.
  12679. *
  12680. * @tsl
  12681. * @function
  12682. * @param {Node<float>} depth - The perspective depth.
  12683. * @param {Node<float>} near - The camera's near value.
  12684. * @param {Node<float>} far - The camera's far value.
  12685. * @returns {Node<float>}
  12686. */
  12687. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  12688. /**
  12689. * TSL function for converting a viewZ value to a logarithmic depth value.
  12690. *
  12691. * @tsl
  12692. * @function
  12693. * @param {Node<float>} viewZ - The viewZ node.
  12694. * @param {Node<float>} near - The camera's near value.
  12695. * @param {Node<float>} far - The camera's far value.
  12696. * @returns {Node<float>}
  12697. */
  12698. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  12699. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  12700. // The final logarithmic depth formula used here is adapted from one described in an
  12701. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  12702. // which was an improvement upon an earlier formula one described in an
  12703. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  12704. // Ulrich's formula is the following:
  12705. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  12706. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  12707. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  12708. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  12709. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  12710. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  12711. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  12712. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  12713. // be used, and ultimately Ulrich's "near plane" version was chosen.
  12714. // Outerra eventually made another improvement to their original "C-constant" variant,
  12715. // but it still does not incorporate the camera near plane (for this version,
  12716. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  12717. // Here we make 4 changes to Ulrich's formula:
  12718. // 1. Clamp the camera near plane so we don't divide by 0.
  12719. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  12720. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  12721. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  12722. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  12723. // so we do the same here, hence the 'viewZ.negate()' call.
  12724. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  12725. near = near.max( 1e-6 ).toVar();
  12726. const numerator = log2( viewZ.negate().div( near ) );
  12727. const denominator = log2( far.div( near ) );
  12728. return numerator.div( denominator );
  12729. };
  12730. /**
  12731. * TSL function for converting a logarithmic depth value to a viewZ value.
  12732. *
  12733. * @tsl
  12734. * @function
  12735. * @param {Node<float>} depth - The logarithmic depth.
  12736. * @param {Node<float>} near - The camera's near value.
  12737. * @param {Node<float>} far - The camera's far value.
  12738. * @returns {Node<float>}
  12739. */
  12740. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  12741. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  12742. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  12743. // a negative viewZ).
  12744. const exponent = depth.mul( log( far.div( near ) ) );
  12745. return float( Math.E ).pow( exponent ).mul( near ).negate();
  12746. };
  12747. /**
  12748. * TSL function for defining a value for the current fragment's depth.
  12749. *
  12750. * @tsl
  12751. * @function
  12752. * @param {Node<float>} value - The depth value to set.
  12753. * @returns {ViewportDepthNode<float>}
  12754. */
  12755. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  12756. /**
  12757. * TSL object that represents the depth value for the current fragment.
  12758. *
  12759. * @tsl
  12760. * @type {ViewportDepthNode}
  12761. */
  12762. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  12763. /**
  12764. * TSL function for converting a perspective depth value to linear depth.
  12765. *
  12766. * @tsl
  12767. * @function
  12768. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  12769. * @returns {ViewportDepthNode<float>}
  12770. */
  12771. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  12772. /**
  12773. * TSL object that represents the linear (orthographic) depth value of the current fragment
  12774. *
  12775. * @tsl
  12776. * @type {ViewportDepthNode}
  12777. */
  12778. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  12779. depth.assign = ( value ) => depthBase( value );
  12780. /**
  12781. * This node is used in {@link NodeMaterial} to setup the clipping
  12782. * which can happen hardware-accelerated (if supported) and optionally
  12783. * use alpha-to-coverage for anti-aliasing clipped edges.
  12784. *
  12785. * @augments Node
  12786. */
  12787. class ClippingNode extends Node {
  12788. static get type() {
  12789. return 'ClippingNode';
  12790. }
  12791. /**
  12792. * Constructs a new clipping node.
  12793. *
  12794. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  12795. * the selected scope influences the behavior of the node and what type of code is generated.
  12796. */
  12797. constructor( scope = ClippingNode.DEFAULT ) {
  12798. super();
  12799. /**
  12800. * The node's scope. Similar to other nodes, the selected scope influences
  12801. * the behavior of the node and what type of code is generated.
  12802. *
  12803. * @type {('default'|'hardware'|'alphaToCoverage')}
  12804. */
  12805. this.scope = scope;
  12806. }
  12807. /**
  12808. * Setups the node depending on the selected scope.
  12809. *
  12810. * @param {NodeBuilder} builder - The current node builder.
  12811. * @return {Node} The result node.
  12812. */
  12813. setup( builder ) {
  12814. super.setup( builder );
  12815. const clippingContext = builder.clippingContext;
  12816. const { intersectionPlanes, unionPlanes } = clippingContext;
  12817. this.hardwareClipping = builder.material.hardwareClipping;
  12818. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  12819. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  12820. } else if ( this.scope === ClippingNode.HARDWARE ) {
  12821. return this.setupHardwareClipping( unionPlanes, builder );
  12822. } else {
  12823. return this.setupDefault( intersectionPlanes, unionPlanes );
  12824. }
  12825. }
  12826. /**
  12827. * Setups alpha to coverage.
  12828. *
  12829. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12830. * @param {Array<Vector4>} unionPlanes - The union planes.
  12831. * @return {Node} The result node.
  12832. */
  12833. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  12834. return Fn( () => {
  12835. const distanceToPlane = float().toVar( 'distanceToPlane' );
  12836. const distanceGradient = float().toVar( 'distanceToGradient' );
  12837. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  12838. const numUnionPlanes = unionPlanes.length;
  12839. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  12840. const clippingPlanes = uniformArray( unionPlanes );
  12841. Loop( numUnionPlanes, ( { i } ) => {
  12842. const plane = clippingPlanes.element( i );
  12843. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  12844. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  12845. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  12846. } );
  12847. }
  12848. const numIntersectionPlanes = intersectionPlanes.length;
  12849. if ( numIntersectionPlanes > 0 ) {
  12850. const clippingPlanes = uniformArray( intersectionPlanes );
  12851. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  12852. Loop( numIntersectionPlanes, ( { i } ) => {
  12853. const plane = clippingPlanes.element( i );
  12854. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  12855. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  12856. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  12857. } );
  12858. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  12859. }
  12860. diffuseColor.a.mulAssign( clipOpacity );
  12861. diffuseColor.a.equal( 0.0 ).discard();
  12862. } )();
  12863. }
  12864. /**
  12865. * Setups the default clipping.
  12866. *
  12867. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12868. * @param {Array<Vector4>} unionPlanes - The union planes.
  12869. * @return {Node} The result node.
  12870. */
  12871. setupDefault( intersectionPlanes, unionPlanes ) {
  12872. return Fn( () => {
  12873. const numUnionPlanes = unionPlanes.length;
  12874. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  12875. const clippingPlanes = uniformArray( unionPlanes );
  12876. Loop( numUnionPlanes, ( { i } ) => {
  12877. const plane = clippingPlanes.element( i );
  12878. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  12879. } );
  12880. }
  12881. const numIntersectionPlanes = intersectionPlanes.length;
  12882. if ( numIntersectionPlanes > 0 ) {
  12883. const clippingPlanes = uniformArray( intersectionPlanes );
  12884. const clipped = bool( true ).toVar( 'clipped' );
  12885. Loop( numIntersectionPlanes, ( { i } ) => {
  12886. const plane = clippingPlanes.element( i );
  12887. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  12888. } );
  12889. clipped.discard();
  12890. }
  12891. } )();
  12892. }
  12893. /**
  12894. * Setups hardware clipping.
  12895. *
  12896. * @param {Array<Vector4>} unionPlanes - The union planes.
  12897. * @param {NodeBuilder} builder - The current node builder.
  12898. * @return {Node} The result node.
  12899. */
  12900. setupHardwareClipping( unionPlanes, builder ) {
  12901. const numUnionPlanes = unionPlanes.length;
  12902. builder.enableHardwareClipping( numUnionPlanes );
  12903. return Fn( () => {
  12904. const clippingPlanes = uniformArray( unionPlanes );
  12905. const hw_clip_distances = builtin( builder.getClipDistance() );
  12906. Loop( numUnionPlanes, ( { i } ) => {
  12907. const plane = clippingPlanes.element( i );
  12908. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  12909. hw_clip_distances.element( i ).assign( distance );
  12910. } );
  12911. } )();
  12912. }
  12913. }
  12914. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  12915. ClippingNode.DEFAULT = 'default';
  12916. ClippingNode.HARDWARE = 'hardware';
  12917. /**
  12918. * TSL function for setting up the default clipping logic.
  12919. *
  12920. * @tsl
  12921. * @function
  12922. * @returns {ClippingNode}
  12923. */
  12924. const clipping = () => nodeObject( new ClippingNode() );
  12925. /**
  12926. * TSL function for setting up alpha to coverage.
  12927. *
  12928. * @tsl
  12929. * @function
  12930. * @returns {ClippingNode}
  12931. */
  12932. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  12933. /**
  12934. * TSL function for setting up hardware-based clipping.
  12935. *
  12936. * @tsl
  12937. * @function
  12938. * @returns {ClippingNode}
  12939. */
  12940. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  12941. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  12942. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  12943. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  12944. 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 ) ) ) ) ) );
  12945. } );
  12946. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  12947. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  12948. } );
  12949. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  12950. // Find the discretized derivatives of our coordinates
  12951. const maxDeriv = max$1(
  12952. length( dFdx( position.xyz ) ),
  12953. length( dFdy( position.xyz ) )
  12954. );
  12955. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  12956. // Find two nearest log-discretized noise scales
  12957. const pixScales = vec2(
  12958. exp2( floor( log2( pixScale ) ) ),
  12959. exp2( ceil( log2( pixScale ) ) )
  12960. );
  12961. // Compute alpha thresholds at our two noise scales
  12962. const alpha = vec2(
  12963. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  12964. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  12965. );
  12966. // Factor to interpolate lerp with
  12967. const lerpFactor = fract( log2( pixScale ) );
  12968. // Interpolate alpha threshold from noise at two scales
  12969. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  12970. // Pass into CDF to compute uniformly distrib threshold
  12971. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  12972. const cases = vec3(
  12973. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  12974. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  12975. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  12976. // Find our final, uniformly distributed alpha threshold (ατ)
  12977. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  12978. // Avoids ατ == 0. Could also do ατ =1-ατ
  12979. return clamp( threshold, 1.0e-6, 1.0 );
  12980. } ).setLayout( {
  12981. name: 'getAlphaHashThreshold',
  12982. type: 'float',
  12983. inputs: [
  12984. { name: 'position', type: 'vec3' }
  12985. ]
  12986. } );
  12987. /**
  12988. * An attribute node for representing vertex colors.
  12989. *
  12990. * @augments AttributeNode
  12991. */
  12992. class VertexColorNode extends AttributeNode {
  12993. static get type() {
  12994. return 'VertexColorNode';
  12995. }
  12996. /**
  12997. * Constructs a new vertex color node.
  12998. *
  12999. * @param {number} index - The attribute index.
  13000. */
  13001. constructor( index ) {
  13002. super( null, 'vec4' );
  13003. /**
  13004. * This flag can be used for type testing.
  13005. *
  13006. * @type {boolean}
  13007. * @readonly
  13008. * @default true
  13009. */
  13010. this.isVertexColorNode = true;
  13011. /**
  13012. * The attribute index to enable more than one sets of vertex colors.
  13013. *
  13014. * @type {number}
  13015. * @default 0
  13016. */
  13017. this.index = index;
  13018. }
  13019. /**
  13020. * Overwrites the default implementation by honoring the attribute index.
  13021. *
  13022. * @param {NodeBuilder} builder - The current node builder.
  13023. * @return {string} The attribute name.
  13024. */
  13025. getAttributeName( /*builder*/ ) {
  13026. const index = this.index;
  13027. return 'color' + ( index > 0 ? index : '' );
  13028. }
  13029. generate( builder ) {
  13030. const attributeName = this.getAttributeName( builder );
  13031. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  13032. let result;
  13033. if ( geometryAttribute === true ) {
  13034. result = super.generate( builder );
  13035. } else {
  13036. // Vertex color fallback should be white
  13037. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  13038. }
  13039. return result;
  13040. }
  13041. serialize( data ) {
  13042. super.serialize( data );
  13043. data.index = this.index;
  13044. }
  13045. deserialize( data ) {
  13046. super.deserialize( data );
  13047. this.index = data.index;
  13048. }
  13049. }
  13050. /**
  13051. * TSL function for creating a reference node.
  13052. *
  13053. * @tsl
  13054. * @function
  13055. * @param {number} [index=0] - The attribute index.
  13056. * @returns {VertexColorNode}
  13057. */
  13058. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  13059. /**
  13060. * Represents a "Color Burn" blend mode.
  13061. *
  13062. * It's designed to darken the base layer's colors based on the color of the blend layer.
  13063. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  13064. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  13065. *
  13066. * @tsl
  13067. * @function
  13068. * @param {Node<vec3>} base - The base color.
  13069. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  13070. * @return {Node<vec3>} The result.
  13071. */
  13072. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13073. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13074. } ).setLayout( {
  13075. name: 'blendBurn',
  13076. type: 'vec3',
  13077. inputs: [
  13078. { name: 'base', type: 'vec3' },
  13079. { name: 'blend', type: 'vec3' }
  13080. ]
  13081. } );
  13082. /**
  13083. * Represents a "Color Dodge" blend mode.
  13084. *
  13085. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  13086. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  13087. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  13088. *
  13089. * @tsl
  13090. * @function
  13091. * @param {Node<vec3>} base - The base color.
  13092. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13093. * @return {Node<vec3>} The result.
  13094. */
  13095. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13096. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13097. } ).setLayout( {
  13098. name: 'blendDodge',
  13099. type: 'vec3',
  13100. inputs: [
  13101. { name: 'base', type: 'vec3' },
  13102. { name: 'blend', type: 'vec3' }
  13103. ]
  13104. } );
  13105. /**
  13106. * Represents a "Screen" blend mode.
  13107. *
  13108. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  13109. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  13110. * effects.
  13111. *
  13112. * @tsl
  13113. * @function
  13114. * @param {Node<vec3>} base - The base color.
  13115. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13116. * @return {Node<vec3>} The result.
  13117. */
  13118. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13119. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  13120. } ).setLayout( {
  13121. name: 'blendScreen',
  13122. type: 'vec3',
  13123. inputs: [
  13124. { name: 'base', type: 'vec3' },
  13125. { name: 'blend', type: 'vec3' }
  13126. ]
  13127. } );
  13128. /**
  13129. * Represents a "Overlay" blend mode.
  13130. *
  13131. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  13132. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  13133. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  13134. *
  13135. * @tsl
  13136. * @function
  13137. * @param {Node<vec3>} base - The base color.
  13138. * @param {Node<vec3>} blend - The blend color
  13139. * @return {Node<vec3>} The result.
  13140. */
  13141. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13142. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  13143. } ).setLayout( {
  13144. name: 'blendOverlay',
  13145. type: 'vec3',
  13146. inputs: [
  13147. { name: 'base', type: 'vec3' },
  13148. { name: 'blend', type: 'vec3' }
  13149. ]
  13150. } );
  13151. /**
  13152. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  13153. * It assumes both input colors have non-premultiplied alpha.
  13154. *
  13155. * @tsl
  13156. * @function
  13157. * @param {Node<vec4>} base - The base color.
  13158. * @param {Node<vec4>} blend - The blend color
  13159. * @return {Node<vec4>} The result.
  13160. */
  13161. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13162. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  13163. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  13164. } ).setLayout( {
  13165. name: 'blendColor',
  13166. type: 'vec4',
  13167. inputs: [
  13168. { name: 'base', type: 'vec4' },
  13169. { name: 'blend', type: 'vec4' }
  13170. ]
  13171. } );
  13172. /**
  13173. * Premultiplies the RGB channels of a color by its alpha channel.
  13174. *
  13175. * This function is useful for converting a non-premultiplied alpha color
  13176. * into a premultiplied alpha format, where the RGB values are scaled
  13177. * by the alpha value. Premultiplied alpha is often used in graphics
  13178. * rendering for certain operations, such as compositing and image processing.
  13179. *
  13180. * @tsl
  13181. * @function
  13182. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  13183. * @return {Node<vec4>} The color with premultiplied alpha.
  13184. */
  13185. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13186. return vec4( color.rgb.mul( color.a ), color.a );
  13187. }, { color: 'vec4', return: 'vec4' } );
  13188. /**
  13189. * Unpremultiplies the RGB channels of a color by its alpha channel.
  13190. *
  13191. * This function is useful for converting a premultiplied alpha color
  13192. * back into a non-premultiplied alpha format, where the RGB values are
  13193. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  13194. * rendering for certain operations, such as compositing and image processing.
  13195. *
  13196. * @tsl
  13197. * @function
  13198. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  13199. * @return {Node<vec4>} The color with non-premultiplied alpha.
  13200. */
  13201. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13202. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  13203. return vec4( color.rgb.div( color.a ), color.a );
  13204. }, { color: 'vec4', return: 'vec4' } );
  13205. // Deprecated
  13206. /**
  13207. * @tsl
  13208. * @function
  13209. * @deprecated since r171. Use {@link blendBurn} instead.
  13210. *
  13211. * @param {...any} params
  13212. * @returns {Function}
  13213. */
  13214. const burn = ( ...params ) => { // @deprecated, r171
  13215. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  13216. return blendBurn( params );
  13217. };
  13218. /**
  13219. * @tsl
  13220. * @function
  13221. * @deprecated since r171. Use {@link blendDodge} instead.
  13222. *
  13223. * @param {...any} params
  13224. * @returns {Function}
  13225. */
  13226. const dodge = ( ...params ) => { // @deprecated, r171
  13227. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  13228. return blendDodge( params );
  13229. };
  13230. /**
  13231. * @tsl
  13232. * @function
  13233. * @deprecated since r171. Use {@link blendScreen} instead.
  13234. *
  13235. * @param {...any} params
  13236. * @returns {Function}
  13237. */
  13238. const screen = ( ...params ) => { // @deprecated, r171
  13239. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  13240. return blendScreen( params );
  13241. };
  13242. /**
  13243. * @tsl
  13244. * @function
  13245. * @deprecated since r171. Use {@link blendOverlay} instead.
  13246. *
  13247. * @param {...any} params
  13248. * @returns {Function}
  13249. */
  13250. const overlay = ( ...params ) => { // @deprecated, r171
  13251. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  13252. return blendOverlay( params );
  13253. };
  13254. /**
  13255. * Base class for all node materials.
  13256. *
  13257. * @augments Material
  13258. */
  13259. class NodeMaterial extends Material {
  13260. static get type() {
  13261. return 'NodeMaterial';
  13262. }
  13263. /**
  13264. * Represents the type of the node material.
  13265. *
  13266. * @type {string}
  13267. */
  13268. get type() {
  13269. return this.constructor.type;
  13270. }
  13271. set type( _value ) { /* */ }
  13272. /**
  13273. * Constructs a new node material.
  13274. */
  13275. constructor() {
  13276. super();
  13277. /**
  13278. * This flag can be used for type testing.
  13279. *
  13280. * @type {boolean}
  13281. * @readonly
  13282. * @default true
  13283. */
  13284. this.isNodeMaterial = true;
  13285. /**
  13286. * Whether this material is affected by fog or not.
  13287. *
  13288. * @type {boolean}
  13289. * @default true
  13290. */
  13291. this.fog = true;
  13292. /**
  13293. * Whether this material is affected by lights or not.
  13294. *
  13295. * @type {boolean}
  13296. * @default false
  13297. */
  13298. this.lights = false;
  13299. /**
  13300. * Whether this material uses hardware clipping or not.
  13301. * This property is managed by the engine and should not be
  13302. * modified by apps.
  13303. *
  13304. * @type {boolean}
  13305. * @default false
  13306. */
  13307. this.hardwareClipping = false;
  13308. /**
  13309. * Node materials which set their `lights` property to `true`
  13310. * are affected by all lights of the scene. Sometimes selective
  13311. * lighting is wanted which means only _some_ lights in the scene
  13312. * affect a material. This can be achieved by creating an instance
  13313. * of {@link LightsNode} with a list of selective
  13314. * lights and assign the node to this property.
  13315. *
  13316. * ```js
  13317. * const customLightsNode = lights( [ light1, light2 ] );
  13318. * material.lightsNode = customLightsNode;
  13319. * ```
  13320. *
  13321. * @type {?LightsNode}
  13322. * @default null
  13323. */
  13324. this.lightsNode = null;
  13325. /**
  13326. * The environment of node materials can be defined by an environment
  13327. * map assigned to the `envMap` property or by `Scene.environment`
  13328. * if the node material is a PBR material. This node property allows to overwrite
  13329. * the default behavior and define the environment with a custom node.
  13330. *
  13331. * ```js
  13332. * material.envNode = pmremTexture( renderTarget.texture );
  13333. * ```
  13334. *
  13335. * @type {?Node<vec3>}
  13336. * @default null
  13337. */
  13338. this.envNode = null;
  13339. /**
  13340. * The lighting of node materials might be influenced by ambient occlusion.
  13341. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  13342. * and the respective `aoMapIntensity`. This node property allows to overwrite
  13343. * the default and define the ambient occlusion with a custom node instead.
  13344. *
  13345. * If you don't want to overwrite the diffuse color but modify the existing
  13346. * values instead, use {@link materialAO}.
  13347. *
  13348. * @type {?Node<float>}
  13349. * @default null
  13350. */
  13351. this.aoNode = null;
  13352. /**
  13353. * The diffuse color of node materials is by default inferred from the
  13354. * `color` and `map` properties. This node property allows to overwrite the default
  13355. * and define the diffuse color with a node instead.
  13356. *
  13357. * ```js
  13358. * material.colorNode = color( 0xff0000 ); // define red color
  13359. * ```
  13360. *
  13361. * If you don't want to overwrite the diffuse color but modify the existing
  13362. * values instead, use {@link materialColor}.
  13363. *
  13364. * ```js
  13365. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  13366. * ```
  13367. *
  13368. * @type {?Node<vec3>}
  13369. * @default null
  13370. */
  13371. this.colorNode = null;
  13372. /**
  13373. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  13374. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  13375. * and define the normals with a node instead.
  13376. *
  13377. * If you don't want to overwrite the normals but modify the existing values instead,
  13378. * use {@link materialNormal}.
  13379. *
  13380. * @type {?Node<vec3>}
  13381. * @default null
  13382. */
  13383. this.normalNode = null;
  13384. /**
  13385. * The opacity of node materials is by default inferred from the `opacity`
  13386. * and `alphaMap` properties. This node property allows to overwrite the default
  13387. * and define the opacity with a node instead.
  13388. *
  13389. * If you don't want to overwrite the normals but modify the existing
  13390. * value instead, use {@link materialOpacity}.
  13391. *
  13392. * @type {?Node<float>}
  13393. * @default null
  13394. */
  13395. this.opacityNode = null;
  13396. /**
  13397. * This node can be used to implement a variety of filter-like effects. The idea is
  13398. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  13399. * to create an arbitrary effect and then assign the node composition to this property.
  13400. * Everything behind the object using this material will now be affected by a filter.
  13401. *
  13402. * ```js
  13403. * const material = new NodeMaterial()
  13404. * material.transparent = true;
  13405. *
  13406. * // everything behind the object will be monochromatic
  13407. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  13408. * ```
  13409. *
  13410. * Backdrop computations are part of the lighting so only lit materials can use this property.
  13411. *
  13412. * @type {?Node<vec3>}
  13413. * @default null
  13414. */
  13415. this.backdropNode = null;
  13416. /**
  13417. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  13418. *
  13419. * @type {?Node<float>}
  13420. * @default null
  13421. */
  13422. this.backdropAlphaNode = null;
  13423. /**
  13424. * The alpha test of node materials is by default inferred from the `alphaTest`
  13425. * property. This node property allows to overwrite the default and define the
  13426. * alpha test with a node instead.
  13427. *
  13428. * If you don't want to overwrite the alpha test but modify the existing
  13429. * value instead, use {@link materialAlphaTest}.
  13430. *
  13431. * @type {?Node<float>}
  13432. * @default null
  13433. */
  13434. this.alphaTestNode = null;
  13435. /**
  13436. * Discards the fragment if the mask value is `false`.
  13437. *
  13438. * @type {?Node<bool>}
  13439. * @default null
  13440. */
  13441. this.maskNode = null;
  13442. /**
  13443. * The local vertex positions are computed based on multiple factors like the
  13444. * attribute data, morphing or skinning. This node property allows to overwrite
  13445. * the default and define local vertex positions with nodes instead.
  13446. *
  13447. * If you don't want to overwrite the vertex positions but modify the existing
  13448. * values instead, use {@link positionLocal}.
  13449. *
  13450. *```js
  13451. * material.positionNode = positionLocal.add( displace );
  13452. * ```
  13453. *
  13454. * @type {?Node<vec3>}
  13455. * @default null
  13456. */
  13457. this.positionNode = null;
  13458. /**
  13459. * This node property is intended for logic which modifies geometry data once or per animation step.
  13460. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  13461. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  13462. * can be implemented.
  13463. *
  13464. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  13465. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  13466. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  13467. * eventually assigned to `geometryNode`.
  13468. *
  13469. * @type {?Function}
  13470. * @default null
  13471. */
  13472. this.geometryNode = null;
  13473. /**
  13474. * Allows to overwrite depth values in the fragment shader.
  13475. *
  13476. * @type {?Node<float>}
  13477. * @default null
  13478. */
  13479. this.depthNode = null;
  13480. /**
  13481. * Allows to overwrite the position used for shadow map rendering which
  13482. * is by default {@link positionWorld}, the vertex position
  13483. * in world space.
  13484. *
  13485. * @type {?Node<float>}
  13486. * @default null
  13487. */
  13488. this.receivedShadowPositionNode = null;
  13489. /**
  13490. * Allows to overwrite the geometry position used for shadow map projection which
  13491. * is by default {@link positionLocal}, the vertex position in local space.
  13492. *
  13493. * @type {?Node<float>}
  13494. * @default null
  13495. */
  13496. this.castShadowPositionNode = null;
  13497. /**
  13498. * This node can be used to influence how an object using this node material
  13499. * receive shadows.
  13500. *
  13501. * ```js
  13502. * const totalShadows = float( 1 ).toVar();
  13503. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  13504. * totalShadows.mulAssign( shadow );
  13505. * //return float( 1 ); // bypass received shadows
  13506. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  13507. * } );
  13508. *
  13509. * @type {?(Function|FunctionNode<vec4>)}
  13510. * @default null
  13511. */
  13512. this.receivedShadowNode = null;
  13513. /**
  13514. * This node can be used to influence how an object using this node material
  13515. * casts shadows. To apply a color to shadows, you can simply do:
  13516. *
  13517. * ```js
  13518. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  13519. * ```
  13520. *
  13521. * Which can be nice to fake colored shadows of semi-transparent objects. It
  13522. * is also common to use the property with `Fn` function so checks are performed
  13523. * per fragment.
  13524. *
  13525. * ```js
  13526. * materialCustomShadow.castShadowNode = Fn( () => {
  13527. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  13528. * return materialColor;
  13529. * } )();
  13530. * ```
  13531. *
  13532. * @type {?Node<vec4>}
  13533. * @default null
  13534. */
  13535. this.castShadowNode = null;
  13536. /**
  13537. * This node can be used to define the final output of the material.
  13538. *
  13539. * TODO: Explain the differences to `fragmentNode`.
  13540. *
  13541. * @type {?Node<vec4>}
  13542. * @default null
  13543. */
  13544. this.outputNode = null;
  13545. /**
  13546. * MRT configuration is done on renderer or pass level. This node allows to
  13547. * overwrite what values are written into MRT targets on material level. This
  13548. * can be useful for implementing selective FX features that should only affect
  13549. * specific objects.
  13550. *
  13551. * @type {?MRTNode}
  13552. * @default null
  13553. */
  13554. this.mrtNode = null;
  13555. /**
  13556. * This node property can be used if you need complete freedom in implementing
  13557. * the fragment shader. Assigning a node will replace the built-in material
  13558. * logic used in the fragment stage.
  13559. *
  13560. * @type {?Node<vec4>}
  13561. * @default null
  13562. */
  13563. this.fragmentNode = null;
  13564. /**
  13565. * This node property can be used if you need complete freedom in implementing
  13566. * the vertex shader. Assigning a node will replace the built-in material logic
  13567. * used in the vertex stage.
  13568. *
  13569. * @type {?Node<vec4>}
  13570. * @default null
  13571. */
  13572. this.vertexNode = null;
  13573. // Deprecated properties
  13574. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  13575. get: () => {
  13576. return this.receivedShadowPositionNode;
  13577. },
  13578. set: ( value ) => {
  13579. console.warn( 'THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  13580. this.receivedShadowPositionNode = value;
  13581. }
  13582. } );
  13583. }
  13584. /**
  13585. * Allows to define a custom cache key that influence the material key computation
  13586. * for render objects.
  13587. *
  13588. * @return {string} The custom cache key.
  13589. */
  13590. customProgramCacheKey() {
  13591. return this.type + getCacheKey$1( this );
  13592. }
  13593. /**
  13594. * Builds this material with the given node builder.
  13595. *
  13596. * @param {NodeBuilder} builder - The current node builder.
  13597. */
  13598. build( builder ) {
  13599. this.setup( builder );
  13600. }
  13601. /**
  13602. * Setups a node material observer with the given builder.
  13603. *
  13604. * @param {NodeBuilder} builder - The current node builder.
  13605. * @return {NodeMaterialObserver} The node material observer.
  13606. */
  13607. setupObserver( builder ) {
  13608. return new NodeMaterialObserver( builder );
  13609. }
  13610. /**
  13611. * Setups the vertex and fragment stage of this node material.
  13612. *
  13613. * @param {NodeBuilder} builder - The current node builder.
  13614. */
  13615. setup( builder ) {
  13616. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  13617. builder.context.setupPositionView = () => this.setupPositionView( builder );
  13618. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  13619. const renderer = builder.renderer;
  13620. const renderTarget = renderer.getRenderTarget();
  13621. // < VERTEX STAGE >
  13622. builder.addStack();
  13623. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  13624. const vertexNode = this.vertexNode || mvp;
  13625. builder.stack.outputNode = vertexNode;
  13626. this.setupHardwareClipping( builder );
  13627. if ( this.geometryNode !== null ) {
  13628. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  13629. }
  13630. builder.addFlow( 'vertex', builder.removeStack() );
  13631. // < FRAGMENT STAGE >
  13632. builder.addStack();
  13633. let resultNode;
  13634. const clippingNode = this.setupClipping( builder );
  13635. if ( this.depthWrite === true || this.depthTest === true ) {
  13636. // only write depth if depth buffer is configured
  13637. if ( renderTarget !== null ) {
  13638. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  13639. } else {
  13640. if ( renderer.depth === true ) this.setupDepth( builder );
  13641. }
  13642. }
  13643. if ( this.fragmentNode === null ) {
  13644. this.setupDiffuseColor( builder );
  13645. this.setupVariants( builder );
  13646. const outgoingLightNode = this.setupLighting( builder );
  13647. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  13648. // force unsigned floats - useful for RenderTargets
  13649. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  13650. resultNode = this.setupOutput( builder, basicOutput );
  13651. // OUTPUT NODE
  13652. output.assign( resultNode );
  13653. //
  13654. const isCustomOutput = this.outputNode !== null;
  13655. if ( isCustomOutput ) resultNode = this.outputNode;
  13656. // MRT
  13657. if ( renderTarget !== null ) {
  13658. const mrt = renderer.getMRT();
  13659. const materialMRT = this.mrtNode;
  13660. if ( mrt !== null ) {
  13661. if ( isCustomOutput ) output.assign( resultNode );
  13662. resultNode = mrt;
  13663. if ( materialMRT !== null ) {
  13664. resultNode = mrt.merge( materialMRT );
  13665. }
  13666. } else if ( materialMRT !== null ) {
  13667. resultNode = materialMRT;
  13668. }
  13669. }
  13670. } else {
  13671. let fragmentNode = this.fragmentNode;
  13672. if ( fragmentNode.isOutputStructNode !== true ) {
  13673. fragmentNode = vec4( fragmentNode );
  13674. }
  13675. resultNode = this.setupOutput( builder, fragmentNode );
  13676. }
  13677. builder.stack.outputNode = resultNode;
  13678. builder.addFlow( 'fragment', builder.removeStack() );
  13679. // < OBSERVER >
  13680. builder.observer = this.setupObserver( builder );
  13681. }
  13682. /**
  13683. * Setups the clipping node.
  13684. *
  13685. * @param {NodeBuilder} builder - The current node builder.
  13686. * @return {ClippingNode} The clipping node.
  13687. */
  13688. setupClipping( builder ) {
  13689. if ( builder.clippingContext === null ) return null;
  13690. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  13691. let result = null;
  13692. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  13693. const samples = builder.renderer.samples;
  13694. if ( this.alphaToCoverage && samples > 1 ) {
  13695. // to be added to flow when the color/alpha value has been determined
  13696. result = clippingAlpha();
  13697. } else {
  13698. builder.stack.add( clipping() );
  13699. }
  13700. }
  13701. return result;
  13702. }
  13703. /**
  13704. * Setups the hardware clipping if available on the current device.
  13705. *
  13706. * @param {NodeBuilder} builder - The current node builder.
  13707. */
  13708. setupHardwareClipping( builder ) {
  13709. this.hardwareClipping = false;
  13710. if ( builder.clippingContext === null ) return;
  13711. const candidateCount = builder.clippingContext.unionPlanes.length;
  13712. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  13713. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  13714. builder.stack.add( hardwareClipping() );
  13715. this.hardwareClipping = true;
  13716. }
  13717. return;
  13718. }
  13719. /**
  13720. * Setups the depth of this material.
  13721. *
  13722. * @param {NodeBuilder} builder - The current node builder.
  13723. */
  13724. setupDepth( builder ) {
  13725. const { renderer, camera } = builder;
  13726. // Depth
  13727. let depthNode = this.depthNode;
  13728. if ( depthNode === null ) {
  13729. const mrt = renderer.getMRT();
  13730. if ( mrt && mrt.has( 'depth' ) ) {
  13731. depthNode = mrt.get( 'depth' );
  13732. } else if ( renderer.logarithmicDepthBuffer === true ) {
  13733. if ( camera.isPerspectiveCamera ) {
  13734. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  13735. } else {
  13736. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13737. }
  13738. }
  13739. }
  13740. if ( depthNode !== null ) {
  13741. depth.assign( depthNode ).toStack();
  13742. }
  13743. }
  13744. /**
  13745. * Setups the position node in view space. This method exists
  13746. * so derived node materials can modify the implementation e.g. sprite materials.
  13747. *
  13748. * @param {NodeBuilder} builder - The current node builder.
  13749. * @return {Node<vec3>} The position in view space.
  13750. */
  13751. setupPositionView( /*builder*/ ) {
  13752. return modelViewMatrix.mul( positionLocal ).xyz;
  13753. }
  13754. /**
  13755. * Setups the position in clip space.
  13756. *
  13757. * @param {NodeBuilder} builder - The current node builder.
  13758. * @return {Node<vec4>} The position in view space.
  13759. */
  13760. setupModelViewProjection( /*builder*/ ) {
  13761. return cameraProjectionMatrix.mul( positionView );
  13762. }
  13763. /**
  13764. * Setups the logic for the vertex stage.
  13765. *
  13766. * @param {NodeBuilder} builder - The current node builder.
  13767. * @return {Node<vec4>} The position in clip space.
  13768. */
  13769. setupVertex( builder ) {
  13770. builder.addStack();
  13771. this.setupPosition( builder );
  13772. builder.context.vertex = builder.removeStack();
  13773. return modelViewProjection;
  13774. }
  13775. /**
  13776. * Setups the computation of the position in local space.
  13777. *
  13778. * @param {NodeBuilder} builder - The current node builder.
  13779. * @return {Node<vec3>} The position in local space.
  13780. */
  13781. setupPosition( builder ) {
  13782. const { object, geometry } = builder;
  13783. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  13784. morphReference( object ).toStack();
  13785. }
  13786. if ( object.isSkinnedMesh === true ) {
  13787. skinning( object ).toStack();
  13788. }
  13789. if ( this.displacementMap ) {
  13790. const displacementMap = materialReference( 'displacementMap', 'texture' );
  13791. const displacementScale = materialReference( 'displacementScale', 'float' );
  13792. const displacementBias = materialReference( 'displacementBias', 'float' );
  13793. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  13794. }
  13795. if ( object.isBatchedMesh ) {
  13796. batch( object ).toStack();
  13797. }
  13798. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  13799. instancedMesh( object ).toStack();
  13800. }
  13801. if ( this.positionNode !== null ) {
  13802. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  13803. }
  13804. return positionLocal;
  13805. }
  13806. /**
  13807. * Setups the computation of the material's diffuse color.
  13808. *
  13809. * @param {NodeBuilder} builder - The current node builder.
  13810. * @param {BufferGeometry} geometry - The geometry.
  13811. */
  13812. setupDiffuseColor( { object, geometry } ) {
  13813. // MASK
  13814. if ( this.maskNode !== null ) {
  13815. // Discard if the mask is `false`
  13816. bool( this.maskNode ).not().discard();
  13817. }
  13818. // COLOR
  13819. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  13820. // VERTEX COLORS
  13821. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  13822. colorNode = colorNode.mul( vertexColor() );
  13823. }
  13824. // INSTANCED COLORS
  13825. if ( object.instanceColor ) {
  13826. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  13827. colorNode = instanceColor.mul( colorNode );
  13828. }
  13829. if ( object.isBatchedMesh && object._colorsTexture ) {
  13830. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  13831. colorNode = batchColor.mul( colorNode );
  13832. }
  13833. // DIFFUSE COLOR
  13834. diffuseColor.assign( colorNode );
  13835. // OPACITY
  13836. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  13837. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  13838. // ALPHA TEST
  13839. let alphaTestNode = null;
  13840. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  13841. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  13842. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  13843. }
  13844. // ALPHA HASH
  13845. if ( this.alphaHash === true ) {
  13846. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  13847. }
  13848. // OPAQUE
  13849. const isOpaque = this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false;
  13850. if ( isOpaque ) {
  13851. diffuseColor.a.assign( 1.0 );
  13852. } else if ( alphaTestNode === null ) {
  13853. diffuseColor.a.lessThanEqual( 0 ).discard();
  13854. }
  13855. }
  13856. /**
  13857. * Abstract interface method that can be implemented by derived materials
  13858. * to setup material-specific node variables.
  13859. *
  13860. * @abstract
  13861. * @param {NodeBuilder} builder - The current node builder.
  13862. */
  13863. setupVariants( /*builder*/ ) {
  13864. // Interface function.
  13865. }
  13866. /**
  13867. * Setups the outgoing light node variable
  13868. *
  13869. * @return {Node<vec3>} The outgoing light node.
  13870. */
  13871. setupOutgoingLight() {
  13872. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  13873. }
  13874. /**
  13875. * Setups the normal node from the material.
  13876. *
  13877. * @return {Node<vec3>} The normal node.
  13878. */
  13879. setupNormal() {
  13880. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  13881. }
  13882. /**
  13883. * Setups the environment node from the material.
  13884. *
  13885. * @param {NodeBuilder} builder - The current node builder.
  13886. * @return {Node<vec4>} The environment node.
  13887. */
  13888. setupEnvironment( /*builder*/ ) {
  13889. let node = null;
  13890. if ( this.envNode ) {
  13891. node = this.envNode;
  13892. } else if ( this.envMap ) {
  13893. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  13894. }
  13895. return node;
  13896. }
  13897. /**
  13898. * Setups the light map node from the material.
  13899. *
  13900. * @param {NodeBuilder} builder - The current node builder.
  13901. * @return {Node<vec3>} The light map node.
  13902. */
  13903. setupLightMap( builder ) {
  13904. let node = null;
  13905. if ( builder.material.lightMap ) {
  13906. node = new IrradianceNode( materialLightMap );
  13907. }
  13908. return node;
  13909. }
  13910. /**
  13911. * Setups the lights node based on the scene, environment and material.
  13912. *
  13913. * @param {NodeBuilder} builder - The current node builder.
  13914. * @return {LightsNode} The lights node.
  13915. */
  13916. setupLights( builder ) {
  13917. const materialLightsNode = [];
  13918. //
  13919. const envNode = this.setupEnvironment( builder );
  13920. if ( envNode && envNode.isLightingNode ) {
  13921. materialLightsNode.push( envNode );
  13922. }
  13923. const lightMapNode = this.setupLightMap( builder );
  13924. if ( lightMapNode && lightMapNode.isLightingNode ) {
  13925. materialLightsNode.push( lightMapNode );
  13926. }
  13927. if ( this.aoNode !== null || builder.material.aoMap ) {
  13928. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  13929. materialLightsNode.push( new AONode( aoNode ) );
  13930. }
  13931. let lightsN = this.lightsNode || builder.lightsNode;
  13932. if ( materialLightsNode.length > 0 ) {
  13933. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  13934. }
  13935. return lightsN;
  13936. }
  13937. /**
  13938. * This method should be implemented by most derived materials
  13939. * since it defines the material's lighting model.
  13940. *
  13941. * @abstract
  13942. * @param {NodeBuilder} builder - The current node builder.
  13943. * @return {LightingModel} The lighting model.
  13944. */
  13945. setupLightingModel( /*builder*/ ) {
  13946. // Interface function.
  13947. }
  13948. /**
  13949. * Setups the outgoing light node.
  13950. *
  13951. * @param {NodeBuilder} builder - The current node builder.
  13952. * @return {Node<vec3>} The outgoing light node.
  13953. */
  13954. setupLighting( builder ) {
  13955. const { material } = builder;
  13956. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  13957. // OUTGOING LIGHT
  13958. const lights = this.lights === true || this.lightsNode !== null;
  13959. const lightsNode = lights ? this.setupLights( builder ) : null;
  13960. let outgoingLightNode = this.setupOutgoingLight( builder );
  13961. if ( lightsNode && lightsNode.getScope().hasLights ) {
  13962. const lightingModel = this.setupLightingModel( builder ) || null;
  13963. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  13964. } else if ( backdropNode !== null ) {
  13965. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  13966. }
  13967. // EMISSIVE
  13968. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  13969. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  13970. outgoingLightNode = outgoingLightNode.add( emissive );
  13971. }
  13972. return outgoingLightNode;
  13973. }
  13974. /**
  13975. * Setup the fog.
  13976. *
  13977. * @param {NodeBuilder} builder - The current node builder.
  13978. * @param {Node<vec4>} outputNode - The existing output node.
  13979. * @return {Node<vec4>} The output node.
  13980. */
  13981. setupFog( builder, outputNode ) {
  13982. const fogNode = builder.fogNode;
  13983. if ( fogNode ) {
  13984. output.assign( outputNode );
  13985. outputNode = vec4( fogNode.toVar() );
  13986. }
  13987. return outputNode;
  13988. }
  13989. /**
  13990. * Setups premultiplied alpha.
  13991. *
  13992. * @param {NodeBuilder} builder - The current node builder.
  13993. * @param {Node<vec4>} outputNode - The existing output node.
  13994. * @return {Node<vec4>} The output node.
  13995. */
  13996. setupPremultipliedAlpha( builder, outputNode ) {
  13997. return premultiplyAlpha( outputNode );
  13998. }
  13999. /**
  14000. * Setups the output node.
  14001. *
  14002. * @param {NodeBuilder} builder - The current node builder.
  14003. * @param {Node<vec4>} outputNode - The existing output node.
  14004. * @return {Node<vec4>} The output node.
  14005. */
  14006. setupOutput( builder, outputNode ) {
  14007. // FOG
  14008. if ( this.fog === true ) {
  14009. outputNode = this.setupFog( builder, outputNode );
  14010. }
  14011. // PREMULTIPLIED ALPHA
  14012. if ( this.premultipliedAlpha === true ) {
  14013. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  14014. }
  14015. return outputNode;
  14016. }
  14017. /**
  14018. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  14019. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  14020. * defining all material properties of the classic type in the node type.
  14021. *
  14022. * @param {Material} material - The material to copy properties with their values to this node material.
  14023. */
  14024. setDefaultValues( material ) {
  14025. // This approach is to reuse the native refreshUniforms*
  14026. // and turn available the use of features like transmission and environment in core
  14027. for ( const property in material ) {
  14028. const value = material[ property ];
  14029. if ( this[ property ] === undefined ) {
  14030. this[ property ] = value;
  14031. if ( value && value.clone ) this[ property ] = value.clone();
  14032. }
  14033. }
  14034. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  14035. for ( const key in descriptors ) {
  14036. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  14037. descriptors[ key ].get !== undefined ) {
  14038. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  14039. }
  14040. }
  14041. }
  14042. /**
  14043. * Serializes this material to JSON.
  14044. *
  14045. * @param {?(Object|string)} meta - The meta information for serialization.
  14046. * @return {Object} The serialized node.
  14047. */
  14048. toJSON( meta ) {
  14049. const isRoot = ( meta === undefined || typeof meta === 'string' );
  14050. if ( isRoot ) {
  14051. meta = {
  14052. textures: {},
  14053. images: {},
  14054. nodes: {}
  14055. };
  14056. }
  14057. const data = Material.prototype.toJSON.call( this, meta );
  14058. const nodeChildren = getNodeChildren( this );
  14059. data.inputNodes = {};
  14060. for ( const { property, childNode } of nodeChildren ) {
  14061. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  14062. }
  14063. // TODO: Copied from Object3D.toJSON
  14064. function extractFromCache( cache ) {
  14065. const values = [];
  14066. for ( const key in cache ) {
  14067. const data = cache[ key ];
  14068. delete data.metadata;
  14069. values.push( data );
  14070. }
  14071. return values;
  14072. }
  14073. if ( isRoot ) {
  14074. const textures = extractFromCache( meta.textures );
  14075. const images = extractFromCache( meta.images );
  14076. const nodes = extractFromCache( meta.nodes );
  14077. if ( textures.length > 0 ) data.textures = textures;
  14078. if ( images.length > 0 ) data.images = images;
  14079. if ( nodes.length > 0 ) data.nodes = nodes;
  14080. }
  14081. return data;
  14082. }
  14083. /**
  14084. * Copies the properties of the given node material to this instance.
  14085. *
  14086. * @param {NodeMaterial} source - The material to copy.
  14087. * @return {NodeMaterial} A reference to this node material.
  14088. */
  14089. copy( source ) {
  14090. this.lightsNode = source.lightsNode;
  14091. this.envNode = source.envNode;
  14092. this.colorNode = source.colorNode;
  14093. this.normalNode = source.normalNode;
  14094. this.opacityNode = source.opacityNode;
  14095. this.backdropNode = source.backdropNode;
  14096. this.backdropAlphaNode = source.backdropAlphaNode;
  14097. this.alphaTestNode = source.alphaTestNode;
  14098. this.maskNode = source.maskNode;
  14099. this.positionNode = source.positionNode;
  14100. this.geometryNode = source.geometryNode;
  14101. this.depthNode = source.depthNode;
  14102. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  14103. this.castShadowPositionNode = source.castShadowPositionNode;
  14104. this.receivedShadowNode = source.receivedShadowNode;
  14105. this.castShadowNode = source.castShadowNode;
  14106. this.outputNode = source.outputNode;
  14107. this.mrtNode = source.mrtNode;
  14108. this.fragmentNode = source.fragmentNode;
  14109. this.vertexNode = source.vertexNode;
  14110. return super.copy( source );
  14111. }
  14112. }
  14113. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  14114. /**
  14115. * Node material version of {@link LineBasicMaterial}.
  14116. *
  14117. * @augments NodeMaterial
  14118. */
  14119. class LineBasicNodeMaterial extends NodeMaterial {
  14120. static get type() {
  14121. return 'LineBasicNodeMaterial';
  14122. }
  14123. /**
  14124. * Constructs a new line basic node material.
  14125. *
  14126. * @param {Object} [parameters] - The configuration parameter.
  14127. */
  14128. constructor( parameters ) {
  14129. super();
  14130. /**
  14131. * This flag can be used for type testing.
  14132. *
  14133. * @type {boolean}
  14134. * @readonly
  14135. * @default true
  14136. */
  14137. this.isLineBasicNodeMaterial = true;
  14138. this.setDefaultValues( _defaultValues$d );
  14139. this.setValues( parameters );
  14140. }
  14141. }
  14142. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  14143. /**
  14144. * Node material version of {@link LineDashedMaterial}.
  14145. *
  14146. * @augments NodeMaterial
  14147. */
  14148. class LineDashedNodeMaterial extends NodeMaterial {
  14149. static get type() {
  14150. return 'LineDashedNodeMaterial';
  14151. }
  14152. /**
  14153. * Constructs a new line dashed node material.
  14154. *
  14155. * @param {Object} [parameters] - The configuration parameter.
  14156. */
  14157. constructor( parameters ) {
  14158. super();
  14159. /**
  14160. * This flag can be used for type testing.
  14161. *
  14162. * @type {boolean}
  14163. * @readonly
  14164. * @default true
  14165. */
  14166. this.isLineDashedNodeMaterial = true;
  14167. this.setDefaultValues( _defaultValues$c );
  14168. /**
  14169. * The dash offset.
  14170. *
  14171. * @type {number}
  14172. * @default 0
  14173. */
  14174. this.dashOffset = 0;
  14175. /**
  14176. * The offset of dash materials is by default inferred from the `dashOffset`
  14177. * property. This node property allows to overwrite the default
  14178. * and define the offset with a node instead.
  14179. *
  14180. * If you don't want to overwrite the offset but modify the existing
  14181. * value instead, use {@link materialLineDashOffset}.
  14182. *
  14183. * @type {?Node<float>}
  14184. * @default null
  14185. */
  14186. this.offsetNode = null;
  14187. /**
  14188. * The scale of dash materials is by default inferred from the `scale`
  14189. * property. This node property allows to overwrite the default
  14190. * and define the scale with a node instead.
  14191. *
  14192. * If you don't want to overwrite the scale but modify the existing
  14193. * value instead, use {@link materialLineScale}.
  14194. *
  14195. * @type {?Node<float>}
  14196. * @default null
  14197. */
  14198. this.dashScaleNode = null;
  14199. /**
  14200. * The dash size of dash materials is by default inferred from the `dashSize`
  14201. * property. This node property allows to overwrite the default
  14202. * and define the dash size with a node instead.
  14203. *
  14204. * If you don't want to overwrite the dash size but modify the existing
  14205. * value instead, use {@link materialLineDashSize}.
  14206. *
  14207. * @type {?Node<float>}
  14208. * @default null
  14209. */
  14210. this.dashSizeNode = null;
  14211. /**
  14212. * The gap size of dash materials is by default inferred from the `gapSize`
  14213. * property. This node property allows to overwrite the default
  14214. * and define the gap size with a node instead.
  14215. *
  14216. * If you don't want to overwrite the gap size but modify the existing
  14217. * value instead, use {@link materialLineGapSize}.
  14218. *
  14219. * @type {?Node<float>}
  14220. * @default null
  14221. */
  14222. this.gapSizeNode = null;
  14223. this.setValues( parameters );
  14224. }
  14225. /**
  14226. * Setups the dash specific node variables.
  14227. *
  14228. * @param {NodeBuilder} builder - The current node builder.
  14229. */
  14230. setupVariants( /* builder */ ) {
  14231. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14232. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14233. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14234. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14235. dashSize.assign( dashSizeNode );
  14236. gapSize.assign( gapSizeNode );
  14237. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  14238. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  14239. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  14240. }
  14241. }
  14242. let _sharedFramebuffer = null;
  14243. /**
  14244. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  14245. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  14246. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  14247. *
  14248. * @augments ViewportTextureNode
  14249. */
  14250. class ViewportSharedTextureNode extends ViewportTextureNode {
  14251. static get type() {
  14252. return 'ViewportSharedTextureNode';
  14253. }
  14254. /**
  14255. * Constructs a new viewport shared texture node.
  14256. *
  14257. * @param {Node} [uvNode=screenUV] - The uv node.
  14258. * @param {?Node} [levelNode=null] - The level node.
  14259. */
  14260. constructor( uvNode = screenUV, levelNode = null ) {
  14261. if ( _sharedFramebuffer === null ) {
  14262. _sharedFramebuffer = new FramebufferTexture();
  14263. }
  14264. super( uvNode, levelNode, _sharedFramebuffer );
  14265. }
  14266. updateReference() {
  14267. return this;
  14268. }
  14269. }
  14270. /**
  14271. * TSL function for creating a shared viewport texture node.
  14272. *
  14273. * @tsl
  14274. * @function
  14275. * @param {?Node} [uvNode=screenUV] - The uv node.
  14276. * @param {?Node} [levelNode=null] - The level node.
  14277. * @returns {ViewportSharedTextureNode}
  14278. */
  14279. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  14280. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  14281. /**
  14282. * This node material can be used to render lines with a size larger than one
  14283. * by representing them as instanced meshes.
  14284. *
  14285. * @augments NodeMaterial
  14286. */
  14287. class Line2NodeMaterial extends NodeMaterial {
  14288. static get type() {
  14289. return 'Line2NodeMaterial';
  14290. }
  14291. /**
  14292. * Constructs a new node material for wide line rendering.
  14293. *
  14294. * @param {Object} [parameters={}] - The configuration parameter.
  14295. */
  14296. constructor( parameters = {} ) {
  14297. super();
  14298. /**
  14299. * This flag can be used for type testing.
  14300. *
  14301. * @type {boolean}
  14302. * @readonly
  14303. * @default true
  14304. */
  14305. this.isLine2NodeMaterial = true;
  14306. this.setDefaultValues( _defaultValues$b );
  14307. /**
  14308. * Whether vertex colors should be used or not.
  14309. *
  14310. * @type {boolean}
  14311. * @default false
  14312. */
  14313. this.useColor = parameters.vertexColors;
  14314. /**
  14315. * The dash offset.
  14316. *
  14317. * @type {number}
  14318. * @default 0
  14319. */
  14320. this.dashOffset = 0;
  14321. /**
  14322. * Defines the lines color.
  14323. *
  14324. * @type {?Node<vec3>}
  14325. * @default null
  14326. */
  14327. this.lineColorNode = null;
  14328. /**
  14329. * Defines the offset.
  14330. *
  14331. * @type {?Node<float>}
  14332. * @default null
  14333. */
  14334. this.offsetNode = null;
  14335. /**
  14336. * Defines the dash scale.
  14337. *
  14338. * @type {?Node<float>}
  14339. * @default null
  14340. */
  14341. this.dashScaleNode = null;
  14342. /**
  14343. * Defines the dash size.
  14344. *
  14345. * @type {?Node<float>}
  14346. * @default null
  14347. */
  14348. this.dashSizeNode = null;
  14349. /**
  14350. * Defines the gap size.
  14351. *
  14352. * @type {?Node<float>}
  14353. * @default null
  14354. */
  14355. this.gapSizeNode = null;
  14356. /**
  14357. * Blending is set to `NoBlending` since transparency
  14358. * is not supported, yet.
  14359. *
  14360. * @type {number}
  14361. * @default 0
  14362. */
  14363. this.blending = NoBlending;
  14364. this._useDash = parameters.dashed;
  14365. this._useAlphaToCoverage = true;
  14366. this._useWorldUnits = false;
  14367. this.setValues( parameters );
  14368. }
  14369. /**
  14370. * Setups the vertex and fragment stage of this node material.
  14371. *
  14372. * @param {NodeBuilder} builder - The current node builder.
  14373. */
  14374. setup( builder ) {
  14375. const { renderer } = builder;
  14376. const useAlphaToCoverage = this._useAlphaToCoverage;
  14377. const useColor = this.useColor;
  14378. const useDash = this._useDash;
  14379. const useWorldUnits = this._useWorldUnits;
  14380. const trimSegment = Fn( ( { start, end } ) => {
  14381. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  14382. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  14383. const nearEstimate = b.mul( -0.5 ).div( a );
  14384. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  14385. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  14386. } ).setLayout( {
  14387. name: 'trimSegment',
  14388. type: 'vec4',
  14389. inputs: [
  14390. { name: 'start', type: 'vec4' },
  14391. { name: 'end', type: 'vec4' }
  14392. ]
  14393. } );
  14394. this.vertexNode = Fn( () => {
  14395. const instanceStart = attribute( 'instanceStart' );
  14396. const instanceEnd = attribute( 'instanceEnd' );
  14397. // camera space
  14398. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  14399. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  14400. if ( useDash ) {
  14401. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14402. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14403. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  14404. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  14405. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  14406. lineDistance = lineDistance.add( offsetNode );
  14407. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  14408. }
  14409. if ( useWorldUnits ) {
  14410. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  14411. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  14412. }
  14413. const aspect = viewport.z.div( viewport.w );
  14414. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  14415. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  14416. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  14417. // perhaps there is a more elegant solution -- WestLangley
  14418. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  14419. If( perspective, () => {
  14420. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  14421. end.assign( trimSegment( { start: start, end: end } ) );
  14422. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  14423. start.assign( trimSegment( { start: end, end: start } ) );
  14424. } );
  14425. } );
  14426. // clip space
  14427. const clipStart = cameraProjectionMatrix.mul( start );
  14428. const clipEnd = cameraProjectionMatrix.mul( end );
  14429. // ndc space
  14430. const ndcStart = clipStart.xyz.div( clipStart.w );
  14431. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  14432. // direction
  14433. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  14434. // account for clip-space aspect ratio
  14435. dir.x.assign( dir.x.mul( aspect ) );
  14436. dir.assign( dir.normalize() );
  14437. const clip = vec4().toVar();
  14438. if ( useWorldUnits ) {
  14439. // get the offset direction as perpendicular to the view vector
  14440. const worldDir = end.xyz.sub( start.xyz ).normalize();
  14441. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  14442. const worldUp = worldDir.cross( tmpFwd ).normalize();
  14443. const worldFwd = worldDir.cross( worldUp );
  14444. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  14445. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  14446. // height offset
  14447. const hw = materialLineWidth.mul( 0.5 );
  14448. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  14449. // don't extend the line if we're rendering dashes because we
  14450. // won't be rendering the endcaps
  14451. if ( ! useDash ) {
  14452. // cap extension
  14453. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  14454. // add width to the box
  14455. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  14456. // endcaps
  14457. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  14458. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  14459. } );
  14460. }
  14461. // project the worldpos
  14462. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  14463. // shift the depth of the projected points so the line
  14464. // segments overlap neatly
  14465. const clipPose = vec3().toVar();
  14466. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  14467. clip.z.assign( clipPose.z.mul( clip.w ) );
  14468. } else {
  14469. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  14470. // undo aspect ratio adjustment
  14471. dir.x.assign( dir.x.div( aspect ) );
  14472. offset.x.assign( offset.x.div( aspect ) );
  14473. // sign flip
  14474. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  14475. // endcaps
  14476. If( positionGeometry.y.lessThan( 0.0 ), () => {
  14477. offset.assign( offset.sub( dir ) );
  14478. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  14479. offset.assign( offset.add( dir ) );
  14480. } );
  14481. // adjust for linewidth
  14482. offset.assign( offset.mul( materialLineWidth ) );
  14483. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  14484. offset.assign( offset.div( viewport.w ) );
  14485. // select end
  14486. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  14487. // back to clip space
  14488. offset.assign( offset.mul( clip.w ) );
  14489. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  14490. }
  14491. return clip;
  14492. } )();
  14493. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  14494. const p13 = p1.sub( p3 );
  14495. const p43 = p4.sub( p3 );
  14496. const p21 = p2.sub( p1 );
  14497. const d1343 = p13.dot( p43 );
  14498. const d4321 = p43.dot( p21 );
  14499. const d1321 = p13.dot( p21 );
  14500. const d4343 = p43.dot( p43 );
  14501. const d2121 = p21.dot( p21 );
  14502. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  14503. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  14504. const mua = numer.div( denom ).clamp();
  14505. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  14506. return vec2( mua, mub );
  14507. } );
  14508. this.colorNode = Fn( () => {
  14509. const vUv = uv$1();
  14510. if ( useDash ) {
  14511. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14512. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14513. dashSize.assign( dashSizeNode );
  14514. gapSize.assign( gapSizeNode );
  14515. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  14516. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  14517. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  14518. }
  14519. const alpha = float( 1 ).toVar( 'alpha' );
  14520. if ( useWorldUnits ) {
  14521. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  14522. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  14523. // Find the closest points on the view ray and the line segment
  14524. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  14525. const lineDir = worldEnd.sub( worldStart );
  14526. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  14527. const p1 = worldStart.add( lineDir.mul( params.x ) );
  14528. const p2 = rayEnd.mul( params.y );
  14529. const delta = p1.sub( p2 );
  14530. const len = delta.length();
  14531. const norm = len.div( materialLineWidth );
  14532. if ( ! useDash ) {
  14533. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  14534. const dnorm = norm.fwidth();
  14535. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  14536. } else {
  14537. norm.greaterThan( 0.5 ).discard();
  14538. }
  14539. }
  14540. } else {
  14541. // round endcaps
  14542. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  14543. const a = vUv.x;
  14544. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  14545. const len2 = a.mul( a ).add( b.mul( b ) );
  14546. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  14547. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  14548. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  14549. } );
  14550. } else {
  14551. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  14552. const a = vUv.x;
  14553. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  14554. const len2 = a.mul( a ).add( b.mul( b ) );
  14555. len2.greaterThan( 1.0 ).discard();
  14556. } );
  14557. }
  14558. }
  14559. let lineColorNode;
  14560. if ( this.lineColorNode ) {
  14561. lineColorNode = this.lineColorNode;
  14562. } else {
  14563. if ( useColor ) {
  14564. const instanceColorStart = attribute( 'instanceColorStart' );
  14565. const instanceColorEnd = attribute( 'instanceColorEnd' );
  14566. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  14567. lineColorNode = instanceColor.mul( materialColor );
  14568. } else {
  14569. lineColorNode = materialColor;
  14570. }
  14571. }
  14572. return vec4( lineColorNode, alpha );
  14573. } )();
  14574. if ( this.transparent ) {
  14575. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14576. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  14577. }
  14578. super.setup( builder );
  14579. }
  14580. /**
  14581. * Whether the lines should sized in world units or not.
  14582. * When set to `false` the unit is pixel.
  14583. *
  14584. * @type {boolean}
  14585. * @default false
  14586. */
  14587. get worldUnits() {
  14588. return this._useWorldUnits;
  14589. }
  14590. set worldUnits( value ) {
  14591. if ( this._useWorldUnits !== value ) {
  14592. this._useWorldUnits = value;
  14593. this.needsUpdate = true;
  14594. }
  14595. }
  14596. /**
  14597. * Whether the lines should be dashed or not.
  14598. *
  14599. * @type {boolean}
  14600. * @default false
  14601. */
  14602. get dashed() {
  14603. return this._useDash;
  14604. }
  14605. set dashed( value ) {
  14606. if ( this._useDash !== value ) {
  14607. this._useDash = value;
  14608. this.needsUpdate = true;
  14609. }
  14610. }
  14611. /**
  14612. * Whether alpha to coverage should be used or not.
  14613. *
  14614. * @type {boolean}
  14615. * @default true
  14616. */
  14617. get alphaToCoverage() {
  14618. return this._useAlphaToCoverage;
  14619. }
  14620. set alphaToCoverage( value ) {
  14621. if ( this._useAlphaToCoverage !== value ) {
  14622. this._useAlphaToCoverage = value;
  14623. this.needsUpdate = true;
  14624. }
  14625. }
  14626. }
  14627. /**
  14628. * Packs a direction vector into a color value.
  14629. *
  14630. * @tsl
  14631. * @function
  14632. * @param {Node<vec3>} node - The direction to pack.
  14633. * @return {Node<vec3>} The color.
  14634. */
  14635. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  14636. /**
  14637. * Unpacks a color value into a direction vector.
  14638. *
  14639. * @tsl
  14640. * @function
  14641. * @param {Node<vec3>} node - The color to unpack.
  14642. * @return {Node<vec3>} The direction.
  14643. */
  14644. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  14645. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  14646. /**
  14647. * Node material version of {@link MeshNormalMaterial}.
  14648. *
  14649. * @augments NodeMaterial
  14650. */
  14651. class MeshNormalNodeMaterial extends NodeMaterial {
  14652. static get type() {
  14653. return 'MeshNormalNodeMaterial';
  14654. }
  14655. /**
  14656. * Constructs a new mesh normal node material.
  14657. *
  14658. * @param {Object} [parameters] - The configuration parameter.
  14659. */
  14660. constructor( parameters ) {
  14661. super();
  14662. /**
  14663. * This flag can be used for type testing.
  14664. *
  14665. * @type {boolean}
  14666. * @readonly
  14667. * @default true
  14668. */
  14669. this.isMeshNormalNodeMaterial = true;
  14670. this.setDefaultValues( _defaultValues$a );
  14671. this.setValues( parameters );
  14672. }
  14673. /**
  14674. * Overwrites the default implementation by computing the diffuse color
  14675. * based on the normal data.
  14676. */
  14677. setupDiffuseColor() {
  14678. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14679. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  14680. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  14681. }
  14682. }
  14683. /**
  14684. * TSL function for creating an equirect uv node.
  14685. *
  14686. * Can be used to compute texture coordinates for projecting an
  14687. * equirectangular texture onto a mesh for using it as the scene's
  14688. * background.
  14689. *
  14690. * ```js
  14691. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  14692. * ```
  14693. *
  14694. * @tsl
  14695. * @function
  14696. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  14697. * @returns {Node<vec2>}
  14698. */
  14699. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  14700. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  14701. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  14702. return vec2( u, v );
  14703. } );
  14704. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  14705. /**
  14706. * This class represents a cube render target. It is a special version
  14707. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  14708. *
  14709. * @augments WebGLCubeRenderTarget
  14710. */
  14711. class CubeRenderTarget extends WebGLCubeRenderTarget {
  14712. /**
  14713. * Constructs a new cube render target.
  14714. *
  14715. * @param {number} [size=1] - The size of the render target.
  14716. * @param {RenderTarget~Options} [options] - The configuration object.
  14717. */
  14718. constructor( size = 1, options = {} ) {
  14719. super( size, options );
  14720. /**
  14721. * This flag can be used for type testing.
  14722. *
  14723. * @type {boolean}
  14724. * @readonly
  14725. * @default true
  14726. */
  14727. this.isCubeRenderTarget = true;
  14728. }
  14729. /**
  14730. * Converts the given equirectangular texture to a cube map.
  14731. *
  14732. * @param {Renderer} renderer - The renderer.
  14733. * @param {Texture} texture - The equirectangular texture.
  14734. * @return {CubeRenderTarget} A reference to this cube render target.
  14735. */
  14736. fromEquirectangularTexture( renderer, texture$1 ) {
  14737. const currentMinFilter = texture$1.minFilter;
  14738. const currentGenerateMipmaps = texture$1.generateMipmaps;
  14739. texture$1.generateMipmaps = true;
  14740. this.texture.type = texture$1.type;
  14741. this.texture.colorSpace = texture$1.colorSpace;
  14742. this.texture.generateMipmaps = texture$1.generateMipmaps;
  14743. this.texture.minFilter = texture$1.minFilter;
  14744. this.texture.magFilter = texture$1.magFilter;
  14745. const geometry = new BoxGeometry( 5, 5, 5 );
  14746. const uvNode = equirectUV( positionWorldDirection );
  14747. const material = new NodeMaterial();
  14748. material.colorNode = texture( texture$1, uvNode, 0 );
  14749. material.side = BackSide;
  14750. material.blending = NoBlending;
  14751. const mesh = new Mesh( geometry, material );
  14752. const scene = new Scene();
  14753. scene.add( mesh );
  14754. // Avoid blurred poles
  14755. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  14756. const camera = new CubeCamera( 1, 10, this );
  14757. const currentMRT = renderer.getMRT();
  14758. renderer.setMRT( null );
  14759. camera.update( renderer, scene );
  14760. renderer.setMRT( currentMRT );
  14761. texture$1.minFilter = currentMinFilter;
  14762. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  14763. mesh.geometry.dispose();
  14764. mesh.material.dispose();
  14765. return this;
  14766. }
  14767. }
  14768. const _cache$1 = new WeakMap();
  14769. /**
  14770. * This node can be used to automatically convert environment maps in the
  14771. * equirectangular format into the cube map format.
  14772. *
  14773. * @augments TempNode
  14774. */
  14775. class CubeMapNode extends TempNode {
  14776. static get type() {
  14777. return 'CubeMapNode';
  14778. }
  14779. /**
  14780. * Constructs a new cube map node.
  14781. *
  14782. * @param {Node} envNode - The node representing the environment map.
  14783. */
  14784. constructor( envNode ) {
  14785. super( 'vec3' );
  14786. /**
  14787. * The node representing the environment map.
  14788. *
  14789. * @type {Node}
  14790. */
  14791. this.envNode = envNode;
  14792. /**
  14793. * A reference to the internal cube texture.
  14794. *
  14795. * @private
  14796. * @type {?CubeTexture}
  14797. * @default null
  14798. */
  14799. this._cubeTexture = null;
  14800. /**
  14801. * A reference to the internal cube texture node.
  14802. *
  14803. * @private
  14804. * @type {CubeTextureNode}
  14805. */
  14806. this._cubeTextureNode = cubeTexture( null );
  14807. const defaultTexture = new CubeTexture();
  14808. defaultTexture.isRenderTargetTexture = true;
  14809. /**
  14810. * A default cube texture that acts as a placeholder.
  14811. * It is used when the conversion from equirectangular to cube
  14812. * map has not finished yet for a given texture.
  14813. *
  14814. * @private
  14815. * @type {CubeTexture}
  14816. */
  14817. this._defaultTexture = defaultTexture;
  14818. /**
  14819. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  14820. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  14821. *
  14822. * @type {string}
  14823. * @default 'render'
  14824. */
  14825. this.updateBeforeType = NodeUpdateType.RENDER;
  14826. }
  14827. updateBefore( frame ) {
  14828. const { renderer, material } = frame;
  14829. const envNode = this.envNode;
  14830. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14831. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14832. if ( texture && texture.isTexture ) {
  14833. const mapping = texture.mapping;
  14834. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  14835. // check for converted cubemap map
  14836. if ( _cache$1.has( texture ) ) {
  14837. const cubeMap = _cache$1.get( texture );
  14838. mapTextureMapping( cubeMap, texture.mapping );
  14839. this._cubeTexture = cubeMap;
  14840. } else {
  14841. // create cube map from equirectangular map
  14842. const image = texture.image;
  14843. if ( isEquirectangularMapReady$1( image ) ) {
  14844. const renderTarget = new CubeRenderTarget( image.height );
  14845. renderTarget.fromEquirectangularTexture( renderer, texture );
  14846. mapTextureMapping( renderTarget.texture, texture.mapping );
  14847. this._cubeTexture = renderTarget.texture;
  14848. _cache$1.set( texture, renderTarget.texture );
  14849. texture.addEventListener( 'dispose', onTextureDispose );
  14850. } else {
  14851. // default cube texture as fallback when equirectangular texture is not yet loaded
  14852. this._cubeTexture = this._defaultTexture;
  14853. }
  14854. }
  14855. //
  14856. this._cubeTextureNode.value = this._cubeTexture;
  14857. } else {
  14858. // envNode already refers to a cube map
  14859. this._cubeTextureNode = this.envNode;
  14860. }
  14861. }
  14862. }
  14863. }
  14864. setup( builder ) {
  14865. this.updateBefore( builder );
  14866. return this._cubeTextureNode;
  14867. }
  14868. }
  14869. /**
  14870. * Returns true if the given equirectangular image has been fully loaded
  14871. * and is ready for further processing.
  14872. *
  14873. * @private
  14874. * @param {Image} image - The equirectangular image to check.
  14875. * @return {boolean} Whether the image is ready or not.
  14876. */
  14877. function isEquirectangularMapReady$1( image ) {
  14878. if ( image === null || image === undefined ) return false;
  14879. return image.height > 0;
  14880. }
  14881. /**
  14882. * This function is executed when `dispose()` is called on the equirectangular
  14883. * texture. In this case, the generated cube map with its render target
  14884. * is deleted as well.
  14885. *
  14886. * @private
  14887. * @param {Object} event - The event object.
  14888. */
  14889. function onTextureDispose( event ) {
  14890. const texture = event.target;
  14891. texture.removeEventListener( 'dispose', onTextureDispose );
  14892. const renderTarget = _cache$1.get( texture );
  14893. if ( renderTarget !== undefined ) {
  14894. _cache$1.delete( texture );
  14895. renderTarget.dispose();
  14896. }
  14897. }
  14898. /**
  14899. * This function makes sure the generated cube map uses the correct
  14900. * texture mapping that corresponds to the equirectangular original.
  14901. *
  14902. * @private
  14903. * @param {Texture} texture - The cube texture.
  14904. * @param {number} mapping - The original texture mapping.
  14905. */
  14906. function mapTextureMapping( texture, mapping ) {
  14907. if ( mapping === EquirectangularReflectionMapping ) {
  14908. texture.mapping = CubeReflectionMapping;
  14909. } else if ( mapping === EquirectangularRefractionMapping ) {
  14910. texture.mapping = CubeRefractionMapping;
  14911. }
  14912. }
  14913. /**
  14914. * TSL function for creating a cube map node.
  14915. *
  14916. * @tsl
  14917. * @function
  14918. * @param {Node} envNode - The node representing the environment map.
  14919. * @returns {CubeMapNode}
  14920. */
  14921. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  14922. /**
  14923. * Represents a basic model for Image-based lighting (IBL). The environment
  14924. * is defined via environment maps in the equirectangular or cube map format.
  14925. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  14926. * or {@link MeshPhongNodeMaterial}.
  14927. *
  14928. * @augments LightingNode
  14929. */
  14930. class BasicEnvironmentNode extends LightingNode {
  14931. static get type() {
  14932. return 'BasicEnvironmentNode';
  14933. }
  14934. /**
  14935. * Constructs a new basic environment node.
  14936. *
  14937. * @param {Node} [envNode=null] - A node representing the environment.
  14938. */
  14939. constructor( envNode = null ) {
  14940. super();
  14941. /**
  14942. * A node representing the environment.
  14943. *
  14944. * @type {Node}
  14945. * @default null
  14946. */
  14947. this.envNode = envNode;
  14948. }
  14949. setup( builder ) {
  14950. // environment property is used in the finish() method of BasicLightingModel
  14951. builder.context.environment = cubeMapNode( this.envNode );
  14952. }
  14953. }
  14954. /**
  14955. * A specific version of {@link IrradianceNode} that is only relevant
  14956. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  14957. * requires a special scaling factor for the light map.
  14958. *
  14959. * @augments LightingNode
  14960. */
  14961. class BasicLightMapNode extends LightingNode {
  14962. static get type() {
  14963. return 'BasicLightMapNode';
  14964. }
  14965. /**
  14966. * Constructs a new basic light map node.
  14967. *
  14968. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  14969. */
  14970. constructor( lightMapNode = null ) {
  14971. super();
  14972. /**
  14973. * The light map node.
  14974. *
  14975. * @type {?Node<vec3>}
  14976. */
  14977. this.lightMapNode = lightMapNode;
  14978. }
  14979. setup( builder ) {
  14980. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  14981. const RECIPROCAL_PI = float( 1 / Math.PI );
  14982. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  14983. }
  14984. }
  14985. /**
  14986. * Abstract class for implementing lighting models. The module defines
  14987. * multiple methods that concrete lighting models can implement. These
  14988. * methods are executed at different points during the light evaluation
  14989. * process.
  14990. */
  14991. class LightingModel {
  14992. /**
  14993. * This method is intended for setting up lighting model and context data
  14994. * which are later used in the evaluation process.
  14995. *
  14996. * @abstract
  14997. * @param {NodeBuilder} builder - The current node builder.
  14998. */
  14999. start( builder ) {
  15000. // lights ( direct )
  15001. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  15002. // indirect
  15003. this.indirect( builder );
  15004. }
  15005. /**
  15006. * This method is intended for executing final tasks like final updates
  15007. * to the outgoing light.
  15008. *
  15009. * @abstract
  15010. * @param {NodeBuilder} builder - The current node builder.
  15011. */
  15012. finish( /*builder*/ ) { }
  15013. /**
  15014. * This method is intended for implementing the direct light term and
  15015. * executed during the build process of directional, point and spot light nodes.
  15016. *
  15017. * @abstract
  15018. * @param {Object} lightData - The light data.
  15019. * @param {NodeBuilder} builder - The current node builder.
  15020. */
  15021. direct( /*lightData, builder*/ ) { }
  15022. /**
  15023. * This method is intended for implementing the direct light term for
  15024. * rect area light nodes.
  15025. *
  15026. * @abstract
  15027. * @param {Object} lightData - The light data.
  15028. * @param {NodeBuilder} builder - The current node builder.
  15029. */
  15030. directRectArea( /*lightData, builder*/ ) {}
  15031. /**
  15032. * This method is intended for implementing the indirect light term.
  15033. *
  15034. * @abstract
  15035. * @param {NodeBuilder} builder - The current node builder.
  15036. */
  15037. indirect( /*builder*/ ) { }
  15038. /**
  15039. * This method is intended for implementing the ambient occlusion term.
  15040. * Unlike other methods, this method must be called manually by the lighting
  15041. * model in its indirect term.
  15042. *
  15043. * @abstract
  15044. * @param {NodeBuilder} builder - The current node builder.
  15045. */
  15046. ambientOcclusion( /*input, stack, builder*/ ) { }
  15047. }
  15048. /**
  15049. * Represents the lighting model for unlit materials. The only light contribution
  15050. * is baked indirect lighting modulated with ambient occlusion and the material's
  15051. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  15052. *
  15053. * @augments LightingModel
  15054. */
  15055. class BasicLightingModel extends LightingModel {
  15056. /**
  15057. * Constructs a new basic lighting model.
  15058. */
  15059. constructor() {
  15060. super();
  15061. }
  15062. /**
  15063. * Implements the baked indirect lighting with its modulation.
  15064. *
  15065. * @param {NodeBuilder} builder - The current node builder.
  15066. */
  15067. indirect( { context } ) {
  15068. const ambientOcclusion = context.ambientOcclusion;
  15069. const reflectedLight = context.reflectedLight;
  15070. const irradianceLightMap = context.irradianceLightMap;
  15071. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  15072. // accumulation (baked indirect lighting only)
  15073. if ( irradianceLightMap ) {
  15074. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  15075. } else {
  15076. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  15077. }
  15078. // modulation
  15079. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15080. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  15081. }
  15082. /**
  15083. * Implements the environment mapping.
  15084. *
  15085. * @param {NodeBuilder} builder - The current node builder.
  15086. */
  15087. finish( builder ) {
  15088. const { material, context } = builder;
  15089. const outgoingLight = context.outgoingLight;
  15090. const envNode = builder.context.environment;
  15091. if ( envNode ) {
  15092. switch ( material.combine ) {
  15093. case MultiplyOperation:
  15094. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  15095. break;
  15096. case MixOperation:
  15097. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  15098. break;
  15099. case AddOperation:
  15100. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  15101. break;
  15102. default:
  15103. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  15104. break;
  15105. }
  15106. }
  15107. }
  15108. }
  15109. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  15110. /**
  15111. * Node material version of {@link MeshBasicMaterial}.
  15112. *
  15113. * @augments NodeMaterial
  15114. */
  15115. class MeshBasicNodeMaterial extends NodeMaterial {
  15116. static get type() {
  15117. return 'MeshBasicNodeMaterial';
  15118. }
  15119. /**
  15120. * Constructs a new mesh basic node material.
  15121. *
  15122. * @param {Object} [parameters] - The configuration parameter.
  15123. */
  15124. constructor( parameters ) {
  15125. super();
  15126. /**
  15127. * This flag can be used for type testing.
  15128. *
  15129. * @type {boolean}
  15130. * @readonly
  15131. * @default true
  15132. */
  15133. this.isMeshBasicNodeMaterial = true;
  15134. /**
  15135. * Although the basic material is by definition unlit, we set
  15136. * this property to `true` since we use a lighting model to compute
  15137. * the outgoing light of the fragment shader.
  15138. *
  15139. * @type {boolean}
  15140. * @default true
  15141. */
  15142. this.lights = true;
  15143. this.setDefaultValues( _defaultValues$9 );
  15144. this.setValues( parameters );
  15145. }
  15146. /**
  15147. * Basic materials are not affected by normal and bump maps so we
  15148. * return by default {@link normalViewGeometry}.
  15149. *
  15150. * @return {Node<vec3>} The normal node.
  15151. */
  15152. setupNormal() {
  15153. return directionToFaceDirection( normalViewGeometry ); // see #28839
  15154. }
  15155. /**
  15156. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15157. * to implement the default environment mapping.
  15158. *
  15159. * @param {NodeBuilder} builder - The current node builder.
  15160. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15161. */
  15162. setupEnvironment( builder ) {
  15163. const envNode = super.setupEnvironment( builder );
  15164. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15165. }
  15166. /**
  15167. * This method must be overwritten since light maps are evaluated
  15168. * with a special scaling factor for basic materials.
  15169. *
  15170. * @param {NodeBuilder} builder - The current node builder.
  15171. * @return {?BasicLightMapNode<vec3>} The light map node.
  15172. */
  15173. setupLightMap( builder ) {
  15174. let node = null;
  15175. if ( builder.material.lightMap ) {
  15176. node = new BasicLightMapNode( materialLightMap );
  15177. }
  15178. return node;
  15179. }
  15180. /**
  15181. * The material overwrites this method because `lights` is set to `true` but
  15182. * we still want to return the diffuse color as the outgoing light.
  15183. *
  15184. * @return {Node<vec3>} The outgoing light node.
  15185. */
  15186. setupOutgoingLight() {
  15187. return diffuseColor.rgb;
  15188. }
  15189. /**
  15190. * Setups the lighting model.
  15191. *
  15192. * @return {BasicLightingModel} The lighting model.
  15193. */
  15194. setupLightingModel() {
  15195. return new BasicLightingModel();
  15196. }
  15197. }
  15198. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  15199. // Original approximation by Christophe Schlick '94
  15200. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  15201. // Optimized variant (presented by Epic at SIGGRAPH '13)
  15202. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  15203. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  15204. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  15205. } ); // validated
  15206. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  15207. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  15208. } ); // validated
  15209. const G_BlinnPhong_Implicit = () => float( 0.25 );
  15210. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  15211. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  15212. } );
  15213. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15214. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15215. const dotNH = normalView.dot( halfDir ).clamp();
  15216. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15217. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  15218. const G = G_BlinnPhong_Implicit();
  15219. const D = D_BlinnPhong( { dotNH } );
  15220. return F.mul( G ).mul( D );
  15221. } );
  15222. /**
  15223. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  15224. *
  15225. * @augments BasicLightingModel
  15226. */
  15227. class PhongLightingModel extends BasicLightingModel {
  15228. /**
  15229. * Constructs a new phong lighting model.
  15230. *
  15231. * @param {boolean} [specular=true] - Whether specular is supported or not.
  15232. */
  15233. constructor( specular = true ) {
  15234. super();
  15235. /**
  15236. * Whether specular is supported or not. Set this to `false` if you are
  15237. * looking for a Lambert-like material meaning a material for non-shiny
  15238. * surfaces, without specular highlights.
  15239. *
  15240. * @type {boolean}
  15241. * @default true
  15242. */
  15243. this.specular = specular;
  15244. }
  15245. /**
  15246. * Implements the direct lighting. The specular portion is optional an can be controlled
  15247. * with the {@link PhongLightingModel#specular} flag.
  15248. *
  15249. * @param {Object} lightData - The light data.
  15250. */
  15251. direct( { lightDirection, lightColor, reflectedLight } ) {
  15252. const dotNL = normalView.dot( lightDirection ).clamp();
  15253. const irradiance = dotNL.mul( lightColor );
  15254. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15255. if ( this.specular === true ) {
  15256. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  15257. }
  15258. }
  15259. /**
  15260. * Implements the indirect lighting.
  15261. *
  15262. * @param {NodeBuilder} builder - The current node builder.
  15263. */
  15264. indirect( builder ) {
  15265. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  15266. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15267. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15268. }
  15269. }
  15270. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  15271. /**
  15272. * Node material version of {@link MeshLambertMaterial}.
  15273. *
  15274. * @augments NodeMaterial
  15275. */
  15276. class MeshLambertNodeMaterial extends NodeMaterial {
  15277. static get type() {
  15278. return 'MeshLambertNodeMaterial';
  15279. }
  15280. /**
  15281. * Constructs a new mesh lambert node material.
  15282. *
  15283. * @param {Object} [parameters] - The configuration parameter.
  15284. */
  15285. constructor( parameters ) {
  15286. super();
  15287. /**
  15288. * This flag can be used for type testing.
  15289. *
  15290. * @type {boolean}
  15291. * @readonly
  15292. * @default true
  15293. */
  15294. this.isMeshLambertNodeMaterial = true;
  15295. /**
  15296. * Set to `true` because lambert materials react on lights.
  15297. *
  15298. * @type {boolean}
  15299. * @default true
  15300. */
  15301. this.lights = true;
  15302. this.setDefaultValues( _defaultValues$8 );
  15303. this.setValues( parameters );
  15304. }
  15305. /**
  15306. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15307. * to implement the default environment mapping.
  15308. *
  15309. * @param {NodeBuilder} builder - The current node builder.
  15310. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15311. */
  15312. setupEnvironment( builder ) {
  15313. const envNode = super.setupEnvironment( builder );
  15314. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15315. }
  15316. /**
  15317. * Setups the lighting model.
  15318. *
  15319. * @return {PhongLightingModel} The lighting model.
  15320. */
  15321. setupLightingModel( /*builder*/ ) {
  15322. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  15323. }
  15324. }
  15325. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  15326. /**
  15327. * Node material version of {@link MeshPhongMaterial}.
  15328. *
  15329. * @augments NodeMaterial
  15330. */
  15331. class MeshPhongNodeMaterial extends NodeMaterial {
  15332. static get type() {
  15333. return 'MeshPhongNodeMaterial';
  15334. }
  15335. /**
  15336. * Constructs a new mesh lambert node material.
  15337. *
  15338. * @param {Object} [parameters] - The configuration parameter.
  15339. */
  15340. constructor( parameters ) {
  15341. super();
  15342. /**
  15343. * This flag can be used for type testing.
  15344. *
  15345. * @type {boolean}
  15346. * @readonly
  15347. * @default true
  15348. */
  15349. this.isMeshPhongNodeMaterial = true;
  15350. /**
  15351. * Set to `true` because phong materials react on lights.
  15352. *
  15353. * @type {boolean}
  15354. * @default true
  15355. */
  15356. this.lights = true;
  15357. /**
  15358. * The shininess of phong materials is by default inferred from the `shininess`
  15359. * property. This node property allows to overwrite the default
  15360. * and define the shininess with a node instead.
  15361. *
  15362. * If you don't want to overwrite the shininess but modify the existing
  15363. * value instead, use {@link materialShininess}.
  15364. *
  15365. * @type {?Node<float>}
  15366. * @default null
  15367. */
  15368. this.shininessNode = null;
  15369. /**
  15370. * The specular color of phong materials is by default inferred from the
  15371. * `specular` property. This node property allows to overwrite the default
  15372. * and define the specular color with a node instead.
  15373. *
  15374. * If you don't want to overwrite the specular color but modify the existing
  15375. * value instead, use {@link materialSpecular}.
  15376. *
  15377. * @type {?Node<vec3>}
  15378. * @default null
  15379. */
  15380. this.specularNode = null;
  15381. this.setDefaultValues( _defaultValues$7 );
  15382. this.setValues( parameters );
  15383. }
  15384. /**
  15385. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15386. * to implement the default environment mapping.
  15387. *
  15388. * @param {NodeBuilder} builder - The current node builder.
  15389. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15390. */
  15391. setupEnvironment( builder ) {
  15392. const envNode = super.setupEnvironment( builder );
  15393. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15394. }
  15395. /**
  15396. * Setups the lighting model.
  15397. *
  15398. * @return {PhongLightingModel} The lighting model.
  15399. */
  15400. setupLightingModel( /*builder*/ ) {
  15401. return new PhongLightingModel();
  15402. }
  15403. /**
  15404. * Setups the phong specific node variables.
  15405. *
  15406. * @param {NodeBuilder} builder - The current node builder.
  15407. */
  15408. setupVariants( /*builder*/ ) {
  15409. // SHININESS
  15410. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15411. shininess.assign( shininessNode );
  15412. // SPECULAR COLOR
  15413. const specularNode = this.specularNode || materialSpecular;
  15414. specularColor.assign( specularNode );
  15415. }
  15416. copy( source ) {
  15417. this.shininessNode = source.shininessNode;
  15418. this.specularNode = source.specularNode;
  15419. return super.copy( source );
  15420. }
  15421. }
  15422. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  15423. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  15424. return float( 0 );
  15425. }
  15426. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  15427. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  15428. return geometryRoughness;
  15429. } );
  15430. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  15431. const { roughness } = inputs;
  15432. const geometryRoughness = getGeometryRoughness();
  15433. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  15434. roughnessFactor = roughnessFactor.add( geometryRoughness );
  15435. roughnessFactor = roughnessFactor.min( 1.0 );
  15436. return roughnessFactor;
  15437. } );
  15438. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  15439. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  15440. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  15441. const a2 = alpha.pow2();
  15442. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  15443. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  15444. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  15445. } ).setLayout( {
  15446. name: 'V_GGX_SmithCorrelated',
  15447. type: 'float',
  15448. inputs: [
  15449. { name: 'alpha', type: 'float' },
  15450. { name: 'dotNL', type: 'float' },
  15451. { name: 'dotNV', type: 'float' }
  15452. ]
  15453. } ); // validated
  15454. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15455. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  15456. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  15457. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  15458. const v = div( 0.5, gv.add( gl ) );
  15459. return v.saturate();
  15460. } ).setLayout( {
  15461. name: 'V_GGX_SmithCorrelated_Anisotropic',
  15462. type: 'float',
  15463. inputs: [
  15464. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15465. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15466. { name: 'dotTV', type: 'float', qualifier: 'in' },
  15467. { name: 'dotBV', type: 'float', qualifier: 'in' },
  15468. { name: 'dotTL', type: 'float', qualifier: 'in' },
  15469. { name: 'dotBL', type: 'float', qualifier: 'in' },
  15470. { name: 'dotNV', type: 'float', qualifier: 'in' },
  15471. { name: 'dotNL', type: 'float', qualifier: 'in' }
  15472. ]
  15473. } );
  15474. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  15475. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  15476. // alpha is "roughness squared" in Disney’s reparameterization
  15477. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  15478. const a2 = alpha.pow2();
  15479. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  15480. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  15481. } ).setLayout( {
  15482. name: 'D_GGX',
  15483. type: 'float',
  15484. inputs: [
  15485. { name: 'alpha', type: 'float' },
  15486. { name: 'dotNH', type: 'float' }
  15487. ]
  15488. } ); // validated
  15489. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  15490. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15491. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  15492. const a2 = alphaT.mul( alphaB );
  15493. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  15494. const v2 = v.dot( v );
  15495. const w2 = a2.div( v2 );
  15496. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  15497. } ).setLayout( {
  15498. name: 'D_GGX_Anisotropic',
  15499. type: 'float',
  15500. inputs: [
  15501. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15502. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15503. { name: 'dotNH', type: 'float', qualifier: 'in' },
  15504. { name: 'dotTH', type: 'float', qualifier: 'in' },
  15505. { name: 'dotBH', type: 'float', qualifier: 'in' }
  15506. ]
  15507. } );
  15508. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  15509. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  15510. const alpha = roughness.pow2(); // UE4's roughness
  15511. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15512. const dotNL = normalView$1.dot( lightDirection ).clamp();
  15513. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15514. const dotNH = normalView$1.dot( halfDir ).clamp();
  15515. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15516. let F = F_Schlick( { f0, f90, dotVH } );
  15517. let V, D;
  15518. if ( defined( USE_IRIDESCENCE ) ) {
  15519. F = iridescence.mix( F, f );
  15520. }
  15521. if ( defined( USE_ANISOTROPY ) ) {
  15522. const dotTL = anisotropyT.dot( lightDirection );
  15523. const dotTV = anisotropyT.dot( positionViewDirection );
  15524. const dotTH = anisotropyT.dot( halfDir );
  15525. const dotBL = anisotropyB.dot( lightDirection );
  15526. const dotBV = anisotropyB.dot( positionViewDirection );
  15527. const dotBH = anisotropyB.dot( halfDir );
  15528. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  15529. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  15530. } else {
  15531. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  15532. D = D_GGX( { alpha, dotNH } );
  15533. }
  15534. return F.mul( V ).mul( D );
  15535. } ); // validated
  15536. // Analytical approximation of the DFG LUT, one half of the
  15537. // split-sum approximation used in indirect specular lighting.
  15538. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  15539. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  15540. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  15541. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  15542. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  15543. const r = roughness.mul( c0 ).add( c1 );
  15544. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  15545. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  15546. return fab;
  15547. } ).setLayout( {
  15548. name: 'DFGApprox',
  15549. type: 'vec2',
  15550. inputs: [
  15551. { name: 'roughness', type: 'float' },
  15552. { name: 'dotNV', type: 'vec3' }
  15553. ]
  15554. } );
  15555. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  15556. const { dotNV, specularColor, specularF90, roughness } = inputs;
  15557. const fab = DFGApprox( { dotNV, roughness } );
  15558. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  15559. } );
  15560. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  15561. const x = dotVH.oneMinus().saturate();
  15562. const x2 = x.mul( x );
  15563. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  15564. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  15565. } ).setLayout( {
  15566. name: 'Schlick_to_F0',
  15567. type: 'vec3',
  15568. inputs: [
  15569. { name: 'f', type: 'vec3' },
  15570. { name: 'f90', type: 'float' },
  15571. { name: 'dotVH', type: 'float' }
  15572. ]
  15573. } );
  15574. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  15575. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  15576. const alpha = roughness.pow2();
  15577. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  15578. const invAlpha = float( 1.0 ).div( alpha );
  15579. const cos2h = dotNH.pow2();
  15580. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  15581. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  15582. } ).setLayout( {
  15583. name: 'D_Charlie',
  15584. type: 'float',
  15585. inputs: [
  15586. { name: 'roughness', type: 'float' },
  15587. { name: 'dotNH', type: 'float' }
  15588. ]
  15589. } );
  15590. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  15591. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  15592. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  15593. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  15594. } ).setLayout( {
  15595. name: 'V_Neubelt',
  15596. type: 'float',
  15597. inputs: [
  15598. { name: 'dotNV', type: 'float' },
  15599. { name: 'dotNL', type: 'float' }
  15600. ]
  15601. } );
  15602. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15603. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15604. const dotNL = normalView.dot( lightDirection ).clamp();
  15605. const dotNV = normalView.dot( positionViewDirection ).clamp();
  15606. const dotNH = normalView.dot( halfDir ).clamp();
  15607. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  15608. const V = V_Neubelt( { dotNV, dotNL } );
  15609. return sheen.mul( D ).mul( V );
  15610. } );
  15611. // Rect Area Light
  15612. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  15613. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  15614. // code: https://github.com/selfshadow/ltc_code/
  15615. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  15616. const LUT_SIZE = 64.0;
  15617. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  15618. const LUT_BIAS = 0.5 / LUT_SIZE;
  15619. const dotNV = N.dot( V ).saturate();
  15620. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  15621. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  15622. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  15623. return uv;
  15624. } ).setLayout( {
  15625. name: 'LTC_Uv',
  15626. type: 'vec2',
  15627. inputs: [
  15628. { name: 'N', type: 'vec3' },
  15629. { name: 'V', type: 'vec3' },
  15630. { name: 'roughness', type: 'float' }
  15631. ]
  15632. } );
  15633. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  15634. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  15635. // An approximation of the form factor of a horizon-clipped rectangle.
  15636. const l = f.length();
  15637. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  15638. } ).setLayout( {
  15639. name: 'LTC_ClippedSphereFormFactor',
  15640. type: 'float',
  15641. inputs: [
  15642. { name: 'f', type: 'vec3' }
  15643. ]
  15644. } );
  15645. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  15646. const x = v1.dot( v2 );
  15647. const y = x.abs().toVar();
  15648. // rational polynomial approximation to theta / sin( theta ) / 2PI
  15649. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  15650. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  15651. const v = a.div( b );
  15652. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  15653. return v1.cross( v2 ).mul( theta_sintheta );
  15654. } ).setLayout( {
  15655. name: 'LTC_EdgeVectorFormFactor',
  15656. type: 'vec3',
  15657. inputs: [
  15658. { name: 'v1', type: 'vec3' },
  15659. { name: 'v2', type: 'vec3' }
  15660. ]
  15661. } );
  15662. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  15663. // bail if point is on back side of plane of light
  15664. // assumes ccw winding order of light vertices
  15665. const v1 = p1.sub( p0 ).toVar();
  15666. const v2 = p3.sub( p0 ).toVar();
  15667. const lightNormal = v1.cross( v2 );
  15668. const result = vec3().toVar();
  15669. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15670. // construct orthonormal basis around N
  15671. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  15672. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  15673. // compute transform
  15674. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  15675. // transform rect
  15676. // & project rect onto sphere
  15677. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  15678. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  15679. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  15680. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  15681. // calculate vector form factor
  15682. const vectorFormFactor = vec3( 0 ).toVar();
  15683. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15684. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15685. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15686. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15687. // adjust for horizon clipping
  15688. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  15689. } );
  15690. return result;
  15691. } ).setLayout( {
  15692. name: 'LTC_Evaluate',
  15693. type: 'vec3',
  15694. inputs: [
  15695. { name: 'N', type: 'vec3' },
  15696. { name: 'V', type: 'vec3' },
  15697. { name: 'P', type: 'vec3' },
  15698. { name: 'mInv', type: 'mat3' },
  15699. { name: 'p0', type: 'vec3' },
  15700. { name: 'p1', type: 'vec3' },
  15701. { name: 'p2', type: 'vec3' },
  15702. { name: 'p3', type: 'vec3' }
  15703. ]
  15704. } );
  15705. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  15706. // bail if point is on back side of plane of light
  15707. // assumes ccw winding order of light vertices
  15708. const v1 = p1.sub( p0 ).toVar();
  15709. const v2 = p3.sub( p0 ).toVar();
  15710. const lightNormal = v1.cross( v2 );
  15711. const result = vec3().toVar();
  15712. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15713. // transform rect
  15714. // & project rect onto sphere
  15715. const coords0 = p0.sub( P ).normalize().toVar();
  15716. const coords1 = p1.sub( P ).normalize().toVar();
  15717. const coords2 = p2.sub( P ).normalize().toVar();
  15718. const coords3 = p3.sub( P ).normalize().toVar();
  15719. // calculate vector form factor
  15720. const vectorFormFactor = vec3( 0 ).toVar();
  15721. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15722. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15723. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15724. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15725. // adjust for horizon clipping
  15726. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  15727. } );
  15728. return result;
  15729. } ).setLayout( {
  15730. name: 'LTC_Evaluate',
  15731. type: 'vec3',
  15732. inputs: [
  15733. { name: 'P', type: 'vec3' },
  15734. { name: 'p0', type: 'vec3' },
  15735. { name: 'p1', type: 'vec3' },
  15736. { name: 'p2', type: 'vec3' },
  15737. { name: 'p3', type: 'vec3' }
  15738. ]
  15739. } );
  15740. // Mipped Bicubic Texture Filtering by N8
  15741. // https://www.shadertoy.com/view/Dl2SDW
  15742. const bC = 1.0 / 6.0;
  15743. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  15744. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  15745. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  15746. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  15747. const g0 = ( a ) => w0( a ).add( w1( a ) );
  15748. const g1 = ( a ) => w2( a ).add( w3( a ) );
  15749. // h0 and h1 are the two offset functions
  15750. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  15751. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  15752. const bicubic = ( textureNode, texelSize, lod ) => {
  15753. const uv = textureNode.uvNode;
  15754. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  15755. const iuv = floor( uvScaled );
  15756. const fuv = fract( uvScaled );
  15757. const g0x = g0( fuv.x );
  15758. const g1x = g1( fuv.x );
  15759. const h0x = h0( fuv.x );
  15760. const h1x = h1( fuv.x );
  15761. const h0y = h0( fuv.y );
  15762. const h1y = h1( fuv.y );
  15763. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  15764. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  15765. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  15766. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  15767. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  15768. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  15769. return a.add( b );
  15770. };
  15771. /**
  15772. * Applies mipped bicubic texture filtering to the given texture node.
  15773. *
  15774. * @tsl
  15775. * @function
  15776. * @param {TextureNode} textureNode - The texture node that should be filtered.
  15777. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  15778. * @return {Node} The filtered texture sample.
  15779. */
  15780. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  15781. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  15782. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  15783. const fLodSizeInv = div( 1.0, fLodSize );
  15784. const cLodSizeInv = div( 1.0, cLodSize );
  15785. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  15786. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  15787. return fract( lodNode ).mix( fSample, cSample );
  15788. } );
  15789. /**
  15790. * Applies mipped bicubic texture filtering to the given texture node.
  15791. *
  15792. * @tsl
  15793. * @function
  15794. * @param {TextureNode} textureNode - The texture node that should be filtered.
  15795. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  15796. * @return {Node} The filtered texture sample.
  15797. */
  15798. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  15799. const lod = strength.mul( maxMipLevel( textureNode ) );
  15800. return textureBicubicLevel( textureNode, lod );
  15801. } );
  15802. //
  15803. // Transmission
  15804. //
  15805. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  15806. // Direction of refracted light.
  15807. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  15808. // Compute rotation-independent scaling of the model matrix.
  15809. const modelScale = vec3(
  15810. length( modelMatrix[ 0 ].xyz ),
  15811. length( modelMatrix[ 1 ].xyz ),
  15812. length( modelMatrix[ 2 ].xyz )
  15813. );
  15814. // The thickness is specified in local space.
  15815. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  15816. } ).setLayout( {
  15817. name: 'getVolumeTransmissionRay',
  15818. type: 'vec3',
  15819. inputs: [
  15820. { name: 'n', type: 'vec3' },
  15821. { name: 'v', type: 'vec3' },
  15822. { name: 'thickness', type: 'float' },
  15823. { name: 'ior', type: 'float' },
  15824. { name: 'modelMatrix', type: 'mat4' }
  15825. ]
  15826. } );
  15827. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  15828. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  15829. // an IOR of 1.5 results in the default amount of microfacet refraction.
  15830. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  15831. } ).setLayout( {
  15832. name: 'applyIorToRoughness',
  15833. type: 'float',
  15834. inputs: [
  15835. { name: 'roughness', type: 'float' },
  15836. { name: 'ior', type: 'float' }
  15837. ]
  15838. } );
  15839. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  15840. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  15841. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  15842. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  15843. const transmissionSample = vTexture.sample( fragCoord );
  15844. //const transmissionSample = viewportMipTexture( fragCoord );
  15845. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  15846. return textureBicubicLevel( transmissionSample, lod );
  15847. } );
  15848. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  15849. If( attenuationDistance.notEqual( 0 ), () => {
  15850. // Compute light attenuation using Beer's law.
  15851. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  15852. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  15853. return transmittance;
  15854. } );
  15855. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  15856. return vec3( 1.0 );
  15857. } ).setLayout( {
  15858. name: 'volumeAttenuation',
  15859. type: 'vec3',
  15860. inputs: [
  15861. { name: 'transmissionDistance', type: 'float' },
  15862. { name: 'attenuationColor', type: 'vec3' },
  15863. { name: 'attenuationDistance', type: 'float' }
  15864. ]
  15865. } );
  15866. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  15867. let transmittedLight, transmittance;
  15868. if ( dispersion ) {
  15869. transmittedLight = vec4().toVar();
  15870. transmittance = vec3().toVar();
  15871. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  15872. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  15873. Loop( { start: 0, end: 3 }, ( { i } ) => {
  15874. const ior = iors.element( i );
  15875. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  15876. const refractedRayExit = position.add( transmissionRay );
  15877. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  15878. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  15879. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  15880. refractionCoords.addAssign( 1.0 );
  15881. refractionCoords.divAssign( 2.0 );
  15882. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  15883. // Sample framebuffer to get pixel the refracted ray hits.
  15884. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  15885. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  15886. transmittedLight.a.addAssign( transmissionSample.a );
  15887. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  15888. } );
  15889. transmittedLight.a.divAssign( 3.0 );
  15890. } else {
  15891. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  15892. const refractedRayExit = position.add( transmissionRay );
  15893. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  15894. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  15895. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  15896. refractionCoords.addAssign( 1.0 );
  15897. refractionCoords.divAssign( 2.0 );
  15898. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  15899. // Sample framebuffer to get pixel the refracted ray hits.
  15900. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  15901. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  15902. }
  15903. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  15904. const dotNV = n.dot( v ).clamp();
  15905. // Get the specular component.
  15906. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  15907. dotNV,
  15908. specularColor,
  15909. specularF90,
  15910. roughness
  15911. } ) );
  15912. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  15913. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  15914. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  15915. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  15916. } );
  15917. //
  15918. // Iridescence
  15919. //
  15920. // XYZ to linear-sRGB color space
  15921. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  15922. 3.2404542, -0.969266, 0.0556434,
  15923. -1.5371385, 1.8760108, -0.2040259,
  15924. -0.4985314, 0.0415560, 1.0572252
  15925. );
  15926. // Assume air interface for top
  15927. // Note: We don't handle the case fresnel0 == 1
  15928. const Fresnel0ToIor = ( fresnel0 ) => {
  15929. const sqrtF0 = fresnel0.sqrt();
  15930. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  15931. };
  15932. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  15933. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  15934. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  15935. };
  15936. // Fresnel equations for dielectric/dielectric interfaces.
  15937. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  15938. // Evaluation XYZ sensitivity curves in Fourier space
  15939. const evalSensitivity = ( OPD, shift ) => {
  15940. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  15941. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  15942. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  15943. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  15944. 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() );
  15945. 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() );
  15946. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  15947. const rgb = XYZ_TO_REC709.mul( xyz );
  15948. return rgb;
  15949. };
  15950. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  15951. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  15952. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  15953. // Evaluate the cosTheta on the base layer (Snell law)
  15954. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  15955. // Handle TIR:
  15956. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  15957. If( cosTheta2Sq.lessThan( 0 ), () => {
  15958. return vec3( 1.0 );
  15959. } );
  15960. const cosTheta2 = cosTheta2Sq.sqrt();
  15961. // First interface
  15962. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  15963. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  15964. //const R21 = R12;
  15965. const T121 = R12.oneMinus();
  15966. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  15967. const phi21 = float( Math.PI ).sub( phi12 );
  15968. // Second interface
  15969. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  15970. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  15971. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  15972. const phi23 = vec3(
  15973. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  15974. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  15975. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  15976. );
  15977. // Phase shift
  15978. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  15979. const phi = vec3( phi21 ).add( phi23 );
  15980. // Compound terms
  15981. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  15982. const r123 = R123.sqrt();
  15983. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  15984. // Reflectance term for m = 0 (DC term amplitude)
  15985. const C0 = R12.add( Rs );
  15986. const I = C0.toVar();
  15987. // Reflectance term for m > 0 (pairs of diracs)
  15988. const Cm = Rs.sub( T121 ).toVar();
  15989. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  15990. Cm.mulAssign( r123 );
  15991. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  15992. I.addAssign( Cm.mul( Sm ) );
  15993. } );
  15994. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  15995. return I.max( vec3( 0.0 ) );
  15996. } ).setLayout( {
  15997. name: 'evalIridescence',
  15998. type: 'vec3',
  15999. inputs: [
  16000. { name: 'outsideIOR', type: 'float' },
  16001. { name: 'eta2', type: 'float' },
  16002. { name: 'cosTheta1', type: 'float' },
  16003. { name: 'thinFilmThickness', type: 'float' },
  16004. { name: 'baseF0', type: 'vec3' }
  16005. ]
  16006. } );
  16007. //
  16008. // Sheen
  16009. //
  16010. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  16011. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  16012. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  16013. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  16014. const dotNV = normal.dot( viewDir ).saturate();
  16015. const r2 = roughness.pow2();
  16016. const a = select(
  16017. roughness.lessThan( 0.25 ),
  16018. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  16019. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  16020. );
  16021. const b = select(
  16022. roughness.lessThan( 0.25 ),
  16023. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  16024. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  16025. );
  16026. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  16027. return DG.mul( 1.0 / Math.PI ).saturate();
  16028. } );
  16029. const clearcoatF0 = vec3( 0.04 );
  16030. const clearcoatF90 = float( 1 );
  16031. /**
  16032. * Represents the lighting model for a PBR material.
  16033. *
  16034. * @augments LightingModel
  16035. */
  16036. class PhysicalLightingModel extends LightingModel {
  16037. /**
  16038. * Constructs a new physical lighting model.
  16039. *
  16040. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  16041. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  16042. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  16043. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  16044. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  16045. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  16046. */
  16047. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  16048. super();
  16049. /**
  16050. * Whether clearcoat is supported or not.
  16051. *
  16052. * @type {boolean}
  16053. * @default false
  16054. */
  16055. this.clearcoat = clearcoat;
  16056. /**
  16057. * Whether sheen is supported or not.
  16058. *
  16059. * @type {boolean}
  16060. * @default false
  16061. */
  16062. this.sheen = sheen;
  16063. /**
  16064. * Whether iridescence is supported or not.
  16065. *
  16066. * @type {boolean}
  16067. * @default false
  16068. */
  16069. this.iridescence = iridescence;
  16070. /**
  16071. * Whether anisotropy is supported or not.
  16072. *
  16073. * @type {boolean}
  16074. * @default false
  16075. */
  16076. this.anisotropy = anisotropy;
  16077. /**
  16078. * Whether transmission is supported or not.
  16079. *
  16080. * @type {boolean}
  16081. * @default false
  16082. */
  16083. this.transmission = transmission;
  16084. /**
  16085. * Whether dispersion is supported or not.
  16086. *
  16087. * @type {boolean}
  16088. * @default false
  16089. */
  16090. this.dispersion = dispersion;
  16091. /**
  16092. * The clear coat radiance.
  16093. *
  16094. * @type {?Node}
  16095. * @default null
  16096. */
  16097. this.clearcoatRadiance = null;
  16098. /**
  16099. * The clear coat specular direct.
  16100. *
  16101. * @type {?Node}
  16102. * @default null
  16103. */
  16104. this.clearcoatSpecularDirect = null;
  16105. /**
  16106. * The clear coat specular indirect.
  16107. *
  16108. * @type {?Node}
  16109. * @default null
  16110. */
  16111. this.clearcoatSpecularIndirect = null;
  16112. /**
  16113. * The sheen specular direct.
  16114. *
  16115. * @type {?Node}
  16116. * @default null
  16117. */
  16118. this.sheenSpecularDirect = null;
  16119. /**
  16120. * The sheen specular indirect.
  16121. *
  16122. * @type {?Node}
  16123. * @default null
  16124. */
  16125. this.sheenSpecularIndirect = null;
  16126. /**
  16127. * The iridescence Fresnel.
  16128. *
  16129. * @type {?Node}
  16130. * @default null
  16131. */
  16132. this.iridescenceFresnel = null;
  16133. /**
  16134. * The iridescence F0.
  16135. *
  16136. * @type {?Node}
  16137. * @default null
  16138. */
  16139. this.iridescenceF0 = null;
  16140. }
  16141. /**
  16142. * Depending on what features are requested, the method prepares certain node variables
  16143. * which are later used for lighting computations.
  16144. *
  16145. * @param {NodeBuilder} builder - The current node builder.
  16146. */
  16147. start( builder ) {
  16148. if ( this.clearcoat === true ) {
  16149. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  16150. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  16151. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  16152. }
  16153. if ( this.sheen === true ) {
  16154. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  16155. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  16156. }
  16157. if ( this.iridescence === true ) {
  16158. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  16159. this.iridescenceFresnel = evalIridescence( {
  16160. outsideIOR: float( 1.0 ),
  16161. eta2: iridescenceIOR,
  16162. cosTheta1: dotNVi,
  16163. thinFilmThickness: iridescenceThickness,
  16164. baseF0: specularColor
  16165. } );
  16166. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  16167. }
  16168. if ( this.transmission === true ) {
  16169. const position = positionWorld;
  16170. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  16171. const n = normalWorld;
  16172. const context = builder.context;
  16173. context.backdrop = getIBLVolumeRefraction(
  16174. n,
  16175. v,
  16176. roughness,
  16177. diffuseColor,
  16178. specularColor,
  16179. specularF90, // specularF90
  16180. position, // positionWorld
  16181. modelWorldMatrix, // modelMatrix
  16182. cameraViewMatrix, // viewMatrix
  16183. cameraProjectionMatrix, // projMatrix
  16184. ior,
  16185. thickness,
  16186. attenuationColor,
  16187. attenuationDistance,
  16188. this.dispersion ? dispersion : null
  16189. );
  16190. context.backdropAlpha = transmission;
  16191. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  16192. }
  16193. super.start( builder );
  16194. }
  16195. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  16196. // Approximates multi-scattering in order to preserve energy.
  16197. // http://www.jcgt.org/published/0008/01/03/
  16198. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  16199. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16200. const fab = DFGApprox( { roughness, dotNV } );
  16201. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  16202. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16203. const Ess = fab.x.add( fab.y );
  16204. const Ems = Ess.oneMinus();
  16205. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  16206. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  16207. singleScatter.addAssign( FssEss );
  16208. multiScatter.addAssign( Fms.mul( Ems ) );
  16209. }
  16210. /**
  16211. * Implements the direct light.
  16212. *
  16213. * @param {Object} lightData - The light data.
  16214. * @param {NodeBuilder} builder - The current node builder.
  16215. */
  16216. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  16217. const dotNL = normalView.dot( lightDirection ).clamp();
  16218. const irradiance = dotNL.mul( lightColor );
  16219. if ( this.sheen === true ) {
  16220. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  16221. }
  16222. if ( this.clearcoat === true ) {
  16223. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  16224. const ccIrradiance = dotNLcc.mul( lightColor );
  16225. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  16226. }
  16227. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16228. 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 } ) ) );
  16229. }
  16230. /**
  16231. * This method is intended for implementing the direct light term for
  16232. * rect area light nodes.
  16233. *
  16234. * @param {Object} input - The input data.
  16235. * @param {NodeBuilder} builder - The current node builder.
  16236. */
  16237. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  16238. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  16239. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  16240. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  16241. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  16242. const N = normalView;
  16243. const V = positionViewDirection;
  16244. const P = positionView.toVar();
  16245. const uv = LTC_Uv( { N, V, roughness } );
  16246. const t1 = ltc_1.sample( uv ).toVar();
  16247. const t2 = ltc_2.sample( uv ).toVar();
  16248. const mInv = mat3(
  16249. vec3( t1.x, 0, t1.y ),
  16250. vec3( 0, 1, 0 ),
  16251. vec3( t1.z, 0, t1.w )
  16252. ).toVar();
  16253. // LTC Fresnel Approximation by Stephen Hill
  16254. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  16255. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  16256. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  16257. 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 } ) ) );
  16258. }
  16259. /**
  16260. * Implements the indirect lighting.
  16261. *
  16262. * @param {NodeBuilder} builder - The current node builder.
  16263. */
  16264. indirect( builder ) {
  16265. this.indirectDiffuse( builder );
  16266. this.indirectSpecular( builder );
  16267. this.ambientOcclusion( builder );
  16268. }
  16269. /**
  16270. * Implements the indirect diffuse term.
  16271. *
  16272. * @param {NodeBuilder} builder - The current node builder.
  16273. */
  16274. indirectDiffuse( builder ) {
  16275. const { irradiance, reflectedLight } = builder.context;
  16276. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16277. }
  16278. /**
  16279. * Implements the indirect specular term.
  16280. *
  16281. * @param {NodeBuilder} builder - The current node builder.
  16282. */
  16283. indirectSpecular( builder ) {
  16284. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  16285. if ( this.sheen === true ) {
  16286. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  16287. sheen,
  16288. IBLSheenBRDF( {
  16289. normal: normalView,
  16290. viewDir: positionViewDirection,
  16291. roughness: sheenRoughness
  16292. } )
  16293. ) );
  16294. }
  16295. if ( this.clearcoat === true ) {
  16296. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16297. const clearcoatEnv = EnvironmentBRDF( {
  16298. dotNV: dotNVcc,
  16299. specularColor: clearcoatF0,
  16300. specularF90: clearcoatF90,
  16301. roughness: clearcoatRoughness
  16302. } );
  16303. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  16304. }
  16305. // Both indirect specular and indirect diffuse light accumulate here
  16306. const singleScattering = vec3().toVar( 'singleScattering' );
  16307. const multiScattering = vec3().toVar( 'multiScattering' );
  16308. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  16309. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  16310. const totalScattering = singleScattering.add( multiScattering );
  16311. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  16312. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  16313. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  16314. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  16315. }
  16316. /**
  16317. * Implements the ambient occlusion term.
  16318. *
  16319. * @param {NodeBuilder} builder - The current node builder.
  16320. */
  16321. ambientOcclusion( builder ) {
  16322. const { ambientOcclusion, reflectedLight } = builder.context;
  16323. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16324. const aoNV = dotNV.add( ambientOcclusion );
  16325. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  16326. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  16327. if ( this.clearcoat === true ) {
  16328. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  16329. }
  16330. if ( this.sheen === true ) {
  16331. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  16332. }
  16333. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16334. reflectedLight.indirectSpecular.mulAssign( aoNode );
  16335. }
  16336. /**
  16337. * Used for final lighting accumulations depending on the requested features.
  16338. *
  16339. * @param {NodeBuilder} builder - The current node builder.
  16340. */
  16341. finish( { context } ) {
  16342. const { outgoingLight } = context;
  16343. if ( this.clearcoat === true ) {
  16344. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16345. const Fcc = F_Schlick( {
  16346. dotVH: dotNVcc,
  16347. f0: clearcoatF0,
  16348. f90: clearcoatF90
  16349. } );
  16350. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  16351. outgoingLight.assign( clearcoatLight );
  16352. }
  16353. if ( this.sheen === true ) {
  16354. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  16355. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  16356. outgoingLight.assign( sheenLight );
  16357. }
  16358. }
  16359. }
  16360. // These defines must match with PMREMGenerator
  16361. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  16362. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  16363. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  16364. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  16365. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  16366. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  16367. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  16368. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  16369. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  16370. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  16371. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  16372. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  16373. // These shader functions convert between the UV coordinates of a single face of
  16374. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  16375. // sampling a textureCube (not generally normalized ).
  16376. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  16377. const absDirection = vec3( abs( direction ) ).toVar();
  16378. const face = float( -1 ).toVar();
  16379. If( absDirection.x.greaterThan( absDirection.z ), () => {
  16380. If( absDirection.x.greaterThan( absDirection.y ), () => {
  16381. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  16382. } ).Else( () => {
  16383. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  16384. } );
  16385. } ).Else( () => {
  16386. If( absDirection.z.greaterThan( absDirection.y ), () => {
  16387. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  16388. } ).Else( () => {
  16389. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  16390. } );
  16391. } );
  16392. return face;
  16393. } ).setLayout( {
  16394. name: 'getFace',
  16395. type: 'float',
  16396. inputs: [
  16397. { name: 'direction', type: 'vec3' }
  16398. ]
  16399. } );
  16400. // RH coordinate system; PMREM face-indexing convention
  16401. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  16402. const uv = vec2().toVar();
  16403. If( face.equal( 0.0 ), () => {
  16404. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  16405. } ).ElseIf( face.equal( 1.0 ), () => {
  16406. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  16407. } ).ElseIf( face.equal( 2.0 ), () => {
  16408. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  16409. } ).ElseIf( face.equal( 3.0 ), () => {
  16410. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  16411. } ).ElseIf( face.equal( 4.0 ), () => {
  16412. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  16413. } ).Else( () => {
  16414. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  16415. } );
  16416. return mul( 0.5, uv.add( 1.0 ) );
  16417. } ).setLayout( {
  16418. name: 'getUV',
  16419. type: 'vec2',
  16420. inputs: [
  16421. { name: 'direction', type: 'vec3' },
  16422. { name: 'face', type: 'float' }
  16423. ]
  16424. } );
  16425. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  16426. const mip = float( 0.0 ).toVar();
  16427. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  16428. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  16429. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  16430. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  16431. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  16432. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  16433. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  16434. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  16435. } ).Else( () => {
  16436. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  16437. } );
  16438. return mip;
  16439. } ).setLayout( {
  16440. name: 'roughnessToMip',
  16441. type: 'float',
  16442. inputs: [
  16443. { name: 'roughness', type: 'float' }
  16444. ]
  16445. } );
  16446. // RH coordinate system; PMREM face-indexing convention
  16447. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  16448. const uv = uv_immutable.toVar();
  16449. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  16450. const direction = vec3( uv, 1.0 ).toVar();
  16451. If( face.equal( 0.0 ), () => {
  16452. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  16453. } ).ElseIf( face.equal( 1.0 ), () => {
  16454. direction.assign( direction.xzy );
  16455. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  16456. } ).ElseIf( face.equal( 2.0 ), () => {
  16457. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  16458. } ).ElseIf( face.equal( 3.0 ), () => {
  16459. direction.assign( direction.zyx );
  16460. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  16461. } ).ElseIf( face.equal( 4.0 ), () => {
  16462. direction.assign( direction.xzy );
  16463. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  16464. } ).ElseIf( face.equal( 5.0 ), () => {
  16465. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  16466. } );
  16467. return direction;
  16468. } ).setLayout( {
  16469. name: 'getDirection',
  16470. type: 'vec3',
  16471. inputs: [
  16472. { name: 'uv', type: 'vec2' },
  16473. { name: 'face', type: 'float' }
  16474. ]
  16475. } );
  16476. //
  16477. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16478. const roughness = float( roughness_immutable );
  16479. const sampleDir = vec3( sampleDir_immutable );
  16480. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  16481. const mipF = fract( mip );
  16482. const mipInt = floor( mip );
  16483. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16484. If( mipF.notEqual( 0.0 ), () => {
  16485. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16486. color0.assign( mix( color0, color1, mipF ) );
  16487. } );
  16488. return color0;
  16489. } );
  16490. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16491. const mipInt = float( mipInt_immutable ).toVar();
  16492. const direction = vec3( direction_immutable );
  16493. const face = float( getFace( direction ) ).toVar();
  16494. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  16495. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  16496. const faceSize = float( exp2( mipInt ) ).toVar();
  16497. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  16498. If( face.greaterThan( 2.0 ), () => {
  16499. uv.y.addAssign( faceSize );
  16500. face.subAssign( 3.0 );
  16501. } );
  16502. uv.x.addAssign( face.mul( faceSize ) );
  16503. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  16504. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  16505. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  16506. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  16507. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  16508. } );
  16509. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16510. const cosTheta = cos( theta );
  16511. // Rodrigues' axis-angle rotation
  16512. const sampleDirection = outputDirection.mul( cosTheta )
  16513. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  16514. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  16515. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  16516. } );
  16517. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16518. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  16519. If( axis.equal( vec3( 0.0 ) ), () => {
  16520. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  16521. } );
  16522. axis.assign( normalize( axis ) );
  16523. const gl_FragColor = vec3().toVar();
  16524. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  16525. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  16526. If( i.greaterThanEqual( samples ), () => {
  16527. Break();
  16528. } );
  16529. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  16530. 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 } ) ) );
  16531. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  16532. } );
  16533. return vec4( gl_FragColor, 1 );
  16534. } );
  16535. const LOD_MIN = 4;
  16536. // The standard deviations (radians) associated with the extra mips. These are
  16537. // chosen to approximate a Trowbridge-Reitz distribution function times the
  16538. // geometric shadowing function. These sigma values squared must match the
  16539. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  16540. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  16541. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  16542. // samples and exit early, but not recompile the shader.
  16543. const MAX_SAMPLES = 20;
  16544. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  16545. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  16546. const _clearColor$2 = /*@__PURE__*/ new Color();
  16547. let _oldTarget = null;
  16548. let _oldActiveCubeFace = 0;
  16549. let _oldActiveMipmapLevel = 0;
  16550. // Golden Ratio
  16551. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  16552. const INV_PHI = 1 / PHI;
  16553. // Vertices of a dodecahedron (except the opposites, which represent the
  16554. // same axis), used as axis directions evenly spread on a sphere.
  16555. const _axisDirections = [
  16556. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  16557. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  16558. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  16559. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  16560. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  16561. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  16562. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  16563. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  16564. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  16565. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  16566. ];
  16567. const _origin = /*@__PURE__*/ new Vector3();
  16568. // maps blur materials to their uniforms dictionary
  16569. const _uniformsMap = new WeakMap();
  16570. // WebGPU Face indices
  16571. const _faceLib = [
  16572. 3, 1, 5,
  16573. 0, 4, 2
  16574. ];
  16575. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  16576. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  16577. /**
  16578. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  16579. * (PMREM) from a cubeMap environment texture. This allows different levels of
  16580. * blur to be quickly accessed based on material roughness. It is packed into a
  16581. * special CubeUV format that allows us to perform custom interpolation so that
  16582. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  16583. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  16584. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  16585. * higher roughness levels. In this way we maintain resolution to smoothly
  16586. * interpolate diffuse lighting while limiting sampling computation.
  16587. *
  16588. * Paper: Fast, Accurate Image-Based Lighting:
  16589. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  16590. */
  16591. class PMREMGenerator {
  16592. /**
  16593. * Constructs a new PMREM generator.
  16594. *
  16595. * @param {Renderer} renderer - The renderer.
  16596. */
  16597. constructor( renderer ) {
  16598. this._renderer = renderer;
  16599. this._pingPongRenderTarget = null;
  16600. this._lodMax = 0;
  16601. this._cubeSize = 0;
  16602. this._lodPlanes = [];
  16603. this._sizeLods = [];
  16604. this._sigmas = [];
  16605. this._lodMeshes = [];
  16606. this._blurMaterial = null;
  16607. this._cubemapMaterial = null;
  16608. this._equirectMaterial = null;
  16609. this._backgroundBox = null;
  16610. }
  16611. get _hasInitialized() {
  16612. return this._renderer.hasInitialized();
  16613. }
  16614. /**
  16615. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16616. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16617. * in radians to be applied to the scene before PMREM generation. Optional near
  16618. * and far planes ensure the scene is rendered in its entirety.
  16619. *
  16620. * @param {Scene} scene - The scene to be captured.
  16621. * @param {number} [sigma=0] - The blur radius in radians.
  16622. * @param {number} [near=0.1] - The near plane distance.
  16623. * @param {number} [far=100] - The far plane distance.
  16624. * @param {Object} [options={}] - The configuration options.
  16625. * @param {number} [options.size=256] - The texture size of the PMREM.
  16626. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  16627. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16628. * @return {RenderTarget} The resulting PMREM.
  16629. * @see {@link PMREMGenerator#fromSceneAsync}
  16630. */
  16631. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16632. const {
  16633. size = 256,
  16634. position = _origin,
  16635. renderTarget = null,
  16636. } = options;
  16637. this._setSize( size );
  16638. if ( this._hasInitialized === false ) {
  16639. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  16640. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16641. options.renderTarget = cubeUVRenderTarget;
  16642. this.fromSceneAsync( scene, sigma, near, far, options );
  16643. return cubeUVRenderTarget;
  16644. }
  16645. _oldTarget = this._renderer.getRenderTarget();
  16646. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16647. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16648. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16649. cubeUVRenderTarget.depthBuffer = true;
  16650. this._init( cubeUVRenderTarget );
  16651. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  16652. if ( sigma > 0 ) {
  16653. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  16654. }
  16655. this._applyPMREM( cubeUVRenderTarget );
  16656. this._cleanup( cubeUVRenderTarget );
  16657. return cubeUVRenderTarget;
  16658. }
  16659. /**
  16660. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16661. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16662. * in radians to be applied to the scene before PMREM generation. Optional near
  16663. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  16664. * is placed at the origin).
  16665. *
  16666. * @param {Scene} scene - The scene to be captured.
  16667. * @param {number} [sigma=0] - The blur radius in radians.
  16668. * @param {number} [near=0.1] - The near plane distance.
  16669. * @param {number} [far=100] - The far plane distance.
  16670. * @param {Object} [options={}] - The configuration options.
  16671. * @param {number} [options.size=256] - The texture size of the PMREM.
  16672. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  16673. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16674. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  16675. * @see {@link PMREMGenerator#fromScene}
  16676. */
  16677. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16678. if ( this._hasInitialized === false ) await this._renderer.init();
  16679. return this.fromScene( scene, sigma, near, far, options );
  16680. }
  16681. /**
  16682. * Generates a PMREM from an equirectangular texture, which can be either LDR
  16683. * or HDR. The ideal input image size is 1k (1024 x 512),
  16684. * as this matches best with the 256 x 256 cubemap output.
  16685. *
  16686. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  16687. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16688. * @return {RenderTarget} The resulting PMREM.
  16689. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  16690. */
  16691. fromEquirectangular( equirectangular, renderTarget = null ) {
  16692. if ( this._hasInitialized === false ) {
  16693. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  16694. this._setSizeFromTexture( equirectangular );
  16695. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16696. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  16697. return cubeUVRenderTarget;
  16698. }
  16699. return this._fromTexture( equirectangular, renderTarget );
  16700. }
  16701. /**
  16702. * Generates a PMREM from an equirectangular texture, which can be either LDR
  16703. * or HDR. The ideal input image size is 1k (1024 x 512),
  16704. * as this matches best with the 256 x 256 cubemap output.
  16705. *
  16706. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  16707. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16708. * @return {Promise<RenderTarget>} The resulting PMREM.
  16709. * @see {@link PMREMGenerator#fromEquirectangular}
  16710. */
  16711. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  16712. if ( this._hasInitialized === false ) await this._renderer.init();
  16713. return this._fromTexture( equirectangular, renderTarget );
  16714. }
  16715. /**
  16716. * Generates a PMREM from an cubemap texture, which can be either LDR
  16717. * or HDR. The ideal input cube size is 256 x 256,
  16718. * as this matches best with the 256 x 256 cubemap output.
  16719. *
  16720. * @param {Texture} cubemap - The cubemap texture to be converted.
  16721. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16722. * @return {RenderTarget} The resulting PMREM.
  16723. * @see {@link PMREMGenerator#fromCubemapAsync}
  16724. */
  16725. fromCubemap( cubemap, renderTarget = null ) {
  16726. if ( this._hasInitialized === false ) {
  16727. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  16728. this._setSizeFromTexture( cubemap );
  16729. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16730. this.fromCubemapAsync( cubemap, renderTarget );
  16731. return cubeUVRenderTarget;
  16732. }
  16733. return this._fromTexture( cubemap, renderTarget );
  16734. }
  16735. /**
  16736. * Generates a PMREM from an cubemap texture, which can be either LDR
  16737. * or HDR. The ideal input cube size is 256 x 256,
  16738. * with the 256 x 256 cubemap output.
  16739. *
  16740. * @param {Texture} cubemap - The cubemap texture to be converted.
  16741. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16742. * @return {Promise<RenderTarget>} The resulting PMREM.
  16743. * @see {@link PMREMGenerator#fromCubemap}
  16744. */
  16745. async fromCubemapAsync( cubemap, renderTarget = null ) {
  16746. if ( this._hasInitialized === false ) await this._renderer.init();
  16747. return this._fromTexture( cubemap, renderTarget );
  16748. }
  16749. /**
  16750. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  16751. * your texture's network fetch for increased concurrency.
  16752. *
  16753. * @returns {Promise}
  16754. */
  16755. async compileCubemapShader() {
  16756. if ( this._cubemapMaterial === null ) {
  16757. this._cubemapMaterial = _getCubemapMaterial();
  16758. await this._compileMaterial( this._cubemapMaterial );
  16759. }
  16760. }
  16761. /**
  16762. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  16763. * your texture's network fetch for increased concurrency.
  16764. *
  16765. * @returns {Promise}
  16766. */
  16767. async compileEquirectangularShader() {
  16768. if ( this._equirectMaterial === null ) {
  16769. this._equirectMaterial = _getEquirectMaterial();
  16770. await this._compileMaterial( this._equirectMaterial );
  16771. }
  16772. }
  16773. /**
  16774. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  16775. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  16776. * one of them will cause any others to also become unusable.
  16777. */
  16778. dispose() {
  16779. this._dispose();
  16780. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  16781. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  16782. if ( this._backgroundBox !== null ) {
  16783. this._backgroundBox.geometry.dispose();
  16784. this._backgroundBox.material.dispose();
  16785. }
  16786. }
  16787. // private interface
  16788. _setSizeFromTexture( texture ) {
  16789. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  16790. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  16791. } else { // Equirectangular
  16792. this._setSize( texture.image.width / 4 );
  16793. }
  16794. }
  16795. _setSize( cubeSize ) {
  16796. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  16797. this._cubeSize = Math.pow( 2, this._lodMax );
  16798. }
  16799. _dispose() {
  16800. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  16801. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  16802. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  16803. this._lodPlanes[ i ].dispose();
  16804. }
  16805. }
  16806. _cleanup( outputTarget ) {
  16807. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  16808. outputTarget.scissorTest = false;
  16809. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  16810. }
  16811. _fromTexture( texture, renderTarget ) {
  16812. this._setSizeFromTexture( texture );
  16813. _oldTarget = this._renderer.getRenderTarget();
  16814. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16815. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16816. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16817. this._init( cubeUVRenderTarget );
  16818. this._textureToCubeUV( texture, cubeUVRenderTarget );
  16819. this._applyPMREM( cubeUVRenderTarget );
  16820. this._cleanup( cubeUVRenderTarget );
  16821. return cubeUVRenderTarget;
  16822. }
  16823. _allocateTarget() {
  16824. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  16825. const height = 4 * this._cubeSize;
  16826. const cubeUVRenderTarget = _createRenderTarget( width, height );
  16827. return cubeUVRenderTarget;
  16828. }
  16829. _init( renderTarget ) {
  16830. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  16831. if ( this._pingPongRenderTarget !== null ) {
  16832. this._dispose();
  16833. }
  16834. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  16835. const { _lodMax } = this;
  16836. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  16837. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  16838. }
  16839. }
  16840. async _compileMaterial( material ) {
  16841. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  16842. await this._renderer.compile( tmpMesh, _flatCamera );
  16843. }
  16844. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  16845. const cubeCamera = _cubeCamera;
  16846. cubeCamera.near = near;
  16847. cubeCamera.far = far;
  16848. // px, py, pz, nx, ny, nz
  16849. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  16850. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  16851. const renderer = this._renderer;
  16852. const originalAutoClear = renderer.autoClear;
  16853. renderer.getClearColor( _clearColor$2 );
  16854. renderer.autoClear = false;
  16855. let backgroundBox = this._backgroundBox;
  16856. if ( backgroundBox === null ) {
  16857. const backgroundMaterial = new MeshBasicMaterial( {
  16858. name: 'PMREM.Background',
  16859. side: BackSide,
  16860. depthWrite: false,
  16861. depthTest: false
  16862. } );
  16863. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  16864. }
  16865. let useSolidColor = false;
  16866. const background = scene.background;
  16867. if ( background ) {
  16868. if ( background.isColor ) {
  16869. backgroundBox.material.color.copy( background );
  16870. scene.background = null;
  16871. useSolidColor = true;
  16872. }
  16873. } else {
  16874. backgroundBox.material.color.copy( _clearColor$2 );
  16875. useSolidColor = true;
  16876. }
  16877. renderer.setRenderTarget( cubeUVRenderTarget );
  16878. renderer.clear();
  16879. if ( useSolidColor ) {
  16880. renderer.render( backgroundBox, cubeCamera );
  16881. }
  16882. for ( let i = 0; i < 6; i ++ ) {
  16883. const col = i % 3;
  16884. if ( col === 0 ) {
  16885. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16886. cubeCamera.position.set( position.x, position.y, position.z );
  16887. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  16888. } else if ( col === 1 ) {
  16889. cubeCamera.up.set( 0, 0, upSign[ i ] );
  16890. cubeCamera.position.set( position.x, position.y, position.z );
  16891. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  16892. } else {
  16893. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16894. cubeCamera.position.set( position.x, position.y, position.z );
  16895. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  16896. }
  16897. const size = this._cubeSize;
  16898. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  16899. renderer.render( scene, cubeCamera );
  16900. }
  16901. renderer.autoClear = originalAutoClear;
  16902. scene.background = background;
  16903. }
  16904. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  16905. const renderer = this._renderer;
  16906. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  16907. if ( isCubeTexture ) {
  16908. if ( this._cubemapMaterial === null ) {
  16909. this._cubemapMaterial = _getCubemapMaterial( texture );
  16910. }
  16911. } else {
  16912. if ( this._equirectMaterial === null ) {
  16913. this._equirectMaterial = _getEquirectMaterial( texture );
  16914. }
  16915. }
  16916. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  16917. material.fragmentNode.value = texture;
  16918. const mesh = this._lodMeshes[ 0 ];
  16919. mesh.material = material;
  16920. const size = this._cubeSize;
  16921. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  16922. renderer.setRenderTarget( cubeUVRenderTarget );
  16923. renderer.render( mesh, _flatCamera );
  16924. }
  16925. _applyPMREM( cubeUVRenderTarget ) {
  16926. const renderer = this._renderer;
  16927. const autoClear = renderer.autoClear;
  16928. renderer.autoClear = false;
  16929. const n = this._lodPlanes.length;
  16930. for ( let i = 1; i < n; i ++ ) {
  16931. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  16932. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  16933. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  16934. }
  16935. renderer.autoClear = autoClear;
  16936. }
  16937. /**
  16938. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  16939. * vertically and horizontally, but this breaks down on a cube. Here we apply
  16940. * the blur latitudinally (around the poles), and then longitudinally (towards
  16941. * the poles) to approximate the orthogonally-separable blur. It is least
  16942. * accurate at the poles, but still does a decent job.
  16943. *
  16944. * @private
  16945. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  16946. * @param {number} lodIn - The input level-of-detail.
  16947. * @param {number} lodOut - The output level-of-detail.
  16948. * @param {number} sigma - The blur radius in radians.
  16949. * @param {Vector3} [poleAxis] - The pole axis.
  16950. */
  16951. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  16952. const pingPongRenderTarget = this._pingPongRenderTarget;
  16953. this._halfBlur(
  16954. cubeUVRenderTarget,
  16955. pingPongRenderTarget,
  16956. lodIn,
  16957. lodOut,
  16958. sigma,
  16959. 'latitudinal',
  16960. poleAxis );
  16961. this._halfBlur(
  16962. pingPongRenderTarget,
  16963. cubeUVRenderTarget,
  16964. lodOut,
  16965. lodOut,
  16966. sigma,
  16967. 'longitudinal',
  16968. poleAxis );
  16969. }
  16970. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  16971. const renderer = this._renderer;
  16972. const blurMaterial = this._blurMaterial;
  16973. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  16974. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  16975. }
  16976. // Number of standard deviations at which to cut off the discrete approximation.
  16977. const STANDARD_DEVIATIONS = 3;
  16978. const blurMesh = this._lodMeshes[ lodOut ];
  16979. blurMesh.material = blurMaterial;
  16980. const blurUniforms = _uniformsMap.get( blurMaterial );
  16981. const pixels = this._sizeLods[ lodIn ] - 1;
  16982. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  16983. const sigmaPixels = sigmaRadians / radiansPerPixel;
  16984. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  16985. if ( samples > MAX_SAMPLES ) {
  16986. console.warn( `sigmaRadians, ${
  16987. sigmaRadians}, is too large and will clip, as it requested ${
  16988. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  16989. }
  16990. const weights = [];
  16991. let sum = 0;
  16992. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  16993. const x = i / sigmaPixels;
  16994. const weight = Math.exp( - x * x / 2 );
  16995. weights.push( weight );
  16996. if ( i === 0 ) {
  16997. sum += weight;
  16998. } else if ( i < samples ) {
  16999. sum += 2 * weight;
  17000. }
  17001. }
  17002. for ( let i = 0; i < weights.length; i ++ ) {
  17003. weights[ i ] = weights[ i ] / sum;
  17004. }
  17005. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  17006. blurUniforms.envMap.value = targetIn.texture;
  17007. blurUniforms.samples.value = samples;
  17008. blurUniforms.weights.array = weights;
  17009. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  17010. if ( poleAxis ) {
  17011. blurUniforms.poleAxis.value = poleAxis;
  17012. }
  17013. const { _lodMax } = this;
  17014. blurUniforms.dTheta.value = radiansPerPixel;
  17015. blurUniforms.mipInt.value = _lodMax - lodIn;
  17016. const outputSize = this._sizeLods[ lodOut ];
  17017. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  17018. const y = 4 * ( this._cubeSize - outputSize );
  17019. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  17020. renderer.setRenderTarget( targetOut );
  17021. renderer.render( blurMesh, _flatCamera );
  17022. }
  17023. }
  17024. function _createPlanes( lodMax ) {
  17025. const lodPlanes = [];
  17026. const sizeLods = [];
  17027. const sigmas = [];
  17028. const lodMeshes = [];
  17029. let lod = lodMax;
  17030. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  17031. for ( let i = 0; i < totalLods; i ++ ) {
  17032. const sizeLod = Math.pow( 2, lod );
  17033. sizeLods.push( sizeLod );
  17034. let sigma = 1.0 / sizeLod;
  17035. if ( i > lodMax - LOD_MIN ) {
  17036. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  17037. } else if ( i === 0 ) {
  17038. sigma = 0;
  17039. }
  17040. sigmas.push( sigma );
  17041. const texelSize = 1.0 / ( sizeLod - 2 );
  17042. const min = - texelSize;
  17043. const max = 1 + texelSize;
  17044. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  17045. const cubeFaces = 6;
  17046. const vertices = 6;
  17047. const positionSize = 3;
  17048. const uvSize = 2;
  17049. const faceIndexSize = 1;
  17050. const position = new Float32Array( positionSize * vertices * cubeFaces );
  17051. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  17052. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  17053. for ( let face = 0; face < cubeFaces; face ++ ) {
  17054. const x = ( face % 3 ) * 2 / 3 - 1;
  17055. const y = face > 2 ? 0 : -1;
  17056. const coordinates = [
  17057. x, y, 0,
  17058. x + 2 / 3, y, 0,
  17059. x + 2 / 3, y + 1, 0,
  17060. x, y, 0,
  17061. x + 2 / 3, y + 1, 0,
  17062. x, y + 1, 0
  17063. ];
  17064. const faceIdx = _faceLib[ face ];
  17065. position.set( coordinates, positionSize * vertices * faceIdx );
  17066. uv.set( uv1, uvSize * vertices * faceIdx );
  17067. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  17068. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  17069. }
  17070. const planes = new BufferGeometry();
  17071. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  17072. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  17073. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  17074. lodPlanes.push( planes );
  17075. lodMeshes.push( new Mesh( planes, null ) );
  17076. if ( lod > LOD_MIN ) {
  17077. lod --;
  17078. }
  17079. }
  17080. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  17081. }
  17082. function _createRenderTarget( width, height ) {
  17083. const params = {
  17084. magFilter: LinearFilter,
  17085. minFilter: LinearFilter,
  17086. generateMipmaps: false,
  17087. type: HalfFloatType,
  17088. format: RGBAFormat,
  17089. colorSpace: LinearSRGBColorSpace,
  17090. //depthBuffer: false
  17091. };
  17092. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  17093. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  17094. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  17095. cubeUVRenderTarget.texture.isPMREMTexture = true;
  17096. cubeUVRenderTarget.scissorTest = true;
  17097. return cubeUVRenderTarget;
  17098. }
  17099. function _setViewport( target, x, y, width, height ) {
  17100. target.viewport.set( x, y, width, height );
  17101. target.scissor.set( x, y, width, height );
  17102. }
  17103. function _getMaterial( type ) {
  17104. const material = new NodeMaterial();
  17105. material.depthTest = false;
  17106. material.depthWrite = false;
  17107. material.blending = NoBlending;
  17108. material.name = `PMREM_${ type }`;
  17109. return material;
  17110. }
  17111. function _getBlurShader( lodMax, width, height ) {
  17112. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  17113. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  17114. const dTheta = uniform( 0 );
  17115. const n = float( MAX_SAMPLES );
  17116. const latitudinal = uniform( 0 ); // false, bool
  17117. const samples = uniform( 1 ); // int
  17118. const envMap = texture( null );
  17119. const mipInt = uniform( 0 ); // int
  17120. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  17121. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  17122. const CUBEUV_MAX_MIP = float( lodMax );
  17123. const materialUniforms = {
  17124. n,
  17125. latitudinal,
  17126. weights,
  17127. poleAxis,
  17128. outputDirection: _outputDirection,
  17129. dTheta,
  17130. samples,
  17131. envMap,
  17132. mipInt,
  17133. CUBEUV_TEXEL_WIDTH,
  17134. CUBEUV_TEXEL_HEIGHT,
  17135. CUBEUV_MAX_MIP
  17136. };
  17137. const material = _getMaterial( 'blur' );
  17138. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  17139. _uniformsMap.set( material, materialUniforms );
  17140. return material;
  17141. }
  17142. function _getCubemapMaterial( envTexture ) {
  17143. const material = _getMaterial( 'cubemap' );
  17144. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  17145. return material;
  17146. }
  17147. function _getEquirectMaterial( envTexture ) {
  17148. const material = _getMaterial( 'equirect' );
  17149. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  17150. return material;
  17151. }
  17152. const _cache = new WeakMap();
  17153. /**
  17154. * Generates the cubeUV size based on the given image height.
  17155. *
  17156. * @private
  17157. * @param {number} imageHeight - The image height.
  17158. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  17159. */
  17160. function _generateCubeUVSize( imageHeight ) {
  17161. const maxMip = Math.log2( imageHeight ) - 2;
  17162. const texelHeight = 1.0 / imageHeight;
  17163. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  17164. return { texelWidth, texelHeight, maxMip };
  17165. }
  17166. /**
  17167. * Generates a PMREM from the given texture.
  17168. *
  17169. * @private
  17170. * @param {Texture} texture - The texture to create the PMREM for.
  17171. * @param {Renderer} renderer - The renderer.
  17172. * @param {PMREMGenerator} generator - The PMREM generator.
  17173. * @return {?Texture} The PMREM.
  17174. */
  17175. function _getPMREMFromTexture( texture, renderer, generator ) {
  17176. const cache = _getCache( renderer );
  17177. let cacheTexture = cache.get( texture );
  17178. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  17179. if ( pmremVersion !== texture.pmremVersion ) {
  17180. const image = texture.image;
  17181. if ( texture.isCubeTexture ) {
  17182. if ( isCubeMapReady( image ) ) {
  17183. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  17184. } else {
  17185. return null;
  17186. }
  17187. } else {
  17188. if ( isEquirectangularMapReady( image ) ) {
  17189. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  17190. } else {
  17191. return null;
  17192. }
  17193. }
  17194. cacheTexture.pmremVersion = texture.pmremVersion;
  17195. cache.set( texture, cacheTexture );
  17196. }
  17197. return cacheTexture.texture;
  17198. }
  17199. /**
  17200. * Returns a cache that stores generated PMREMs for the respective textures.
  17201. * A cache must be maintained per renderer since PMREMs are render target textures
  17202. * which can't be shared across render contexts.
  17203. *
  17204. * @private
  17205. * @param {Renderer} renderer - The renderer.
  17206. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  17207. */
  17208. function _getCache( renderer ) {
  17209. let rendererCache = _cache.get( renderer );
  17210. if ( rendererCache === undefined ) {
  17211. rendererCache = new WeakMap();
  17212. _cache.set( renderer, rendererCache );
  17213. }
  17214. return rendererCache;
  17215. }
  17216. /**
  17217. * This node represents a PMREM which is a special type of preprocessed
  17218. * environment map intended for PBR materials.
  17219. *
  17220. * ```js
  17221. * const material = new MeshStandardNodeMaterial();
  17222. * material.envNode = pmremTexture( envMap );
  17223. * ```
  17224. *
  17225. * @augments TempNode
  17226. */
  17227. class PMREMNode extends TempNode {
  17228. static get type() {
  17229. return 'PMREMNode';
  17230. }
  17231. /**
  17232. * Constructs a new function overloading node.
  17233. *
  17234. * @param {Texture} value - The input texture.
  17235. * @param {Node<vec2>} [uvNode=null] - The uv node.
  17236. * @param {Node<float>} [levelNode=null] - The level node.
  17237. */
  17238. constructor( value, uvNode = null, levelNode = null ) {
  17239. super( 'vec3' );
  17240. /**
  17241. * Reference to the input texture.
  17242. *
  17243. * @private
  17244. * @type {Texture}
  17245. */
  17246. this._value = value;
  17247. /**
  17248. * Reference to the generated PMREM.
  17249. *
  17250. * @private
  17251. * @type {Texture | null}
  17252. * @default null
  17253. */
  17254. this._pmrem = null;
  17255. /**
  17256. * The uv node.
  17257. *
  17258. * @type {Node<vec2>}
  17259. */
  17260. this.uvNode = uvNode;
  17261. /**
  17262. * The level node.
  17263. *
  17264. * @type {Node<float>}
  17265. */
  17266. this.levelNode = levelNode;
  17267. /**
  17268. * Reference to a PMREM generator.
  17269. *
  17270. * @private
  17271. * @type {?PMREMGenerator}
  17272. * @default null
  17273. */
  17274. this._generator = null;
  17275. const defaultTexture = new Texture();
  17276. defaultTexture.isRenderTargetTexture = true;
  17277. /**
  17278. * The texture node holding the generated PMREM.
  17279. *
  17280. * @private
  17281. * @type {TextureNode}
  17282. */
  17283. this._texture = texture( defaultTexture );
  17284. /**
  17285. * A uniform representing the PMREM's width.
  17286. *
  17287. * @private
  17288. * @type {UniformNode<float>}
  17289. */
  17290. this._width = uniform( 0 );
  17291. /**
  17292. * A uniform representing the PMREM's height.
  17293. *
  17294. * @private
  17295. * @type {UniformNode<float>}
  17296. */
  17297. this._height = uniform( 0 );
  17298. /**
  17299. * A uniform representing the PMREM's max Mip.
  17300. *
  17301. * @private
  17302. * @type {UniformNode<float>}
  17303. */
  17304. this._maxMip = uniform( 0 );
  17305. /**
  17306. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  17307. *
  17308. * @type {string}
  17309. * @default 'render'
  17310. */
  17311. this.updateBeforeType = NodeUpdateType.RENDER;
  17312. }
  17313. set value( value ) {
  17314. this._value = value;
  17315. this._pmrem = null;
  17316. }
  17317. /**
  17318. * The node's texture value.
  17319. *
  17320. * @type {Texture}
  17321. */
  17322. get value() {
  17323. return this._value;
  17324. }
  17325. /**
  17326. * Uses the given PMREM texture to update internal values.
  17327. *
  17328. * @param {Texture} texture - The PMREM texture.
  17329. */
  17330. updateFromTexture( texture ) {
  17331. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  17332. this._texture.value = texture;
  17333. this._width.value = cubeUVSize.texelWidth;
  17334. this._height.value = cubeUVSize.texelHeight;
  17335. this._maxMip.value = cubeUVSize.maxMip;
  17336. }
  17337. updateBefore( frame ) {
  17338. let pmrem = this._pmrem;
  17339. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  17340. const texture = this._value;
  17341. if ( pmremVersion !== texture.pmremVersion ) {
  17342. if ( texture.isPMREMTexture === true ) {
  17343. pmrem = texture;
  17344. } else {
  17345. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  17346. }
  17347. if ( pmrem !== null ) {
  17348. this._pmrem = pmrem;
  17349. this.updateFromTexture( pmrem );
  17350. }
  17351. }
  17352. }
  17353. setup( builder ) {
  17354. if ( this._generator === null ) {
  17355. this._generator = new PMREMGenerator( builder.renderer );
  17356. }
  17357. this.updateBefore( builder );
  17358. //
  17359. let uvNode = this.uvNode;
  17360. if ( uvNode === null && builder.context.getUV ) {
  17361. uvNode = builder.context.getUV( this );
  17362. }
  17363. //
  17364. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  17365. //
  17366. let levelNode = this.levelNode;
  17367. if ( levelNode === null && builder.context.getTextureLevel ) {
  17368. levelNode = builder.context.getTextureLevel( this );
  17369. }
  17370. //
  17371. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  17372. }
  17373. dispose() {
  17374. super.dispose();
  17375. if ( this._generator !== null ) this._generator.dispose();
  17376. }
  17377. }
  17378. /**
  17379. * Returns `true` if the given cube map image has been fully loaded.
  17380. *
  17381. * @private
  17382. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  17383. * @return {boolean} Whether the given cube map is ready or not.
  17384. */
  17385. function isCubeMapReady( image ) {
  17386. if ( image === null || image === undefined ) return false;
  17387. let count = 0;
  17388. const length = 6;
  17389. for ( let i = 0; i < length; i ++ ) {
  17390. if ( image[ i ] !== undefined ) count ++;
  17391. }
  17392. return count === length;
  17393. }
  17394. /**
  17395. * Returns `true` if the given equirectangular image has been fully loaded.
  17396. *
  17397. * @private
  17398. * @param {(Image|Object)} image - The equirectangular image.
  17399. * @return {boolean} Whether the given cube map is ready or not.
  17400. */
  17401. function isEquirectangularMapReady( image ) {
  17402. if ( image === null || image === undefined ) return false;
  17403. return image.height > 0;
  17404. }
  17405. /**
  17406. * TSL function for creating a PMREM node.
  17407. *
  17408. * @tsl
  17409. * @function
  17410. * @param {Texture} value - The input texture.
  17411. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  17412. * @param {?Node<float>} [levelNode=null] - The level node.
  17413. * @returns {PMREMNode}
  17414. */
  17415. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  17416. const _envNodeCache = new WeakMap();
  17417. /**
  17418. * Represents a physical model for Image-based lighting (IBL). The environment
  17419. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  17420. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  17421. *
  17422. * @augments LightingNode
  17423. */
  17424. class EnvironmentNode extends LightingNode {
  17425. static get type() {
  17426. return 'EnvironmentNode';
  17427. }
  17428. /**
  17429. * Constructs a new environment node.
  17430. *
  17431. * @param {Node} [envNode=null] - A node representing the environment.
  17432. */
  17433. constructor( envNode = null ) {
  17434. super();
  17435. /**
  17436. * A node representing the environment.
  17437. *
  17438. * @type {?Node}
  17439. * @default null
  17440. */
  17441. this.envNode = envNode;
  17442. }
  17443. setup( builder ) {
  17444. const { material } = builder;
  17445. let envNode = this.envNode;
  17446. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  17447. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  17448. let cacheEnvNode = _envNodeCache.get( value );
  17449. if ( cacheEnvNode === undefined ) {
  17450. cacheEnvNode = pmremTexture( value );
  17451. _envNodeCache.set( value, cacheEnvNode );
  17452. }
  17453. envNode = cacheEnvNode;
  17454. }
  17455. //
  17456. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  17457. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  17458. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  17459. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  17460. const isolateRadiance = cache( radiance );
  17461. const isolateIrradiance = cache( irradiance );
  17462. //
  17463. builder.context.radiance.addAssign( isolateRadiance );
  17464. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  17465. //
  17466. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  17467. if ( clearcoatRadiance ) {
  17468. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  17469. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  17470. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  17471. }
  17472. }
  17473. }
  17474. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  17475. let reflectVec = null;
  17476. return {
  17477. getUV: () => {
  17478. if ( reflectVec === null ) {
  17479. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  17480. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  17481. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  17482. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  17483. }
  17484. return reflectVec;
  17485. },
  17486. getTextureLevel: () => {
  17487. return roughnessNode;
  17488. }
  17489. };
  17490. };
  17491. const createIrradianceContext = ( normalWorldNode ) => {
  17492. return {
  17493. getUV: () => {
  17494. return normalWorldNode;
  17495. },
  17496. getTextureLevel: () => {
  17497. return float( 1.0 );
  17498. }
  17499. };
  17500. };
  17501. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  17502. /**
  17503. * Node material version of {@link MeshStandardMaterial}.
  17504. *
  17505. * @augments NodeMaterial
  17506. */
  17507. class MeshStandardNodeMaterial extends NodeMaterial {
  17508. static get type() {
  17509. return 'MeshStandardNodeMaterial';
  17510. }
  17511. /**
  17512. * Constructs a new mesh standard node material.
  17513. *
  17514. * @param {Object} [parameters] - The configuration parameter.
  17515. */
  17516. constructor( parameters ) {
  17517. super();
  17518. /**
  17519. * This flag can be used for type testing.
  17520. *
  17521. * @type {boolean}
  17522. * @readonly
  17523. * @default true
  17524. */
  17525. this.isMeshStandardNodeMaterial = true;
  17526. /**
  17527. * Set to `true` because standard materials react on lights.
  17528. *
  17529. * @type {boolean}
  17530. * @default true
  17531. */
  17532. this.lights = true;
  17533. /**
  17534. * The emissive color of standard materials is by default inferred from the `emissive`,
  17535. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  17536. * overwrite the default and define the emissive color with a node instead.
  17537. *
  17538. * If you don't want to overwrite the emissive color but modify the existing
  17539. * value instead, use {@link materialEmissive}.
  17540. *
  17541. * @type {?Node<vec3>}
  17542. * @default null
  17543. */
  17544. this.emissiveNode = null;
  17545. /**
  17546. * The metalness of standard materials is by default inferred from the `metalness`,
  17547. * and `metalnessMap` properties. This node property allows to
  17548. * overwrite the default and define the metalness with a node instead.
  17549. *
  17550. * If you don't want to overwrite the metalness but modify the existing
  17551. * value instead, use {@link materialMetalness}.
  17552. *
  17553. * @type {?Node<float>}
  17554. * @default null
  17555. */
  17556. this.metalnessNode = null;
  17557. /**
  17558. * The roughness of standard materials is by default inferred from the `roughness`,
  17559. * and `roughnessMap` properties. This node property allows to
  17560. * overwrite the default and define the roughness with a node instead.
  17561. *
  17562. * If you don't want to overwrite the roughness but modify the existing
  17563. * value instead, use {@link materialRoughness}.
  17564. *
  17565. * @type {?Node<float>}
  17566. * @default null
  17567. */
  17568. this.roughnessNode = null;
  17569. this.setDefaultValues( _defaultValues$6 );
  17570. this.setValues( parameters );
  17571. }
  17572. /**
  17573. * Overwritten since this type of material uses {@link EnvironmentNode}
  17574. * to implement the PBR (PMREM based) environment mapping. Besides, the
  17575. * method honors `Scene.environment`.
  17576. *
  17577. * @param {NodeBuilder} builder - The current node builder.
  17578. * @return {?EnvironmentNode<vec3>} The environment node.
  17579. */
  17580. setupEnvironment( builder ) {
  17581. let envNode = super.setupEnvironment( builder );
  17582. if ( envNode === null && builder.environmentNode ) {
  17583. envNode = builder.environmentNode;
  17584. }
  17585. return envNode ? new EnvironmentNode( envNode ) : null;
  17586. }
  17587. /**
  17588. * Setups the lighting model.
  17589. *
  17590. * @return {PhysicalLightingModel} The lighting model.
  17591. */
  17592. setupLightingModel( /*builder*/ ) {
  17593. return new PhysicalLightingModel();
  17594. }
  17595. /**
  17596. * Setups the specular related node variables.
  17597. */
  17598. setupSpecular() {
  17599. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  17600. specularColor.assign( specularColorNode );
  17601. specularF90.assign( 1.0 );
  17602. }
  17603. /**
  17604. * Setups the standard specific node variables.
  17605. *
  17606. * @param {NodeBuilder} builder - The current node builder.
  17607. */
  17608. setupVariants() {
  17609. // METALNESS
  17610. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  17611. metalness.assign( metalnessNode );
  17612. // ROUGHNESS
  17613. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  17614. roughnessNode = getRoughness( { roughness: roughnessNode } );
  17615. roughness.assign( roughnessNode );
  17616. // SPECULAR COLOR
  17617. this.setupSpecular();
  17618. // DIFFUSE COLOR
  17619. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  17620. }
  17621. copy( source ) {
  17622. this.emissiveNode = source.emissiveNode;
  17623. this.metalnessNode = source.metalnessNode;
  17624. this.roughnessNode = source.roughnessNode;
  17625. return super.copy( source );
  17626. }
  17627. }
  17628. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  17629. /**
  17630. * Node material version of {@link MeshPhysicalMaterial}.
  17631. *
  17632. * @augments MeshStandardNodeMaterial
  17633. */
  17634. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  17635. static get type() {
  17636. return 'MeshPhysicalNodeMaterial';
  17637. }
  17638. /**
  17639. * Constructs a new mesh physical node material.
  17640. *
  17641. * @param {Object} [parameters] - The configuration parameter.
  17642. */
  17643. constructor( parameters ) {
  17644. super();
  17645. /**
  17646. * This flag can be used for type testing.
  17647. *
  17648. * @type {boolean}
  17649. * @readonly
  17650. * @default true
  17651. */
  17652. this.isMeshPhysicalNodeMaterial = true;
  17653. /**
  17654. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  17655. * and `clearcoatMap` properties. This node property allows to overwrite the default
  17656. * and define the clearcoat with a node instead.
  17657. *
  17658. * If you don't want to overwrite the clearcoat but modify the existing
  17659. * value instead, use {@link materialClearcoat}.
  17660. *
  17661. * @type {?Node<float>}
  17662. * @default null
  17663. */
  17664. this.clearcoatNode = null;
  17665. /**
  17666. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  17667. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  17668. * and define the clearcoat roughness with a node instead.
  17669. *
  17670. * If you don't want to overwrite the clearcoat roughness but modify the existing
  17671. * value instead, use {@link materialClearcoatRoughness}.
  17672. *
  17673. * @type {?Node<float>}
  17674. * @default null
  17675. */
  17676. this.clearcoatRoughnessNode = null;
  17677. /**
  17678. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  17679. * property. This node property allows to overwrite the default
  17680. * and define the clearcoat normal with a node instead.
  17681. *
  17682. * If you don't want to overwrite the clearcoat normal but modify the existing
  17683. * value instead, use {@link materialClearcoatNormal}.
  17684. *
  17685. * @type {?Node<vec3>}
  17686. * @default null
  17687. */
  17688. this.clearcoatNormalNode = null;
  17689. /**
  17690. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  17691. * and `sheenColorMap` properties. This node property allows to overwrite the default
  17692. * and define the sheen with a node instead.
  17693. *
  17694. * If you don't want to overwrite the sheen but modify the existing
  17695. * value instead, use {@link materialSheen}.
  17696. *
  17697. * @type {?Node<vec3>}
  17698. * @default null
  17699. */
  17700. this.sheenNode = null;
  17701. /**
  17702. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  17703. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  17704. * and define the sheen roughness with a node instead.
  17705. *
  17706. * If you don't want to overwrite the sheen roughness but modify the existing
  17707. * value instead, use {@link materialSheenRoughness}.
  17708. *
  17709. * @type {?Node<float>}
  17710. * @default null
  17711. */
  17712. this.sheenRoughnessNode = null;
  17713. /**
  17714. * The iridescence of physical materials is by default inferred from the `iridescence`
  17715. * property. This node property allows to overwrite the default
  17716. * and define the iridescence with a node instead.
  17717. *
  17718. * If you don't want to overwrite the iridescence but modify the existing
  17719. * value instead, use {@link materialIridescence}.
  17720. *
  17721. * @type {?Node<float>}
  17722. * @default null
  17723. */
  17724. this.iridescenceNode = null;
  17725. /**
  17726. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  17727. * property. This node property allows to overwrite the default
  17728. * and define the iridescence IOR with a node instead.
  17729. *
  17730. * If you don't want to overwrite the iridescence IOR but modify the existing
  17731. * value instead, use {@link materialIridescenceIOR}.
  17732. *
  17733. * @type {?Node<float>}
  17734. * @default null
  17735. */
  17736. this.iridescenceIORNode = null;
  17737. /**
  17738. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  17739. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  17740. * and define the iridescence thickness with a node instead.
  17741. *
  17742. * If you don't want to overwrite the iridescence thickness but modify the existing
  17743. * value instead, use {@link materialIridescenceThickness}.
  17744. *
  17745. * @type {?Node<float>}
  17746. * @default null
  17747. */
  17748. this.iridescenceThicknessNode = null;
  17749. /**
  17750. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  17751. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  17752. * and define the specular intensity with a node instead.
  17753. *
  17754. * If you don't want to overwrite the specular intensity but modify the existing
  17755. * value instead, use {@link materialSpecularIntensity}.
  17756. *
  17757. * @type {?Node<float>}
  17758. * @default null
  17759. */
  17760. this.specularIntensityNode = null;
  17761. /**
  17762. * The specular color of physical materials is by default inferred from the `specularColor`
  17763. * and `specularColorMap` properties. This node property allows to overwrite the default
  17764. * and define the specular color with a node instead.
  17765. *
  17766. * If you don't want to overwrite the specular color but modify the existing
  17767. * value instead, use {@link materialSpecularColor}.
  17768. *
  17769. * @type {?Node<vec3>}
  17770. * @default null
  17771. */
  17772. this.specularColorNode = null;
  17773. /**
  17774. * The ior of physical materials is by default inferred from the `ior`
  17775. * property. This node property allows to overwrite the default
  17776. * and define the ior with a node instead.
  17777. *
  17778. * If you don't want to overwrite the ior but modify the existing
  17779. * value instead, use {@link materialIOR}.
  17780. *
  17781. * @type {?Node<float>}
  17782. * @default null
  17783. */
  17784. this.iorNode = null;
  17785. /**
  17786. * The transmission of physical materials is by default inferred from the `transmission` and
  17787. * `transmissionMap` properties. This node property allows to overwrite the default
  17788. * and define the transmission with a node instead.
  17789. *
  17790. * If you don't want to overwrite the transmission but modify the existing
  17791. * value instead, use {@link materialTransmission}.
  17792. *
  17793. * @type {?Node<float>}
  17794. * @default null
  17795. */
  17796. this.transmissionNode = null;
  17797. /**
  17798. * The thickness of physical materials is by default inferred from the `thickness` and
  17799. * `thicknessMap` properties. This node property allows to overwrite the default
  17800. * and define the thickness with a node instead.
  17801. *
  17802. * If you don't want to overwrite the thickness but modify the existing
  17803. * value instead, use {@link materialThickness}.
  17804. *
  17805. * @type {?Node<float>}
  17806. * @default null
  17807. */
  17808. this.thicknessNode = null;
  17809. /**
  17810. * The attenuation distance of physical materials is by default inferred from the
  17811. * `attenuationDistance` property. This node property allows to overwrite the default
  17812. * and define the attenuation distance with a node instead.
  17813. *
  17814. * If you don't want to overwrite the attenuation distance but modify the existing
  17815. * value instead, use {@link materialAttenuationDistance}.
  17816. *
  17817. * @type {?Node<float>}
  17818. * @default null
  17819. */
  17820. this.attenuationDistanceNode = null;
  17821. /**
  17822. * The attenuation color of physical materials is by default inferred from the
  17823. * `attenuationColor` property. This node property allows to overwrite the default
  17824. * and define the attenuation color with a node instead.
  17825. *
  17826. * If you don't want to overwrite the attenuation color but modify the existing
  17827. * value instead, use {@link materialAttenuationColor}.
  17828. *
  17829. * @type {?Node<vec3>}
  17830. * @default null
  17831. */
  17832. this.attenuationColorNode = null;
  17833. /**
  17834. * The dispersion of physical materials is by default inferred from the
  17835. * `dispersion` property. This node property allows to overwrite the default
  17836. * and define the dispersion with a node instead.
  17837. *
  17838. * If you don't want to overwrite the dispersion but modify the existing
  17839. * value instead, use {@link materialDispersion}.
  17840. *
  17841. * @type {?Node<float>}
  17842. * @default null
  17843. */
  17844. this.dispersionNode = null;
  17845. /**
  17846. * The anisotropy of physical materials is by default inferred from the
  17847. * `anisotropy` property. This node property allows to overwrite the default
  17848. * and define the anisotropy with a node instead.
  17849. *
  17850. * If you don't want to overwrite the anisotropy but modify the existing
  17851. * value instead, use {@link materialAnisotropy}.
  17852. *
  17853. * @type {?Node<float>}
  17854. * @default null
  17855. */
  17856. this.anisotropyNode = null;
  17857. this.setDefaultValues( _defaultValues$5 );
  17858. this.setValues( parameters );
  17859. }
  17860. /**
  17861. * Whether the lighting model should use clearcoat or not.
  17862. *
  17863. * @type {boolean}
  17864. * @default true
  17865. */
  17866. get useClearcoat() {
  17867. return this.clearcoat > 0 || this.clearcoatNode !== null;
  17868. }
  17869. /**
  17870. * Whether the lighting model should use iridescence or not.
  17871. *
  17872. * @type {boolean}
  17873. * @default true
  17874. */
  17875. get useIridescence() {
  17876. return this.iridescence > 0 || this.iridescenceNode !== null;
  17877. }
  17878. /**
  17879. * Whether the lighting model should use sheen or not.
  17880. *
  17881. * @type {boolean}
  17882. * @default true
  17883. */
  17884. get useSheen() {
  17885. return this.sheen > 0 || this.sheenNode !== null;
  17886. }
  17887. /**
  17888. * Whether the lighting model should use anisotropy or not.
  17889. *
  17890. * @type {boolean}
  17891. * @default true
  17892. */
  17893. get useAnisotropy() {
  17894. return this.anisotropy > 0 || this.anisotropyNode !== null;
  17895. }
  17896. /**
  17897. * Whether the lighting model should use transmission or not.
  17898. *
  17899. * @type {boolean}
  17900. * @default true
  17901. */
  17902. get useTransmission() {
  17903. return this.transmission > 0 || this.transmissionNode !== null;
  17904. }
  17905. /**
  17906. * Whether the lighting model should use dispersion or not.
  17907. *
  17908. * @type {boolean}
  17909. * @default true
  17910. */
  17911. get useDispersion() {
  17912. return this.dispersion > 0 || this.dispersionNode !== null;
  17913. }
  17914. /**
  17915. * Setups the specular related node variables.
  17916. */
  17917. setupSpecular() {
  17918. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  17919. ior.assign( iorNode );
  17920. 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 ) );
  17921. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  17922. }
  17923. /**
  17924. * Setups the lighting model.
  17925. *
  17926. * @return {PhysicalLightingModel} The lighting model.
  17927. */
  17928. setupLightingModel( /*builder*/ ) {
  17929. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  17930. }
  17931. /**
  17932. * Setups the physical specific node variables.
  17933. *
  17934. * @param {NodeBuilder} builder - The current node builder.
  17935. */
  17936. setupVariants( builder ) {
  17937. super.setupVariants( builder );
  17938. // CLEARCOAT
  17939. if ( this.useClearcoat ) {
  17940. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  17941. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  17942. clearcoat.assign( clearcoatNode );
  17943. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  17944. }
  17945. // SHEEN
  17946. if ( this.useSheen ) {
  17947. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  17948. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  17949. sheen.assign( sheenNode );
  17950. sheenRoughness.assign( sheenRoughnessNode );
  17951. }
  17952. // IRIDESCENCE
  17953. if ( this.useIridescence ) {
  17954. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  17955. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  17956. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  17957. iridescence.assign( iridescenceNode );
  17958. iridescenceIOR.assign( iridescenceIORNode );
  17959. iridescenceThickness.assign( iridescenceThicknessNode );
  17960. }
  17961. // ANISOTROPY
  17962. if ( this.useAnisotropy ) {
  17963. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  17964. anisotropy.assign( anisotropyV.length() );
  17965. If( anisotropy.equal( 0.0 ), () => {
  17966. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  17967. } ).Else( () => {
  17968. anisotropyV.divAssign( vec2( anisotropy ) );
  17969. anisotropy.assign( anisotropy.saturate() );
  17970. } );
  17971. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  17972. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  17973. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  17974. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  17975. }
  17976. // TRANSMISSION
  17977. if ( this.useTransmission ) {
  17978. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  17979. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  17980. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  17981. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  17982. transmission.assign( transmissionNode );
  17983. thickness.assign( thicknessNode );
  17984. attenuationDistance.assign( attenuationDistanceNode );
  17985. attenuationColor.assign( attenuationColorNode );
  17986. if ( this.useDispersion ) {
  17987. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  17988. dispersion.assign( dispersionNode );
  17989. }
  17990. }
  17991. }
  17992. /**
  17993. * Setups the clearcoat normal node.
  17994. *
  17995. * @return {Node<vec3>} The clearcoat normal.
  17996. */
  17997. setupClearcoatNormal() {
  17998. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  17999. }
  18000. setup( builder ) {
  18001. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  18002. super.setup( builder );
  18003. }
  18004. copy( source ) {
  18005. this.clearcoatNode = source.clearcoatNode;
  18006. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  18007. this.clearcoatNormalNode = source.clearcoatNormalNode;
  18008. this.sheenNode = source.sheenNode;
  18009. this.sheenRoughnessNode = source.sheenRoughnessNode;
  18010. this.iridescenceNode = source.iridescenceNode;
  18011. this.iridescenceIORNode = source.iridescenceIORNode;
  18012. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  18013. this.specularIntensityNode = source.specularIntensityNode;
  18014. this.specularColorNode = source.specularColorNode;
  18015. this.transmissionNode = source.transmissionNode;
  18016. this.thicknessNode = source.thicknessNode;
  18017. this.attenuationDistanceNode = source.attenuationDistanceNode;
  18018. this.attenuationColorNode = source.attenuationColorNode;
  18019. this.dispersionNode = source.dispersionNode;
  18020. this.anisotropyNode = source.anisotropyNode;
  18021. return super.copy( source );
  18022. }
  18023. }
  18024. /**
  18025. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  18026. *
  18027. * @augments PhysicalLightingModel
  18028. */
  18029. class SSSLightingModel extends PhysicalLightingModel {
  18030. /**
  18031. * Constructs a new physical lighting model.
  18032. *
  18033. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  18034. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  18035. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  18036. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  18037. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  18038. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  18039. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  18040. */
  18041. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  18042. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  18043. /**
  18044. * Whether the lighting model should use SSS or not.
  18045. *
  18046. * @type {boolean}
  18047. * @default false
  18048. */
  18049. this.useSSS = sss;
  18050. }
  18051. /**
  18052. * Extends the default implementation with a SSS term.
  18053. *
  18054. * 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/}
  18055. *
  18056. * @param {Object} input - The input data.
  18057. * @param {NodeBuilder} builder - The current node builder.
  18058. */
  18059. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18060. if ( this.useSSS === true ) {
  18061. const material = builder.material;
  18062. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  18063. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  18064. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  18065. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  18066. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  18067. }
  18068. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  18069. }
  18070. }
  18071. /**
  18072. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  18073. * that implements a Subsurface scattering (SSS) term.
  18074. *
  18075. * @augments MeshPhysicalNodeMaterial
  18076. */
  18077. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  18078. static get type() {
  18079. return 'MeshSSSNodeMaterial';
  18080. }
  18081. /**
  18082. * Constructs a new mesh SSS node material.
  18083. *
  18084. * @param {Object} [parameters] - The configuration parameter.
  18085. */
  18086. constructor( parameters ) {
  18087. super( parameters );
  18088. /**
  18089. * Represents the thickness color.
  18090. *
  18091. * @type {?Node<vec3>}
  18092. * @default null
  18093. */
  18094. this.thicknessColorNode = null;
  18095. /**
  18096. * Represents the distortion factor.
  18097. *
  18098. * @type {?Node<float>}
  18099. */
  18100. this.thicknessDistortionNode = float( 0.1 );
  18101. /**
  18102. * Represents the thickness ambient factor.
  18103. *
  18104. * @type {?Node<float>}
  18105. */
  18106. this.thicknessAmbientNode = float( 0.0 );
  18107. /**
  18108. * Represents the thickness attenuation.
  18109. *
  18110. * @type {?Node<float>}
  18111. */
  18112. this.thicknessAttenuationNode = float( .1 );
  18113. /**
  18114. * Represents the thickness power.
  18115. *
  18116. * @type {?Node<float>}
  18117. */
  18118. this.thicknessPowerNode = float( 2.0 );
  18119. /**
  18120. * Represents the thickness scale.
  18121. *
  18122. * @type {?Node<float>}
  18123. */
  18124. this.thicknessScaleNode = float( 10.0 );
  18125. }
  18126. /**
  18127. * Whether the lighting model should use SSS or not.
  18128. *
  18129. * @type {boolean}
  18130. * @default true
  18131. */
  18132. get useSSS() {
  18133. return this.thicknessColorNode !== null;
  18134. }
  18135. /**
  18136. * Setups the lighting model.
  18137. *
  18138. * @return {SSSLightingModel} The lighting model.
  18139. */
  18140. setupLightingModel( /*builder*/ ) {
  18141. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  18142. }
  18143. copy( source ) {
  18144. this.thicknessColorNode = source.thicknessColorNode;
  18145. this.thicknessDistortionNode = source.thicknessDistortionNode;
  18146. this.thicknessAmbientNode = source.thicknessAmbientNode;
  18147. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  18148. this.thicknessPowerNode = source.thicknessPowerNode;
  18149. this.thicknessScaleNode = source.thicknessScaleNode;
  18150. return super.copy( source );
  18151. }
  18152. }
  18153. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  18154. // dotNL will be from -1.0 to 1.0
  18155. const dotNL = normal.dot( lightDirection );
  18156. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  18157. if ( builder.material.gradientMap ) {
  18158. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  18159. return vec3( gradientMap.r );
  18160. } else {
  18161. const fw = coord.fwidth().mul( 0.5 );
  18162. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  18163. }
  18164. } );
  18165. /**
  18166. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  18167. *
  18168. * @augments LightingModel
  18169. */
  18170. class ToonLightingModel extends LightingModel {
  18171. /**
  18172. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  18173. * reduced to a small number of discrete shades to create a comic-like, flat look.
  18174. *
  18175. * @param {Object} lightData - The light data.
  18176. * @param {NodeBuilder} builder - The current node builder.
  18177. */
  18178. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18179. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  18180. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  18181. }
  18182. /**
  18183. * Implements the indirect lighting.
  18184. *
  18185. * @param {NodeBuilder} builder - The current node builder.
  18186. */
  18187. indirect( builder ) {
  18188. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  18189. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  18190. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  18191. }
  18192. }
  18193. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  18194. /**
  18195. * Node material version of {@link MeshToonMaterial}.
  18196. *
  18197. * @augments NodeMaterial
  18198. */
  18199. class MeshToonNodeMaterial extends NodeMaterial {
  18200. static get type() {
  18201. return 'MeshToonNodeMaterial';
  18202. }
  18203. /**
  18204. * Constructs a new mesh toon node material.
  18205. *
  18206. * @param {Object} [parameters] - The configuration parameter.
  18207. */
  18208. constructor( parameters ) {
  18209. super();
  18210. /**
  18211. * This flag can be used for type testing.
  18212. *
  18213. * @type {boolean}
  18214. * @readonly
  18215. * @default true
  18216. */
  18217. this.isMeshToonNodeMaterial = true;
  18218. /**
  18219. * Set to `true` because toon materials react on lights.
  18220. *
  18221. * @type {boolean}
  18222. * @default true
  18223. */
  18224. this.lights = true;
  18225. this.setDefaultValues( _defaultValues$4 );
  18226. this.setValues( parameters );
  18227. }
  18228. /**
  18229. * Setups the lighting model.
  18230. *
  18231. * @return {ToonLightingModel} The lighting model.
  18232. */
  18233. setupLightingModel( /*builder*/ ) {
  18234. return new ToonLightingModel();
  18235. }
  18236. }
  18237. /**
  18238. * TSL function for creating a matcap uv node.
  18239. *
  18240. * Can be used to compute texture coordinates for projecting a
  18241. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  18242. *
  18243. * @tsl
  18244. * @function
  18245. * @returns {Node<vec2>} The matcap UV coordinates.
  18246. */
  18247. const matcapUV = /*@__PURE__*/ Fn( () => {
  18248. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  18249. const y = positionViewDirection.cross( x );
  18250. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  18251. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  18252. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  18253. /**
  18254. * Node material version of {@link MeshMatcapMaterial}.
  18255. *
  18256. * @augments NodeMaterial
  18257. */
  18258. class MeshMatcapNodeMaterial extends NodeMaterial {
  18259. static get type() {
  18260. return 'MeshMatcapNodeMaterial';
  18261. }
  18262. /**
  18263. * Constructs a new mesh normal node material.
  18264. *
  18265. * @param {Object} [parameters] - The configuration parameter.
  18266. */
  18267. constructor( parameters ) {
  18268. super();
  18269. /**
  18270. * This flag can be used for type testing.
  18271. *
  18272. * @type {boolean}
  18273. * @readonly
  18274. * @default true
  18275. */
  18276. this.isMeshMatcapNodeMaterial = true;
  18277. this.setDefaultValues( _defaultValues$3 );
  18278. this.setValues( parameters );
  18279. }
  18280. /**
  18281. * Setups the matcap specific node variables.
  18282. *
  18283. * @param {NodeBuilder} builder - The current node builder.
  18284. */
  18285. setupVariants( builder ) {
  18286. const uv = matcapUV;
  18287. let matcapColor;
  18288. if ( builder.material.matcap ) {
  18289. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  18290. } else {
  18291. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  18292. }
  18293. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  18294. }
  18295. }
  18296. /**
  18297. * Applies a rotation to the given position node.
  18298. *
  18299. * @augments TempNode
  18300. */
  18301. class RotateNode extends TempNode {
  18302. static get type() {
  18303. return 'RotateNode';
  18304. }
  18305. /**
  18306. * Constructs a new rotate node.
  18307. *
  18308. * @param {Node} positionNode - The position node.
  18309. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18310. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18311. */
  18312. constructor( positionNode, rotationNode ) {
  18313. super();
  18314. /**
  18315. * The position node.
  18316. *
  18317. * @type {Node}
  18318. */
  18319. this.positionNode = positionNode;
  18320. /**
  18321. * Represents the rotation that is applied to the position node.
  18322. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18323. *
  18324. * @type {Node}
  18325. */
  18326. this.rotationNode = rotationNode;
  18327. }
  18328. /**
  18329. * The type of the {@link RotateNode#positionNode} defines the node's type.
  18330. *
  18331. * @param {NodeBuilder} builder - The current node builder.
  18332. * @return {string} The node's type.
  18333. */
  18334. getNodeType( builder ) {
  18335. return this.positionNode.getNodeType( builder );
  18336. }
  18337. setup( builder ) {
  18338. const { rotationNode, positionNode } = this;
  18339. const nodeType = this.getNodeType( builder );
  18340. if ( nodeType === 'vec2' ) {
  18341. const cosAngle = rotationNode.cos();
  18342. const sinAngle = rotationNode.sin();
  18343. const rotationMatrix = mat2(
  18344. cosAngle, sinAngle,
  18345. sinAngle.negate(), cosAngle
  18346. );
  18347. return rotationMatrix.mul( positionNode );
  18348. } else {
  18349. const rotation = rotationNode;
  18350. 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 ) );
  18351. 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 ) );
  18352. 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 ) );
  18353. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  18354. }
  18355. }
  18356. }
  18357. /**
  18358. * TSL function for creating a rotate node.
  18359. *
  18360. * @tsl
  18361. * @function
  18362. * @param {Node} positionNode - The position node.
  18363. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18364. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18365. * @returns {RotateNode}
  18366. */
  18367. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  18368. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  18369. /**
  18370. * Node material version of {@link SpriteMaterial}.
  18371. *
  18372. * @augments NodeMaterial
  18373. */
  18374. class SpriteNodeMaterial extends NodeMaterial {
  18375. static get type() {
  18376. return 'SpriteNodeMaterial';
  18377. }
  18378. /**
  18379. * Constructs a new sprite node material.
  18380. *
  18381. * @param {Object} [parameters] - The configuration parameter.
  18382. */
  18383. constructor( parameters ) {
  18384. super();
  18385. /**
  18386. * This flag can be used for type testing.
  18387. *
  18388. * @type {boolean}
  18389. * @readonly
  18390. * @default true
  18391. */
  18392. this.isSpriteNodeMaterial = true;
  18393. this._useSizeAttenuation = true;
  18394. /**
  18395. * This property makes it possible to define the position of the sprite with a
  18396. * node. That can be useful when the material is used with instanced rendering
  18397. * and node data are defined with an instanced attribute node:
  18398. * ```js
  18399. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  18400. * material.positionNode = instancedBufferAttribute( positionAttribute );
  18401. * ```
  18402. * Another possibility is to compute the instanced data with a compute shader:
  18403. * ```js
  18404. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  18405. * particleMaterial.positionNode = positionBuffer.toAttribute();
  18406. * ```
  18407. *
  18408. * @type {?Node<vec2>}
  18409. * @default null
  18410. */
  18411. this.positionNode = null;
  18412. /**
  18413. * The rotation of sprite materials is by default inferred from the `rotation`,
  18414. * property. This node property allows to overwrite the default and define
  18415. * the rotation with a node instead.
  18416. *
  18417. * If you don't want to overwrite the rotation but modify the existing
  18418. * value instead, use {@link materialRotation}.
  18419. *
  18420. * @type {?Node<float>}
  18421. * @default null
  18422. */
  18423. this.rotationNode = null;
  18424. /**
  18425. * This node property provides an additional way to scale sprites next to
  18426. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  18427. * is multiplied with the scale value of this node in the vertex shader.
  18428. *
  18429. * @type {?Node<vec2>}
  18430. * @default null
  18431. */
  18432. this.scaleNode = null;
  18433. /**
  18434. * In Sprites, the transparent property is enabled by default.
  18435. *
  18436. * @type {boolean}
  18437. * @default true
  18438. */
  18439. this.transparent = true;
  18440. this.setDefaultValues( _defaultValues$2 );
  18441. this.setValues( parameters );
  18442. }
  18443. /**
  18444. * Setups the position node in view space. This method implements
  18445. * the sprite specific vertex shader.
  18446. *
  18447. * @param {NodeBuilder} builder - The current node builder.
  18448. * @return {Node<vec3>} The position in view space.
  18449. */
  18450. setupPositionView( builder ) {
  18451. const { object, camera } = builder;
  18452. const sizeAttenuation = this.sizeAttenuation;
  18453. const { positionNode, rotationNode, scaleNode } = this;
  18454. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  18455. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  18456. if ( scaleNode !== null ) {
  18457. scale = scale.mul( vec2( scaleNode ) );
  18458. }
  18459. if ( sizeAttenuation === false ) {
  18460. if ( camera.isPerspectiveCamera ) {
  18461. scale = scale.mul( mvPosition.z.negate() );
  18462. } else {
  18463. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  18464. scale = scale.mul( orthoScale.mul( 2 ) );
  18465. }
  18466. }
  18467. let alignedPosition = positionGeometry.xy;
  18468. if ( object.center && object.center.isVector2 === true ) {
  18469. const center = reference$1( 'center', 'vec2', object );
  18470. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  18471. }
  18472. alignedPosition = alignedPosition.mul( scale );
  18473. const rotation = float( rotationNode || materialRotation );
  18474. const rotatedPosition = rotate( alignedPosition, rotation );
  18475. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  18476. }
  18477. copy( source ) {
  18478. this.positionNode = source.positionNode;
  18479. this.rotationNode = source.rotationNode;
  18480. this.scaleNode = source.scaleNode;
  18481. return super.copy( source );
  18482. }
  18483. /**
  18484. * Whether to use size attenuation or not.
  18485. *
  18486. * @type {boolean}
  18487. * @default true
  18488. */
  18489. get sizeAttenuation() {
  18490. return this._useSizeAttenuation;
  18491. }
  18492. set sizeAttenuation( value ) {
  18493. if ( this._useSizeAttenuation !== value ) {
  18494. this._useSizeAttenuation = value;
  18495. this.needsUpdate = true;
  18496. }
  18497. }
  18498. }
  18499. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  18500. /**
  18501. * Node material version of {@link PointsMaterial}.
  18502. *
  18503. * @augments SpriteNodeMaterial
  18504. */
  18505. class PointsNodeMaterial extends SpriteNodeMaterial {
  18506. static get type() {
  18507. return 'PointsNodeMaterial';
  18508. }
  18509. /**
  18510. * Constructs a new points node material.
  18511. *
  18512. * @param {Object} [parameters] - The configuration parameter.
  18513. */
  18514. constructor( parameters ) {
  18515. super();
  18516. /**
  18517. * This node property provides an additional way to set the point size.
  18518. *
  18519. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  18520. * this node has no effect when the material is used with {@link Points} and a WebGPU
  18521. * backend. If an application wants to render points with a size larger than 1 pixel,
  18522. * the material should be used with {@link Sprite} and instancing.
  18523. *
  18524. * @type {?Node<vec2>}
  18525. * @default null
  18526. */
  18527. this.sizeNode = null;
  18528. /**
  18529. * This flag can be used for type testing.
  18530. *
  18531. * @type {boolean}
  18532. * @readonly
  18533. * @default true
  18534. */
  18535. this.isPointsNodeMaterial = true;
  18536. this.setDefaultValues( _defaultValues$1 );
  18537. this.setValues( parameters );
  18538. }
  18539. setupPositionView() {
  18540. const { positionNode } = this;
  18541. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  18542. }
  18543. setupVertex( builder ) {
  18544. const mvp = super.setupVertex( builder );
  18545. // skip further processing if the material is not a node material
  18546. if ( builder.material.isNodeMaterial !== true ) {
  18547. return mvp;
  18548. }
  18549. // ndc space
  18550. const { rotationNode, scaleNode, sizeNode } = this;
  18551. const alignedPosition = positionGeometry.xy.toVar();
  18552. const aspect = viewport.z.div( viewport.w );
  18553. // rotation
  18554. if ( rotationNode && rotationNode.isNode ) {
  18555. const rotation = float( rotationNode );
  18556. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  18557. }
  18558. // point size
  18559. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  18560. if ( this.sizeAttenuation === true ) {
  18561. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  18562. }
  18563. // scale
  18564. if ( scaleNode && scaleNode.isNode ) {
  18565. pointSize = pointSize.mul( vec2( scaleNode ) );
  18566. }
  18567. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  18568. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  18569. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  18570. // back to clip space
  18571. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  18572. //clipPos.xy += offset;
  18573. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  18574. return mvp;
  18575. }
  18576. /**
  18577. * Whether alpha to coverage should be used or not.
  18578. *
  18579. * @type {boolean}
  18580. * @default true
  18581. */
  18582. get alphaToCoverage() {
  18583. return this._useAlphaToCoverage;
  18584. }
  18585. set alphaToCoverage( value ) {
  18586. if ( this._useAlphaToCoverage !== value ) {
  18587. this._useAlphaToCoverage = value;
  18588. this.needsUpdate = true;
  18589. }
  18590. }
  18591. }
  18592. /**
  18593. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  18594. *
  18595. * @augments LightingModel
  18596. */
  18597. class ShadowMaskModel extends LightingModel {
  18598. /**
  18599. * Constructs a new shadow mask model.
  18600. */
  18601. constructor() {
  18602. super();
  18603. /**
  18604. * The shadow mask node.
  18605. *
  18606. * @type {Node}
  18607. */
  18608. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  18609. }
  18610. /**
  18611. * Only used to save the shadow mask.
  18612. *
  18613. * @param {Object} input - The input data.
  18614. */
  18615. direct( { lightNode } ) {
  18616. if ( lightNode.shadowNode !== null ) {
  18617. this.shadowNode.mulAssign( lightNode.shadowNode );
  18618. }
  18619. }
  18620. /**
  18621. * Uses the shadow mask to produce the final color.
  18622. *
  18623. * @param {NodeBuilder} builder - The current node builder.
  18624. */
  18625. finish( { context } ) {
  18626. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  18627. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  18628. }
  18629. }
  18630. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  18631. /**
  18632. * Node material version of {@link ShadowMaterial}.
  18633. *
  18634. * @augments NodeMaterial
  18635. */
  18636. class ShadowNodeMaterial extends NodeMaterial {
  18637. static get type() {
  18638. return 'ShadowNodeMaterial';
  18639. }
  18640. /**
  18641. * Constructs a new shadow node material.
  18642. *
  18643. * @param {Object} [parameters] - The configuration parameter.
  18644. */
  18645. constructor( parameters ) {
  18646. super();
  18647. /**
  18648. * This flag can be used for type testing.
  18649. *
  18650. * @type {boolean}
  18651. * @readonly
  18652. * @default true
  18653. */
  18654. this.isShadowNodeMaterial = true;
  18655. /**
  18656. * Set to `true` because so it's possible to implement
  18657. * the shadow mask effect.
  18658. *
  18659. * @type {boolean}
  18660. * @default true
  18661. */
  18662. this.lights = true;
  18663. /**
  18664. * Overwritten since shadow materials are transparent
  18665. * by default.
  18666. *
  18667. * @type {boolean}
  18668. * @default true
  18669. */
  18670. this.transparent = true;
  18671. this.setDefaultValues( _defaultValues );
  18672. this.setValues( parameters );
  18673. }
  18674. /**
  18675. * Setups the lighting model.
  18676. *
  18677. * @return {ShadowMaskModel} The lighting model.
  18678. */
  18679. setupLightingModel( /*builder*/ ) {
  18680. return new ShadowMaskModel();
  18681. }
  18682. }
  18683. const scatteringDensity = property( 'vec3' );
  18684. const linearDepthRay = property( 'vec3' );
  18685. const outgoingRayLight = property( 'vec3' );
  18686. /**
  18687. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  18688. * This model calculates the scattering and transmittance of light through a volumetric medium.
  18689. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  18690. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  18691. *
  18692. * @augments LightingModel
  18693. */
  18694. class VolumetricLightingModel extends LightingModel {
  18695. constructor() {
  18696. super();
  18697. }
  18698. start( builder ) {
  18699. const { material, context } = builder;
  18700. const startPos = property( 'vec3' );
  18701. const endPos = property( 'vec3' );
  18702. // This approach dynamically changes the direction of the ray,
  18703. // 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.
  18704. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  18705. startPos.assign( cameraPosition );
  18706. endPos.assign( positionWorld );
  18707. } ).Else( () => {
  18708. startPos.assign( positionWorld );
  18709. endPos.assign( cameraPosition );
  18710. } );
  18711. //
  18712. const viewVector = endPos.sub( startPos );
  18713. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  18714. const stepSize = viewVector.length().div( steps ).toVar();
  18715. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  18716. const distTravelled = float( 0.0 ).toVar();
  18717. const transmittance = vec3( 1 ).toVar();
  18718. if ( material.offsetNode ) {
  18719. // reduce banding
  18720. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  18721. }
  18722. Loop( steps, () => {
  18723. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  18724. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  18725. if ( material.depthNode !== null ) {
  18726. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  18727. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  18728. }
  18729. context.positionWorld = positionRay;
  18730. context.shadowPositionWorld = positionRay;
  18731. context.positionView = positionViewRay;
  18732. scatteringDensity.assign( 0 );
  18733. let scatteringNode;
  18734. if ( material.scatteringNode ) {
  18735. scatteringNode = material.scatteringNode( {
  18736. positionRay
  18737. } );
  18738. }
  18739. super.start( builder );
  18740. if ( scatteringNode ) {
  18741. scatteringDensity.mulAssign( scatteringNode );
  18742. }
  18743. // beer's law
  18744. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  18745. transmittance.mulAssign( falloff );
  18746. // move along the ray
  18747. distTravelled.addAssign( stepSize );
  18748. } );
  18749. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  18750. }
  18751. scatteringLight( lightColor, builder ) {
  18752. const sceneDepthNode = builder.context.sceneDepthNode;
  18753. if ( sceneDepthNode ) {
  18754. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  18755. scatteringDensity.addAssign( lightColor );
  18756. } );
  18757. } else {
  18758. scatteringDensity.addAssign( lightColor );
  18759. }
  18760. }
  18761. direct( { lightNode, lightColor }, builder ) {
  18762. // Ignore lights with infinite distance
  18763. if ( lightNode.light.distance === undefined ) return;
  18764. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  18765. const directLight = lightColor.xyz.toVar();
  18766. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  18767. this.scatteringLight( directLight, builder );
  18768. }
  18769. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  18770. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  18771. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  18772. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  18773. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  18774. const P = builder.context.positionView;
  18775. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  18776. this.scatteringLight( directLight, builder );
  18777. }
  18778. finish( builder ) {
  18779. builder.context.outgoingLight.assign( outgoingRayLight );
  18780. }
  18781. }
  18782. /**
  18783. * Volume node material.
  18784. *
  18785. * @augments NodeMaterial
  18786. */
  18787. class VolumeNodeMaterial extends NodeMaterial {
  18788. static get type() {
  18789. return 'VolumeNodeMaterial';
  18790. }
  18791. /**
  18792. * Constructs a new volume node material.
  18793. *
  18794. * @param {Object} [parameters] - The configuration parameter.
  18795. */
  18796. constructor( parameters ) {
  18797. super();
  18798. /**
  18799. * This flag can be used for type testing.
  18800. *
  18801. * @type {boolean}
  18802. * @readonly
  18803. * @default true
  18804. */
  18805. this.isVolumeNodeMaterial = true;
  18806. /**
  18807. * Number of steps used for raymarching.
  18808. *
  18809. * @type {number}
  18810. * @default 25
  18811. */
  18812. this.steps = 25;
  18813. /**
  18814. * Offsets the distance a ray has been traveled through a volume.
  18815. * Can be used to implement dithering to reduce banding.
  18816. *
  18817. * @type {Node<float>}
  18818. * @default null
  18819. */
  18820. this.offsetNode = null;
  18821. /**
  18822. * Node used for scattering calculations.
  18823. *
  18824. * @type {Function|FunctionNode<vec4>}
  18825. * @default null
  18826. */
  18827. this.scatteringNode = null;
  18828. this.lights = true;
  18829. this.transparent = true;
  18830. this.side = BackSide;
  18831. this.depthTest = false;
  18832. this.depthWrite = false;
  18833. this.setValues( parameters );
  18834. }
  18835. setupLightingModel() {
  18836. return new VolumetricLightingModel();
  18837. }
  18838. }
  18839. /**
  18840. * This module manages the internal animation loop of the renderer.
  18841. *
  18842. * @private
  18843. */
  18844. class Animation {
  18845. /**
  18846. * Constructs a new animation loop management component.
  18847. *
  18848. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18849. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18850. */
  18851. constructor( nodes, info ) {
  18852. /**
  18853. * Renderer component for managing nodes related logic.
  18854. *
  18855. * @type {Nodes}
  18856. */
  18857. this.nodes = nodes;
  18858. /**
  18859. * Renderer component for managing metrics and monitoring data.
  18860. *
  18861. * @type {Info}
  18862. */
  18863. this.info = info;
  18864. /**
  18865. * A reference to the context from `requestAnimationFrame()` can
  18866. * be called (usually `window`).
  18867. *
  18868. * @type {?(Window|XRSession)}
  18869. */
  18870. this._context = typeof self !== 'undefined' ? self : null;
  18871. /**
  18872. * The user-defined animation loop.
  18873. *
  18874. * @type {?Function}
  18875. * @default null
  18876. */
  18877. this._animationLoop = null;
  18878. /**
  18879. * The requestId which is returned from the `requestAnimationFrame()` call.
  18880. * Can be used to cancel the stop the animation loop.
  18881. *
  18882. * @type {?number}
  18883. * @default null
  18884. */
  18885. this._requestId = null;
  18886. }
  18887. /**
  18888. * Starts the internal animation loop.
  18889. */
  18890. start() {
  18891. const update = ( time, xrFrame ) => {
  18892. this._requestId = this._context.requestAnimationFrame( update );
  18893. if ( this.info.autoReset === true ) this.info.reset();
  18894. this.nodes.nodeFrame.update();
  18895. this.info.frame = this.nodes.nodeFrame.frameId;
  18896. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  18897. };
  18898. update();
  18899. }
  18900. /**
  18901. * Stops the internal animation loop.
  18902. */
  18903. stop() {
  18904. this._context.cancelAnimationFrame( this._requestId );
  18905. this._requestId = null;
  18906. }
  18907. /**
  18908. * Returns the user-level animation loop.
  18909. *
  18910. * @return {?Function} The animation loop.
  18911. */
  18912. getAnimationLoop() {
  18913. return this._animationLoop;
  18914. }
  18915. /**
  18916. * Defines the user-level animation loop.
  18917. *
  18918. * @param {?Function} callback - The animation loop.
  18919. */
  18920. setAnimationLoop( callback ) {
  18921. this._animationLoop = callback;
  18922. }
  18923. /**
  18924. * Returns the animation context.
  18925. *
  18926. * @return {Window|XRSession} The animation context.
  18927. */
  18928. getContext() {
  18929. return this._context;
  18930. }
  18931. /**
  18932. * Defines the context in which `requestAnimationFrame()` is executed.
  18933. *
  18934. * @param {Window|XRSession} context - The context to set.
  18935. */
  18936. setContext( context ) {
  18937. this._context = context;
  18938. }
  18939. /**
  18940. * Frees all internal resources and stops the animation loop.
  18941. */
  18942. dispose() {
  18943. this.stop();
  18944. }
  18945. }
  18946. /**
  18947. * Data structure for the renderer. It allows defining values
  18948. * with chained, hierarchical keys. Keys are meant to be
  18949. * objects since the module internally works with Weak Maps
  18950. * for performance reasons.
  18951. *
  18952. * @private
  18953. */
  18954. class ChainMap {
  18955. /**
  18956. * Constructs a new Chain Map.
  18957. */
  18958. constructor() {
  18959. /**
  18960. * The root Weak Map.
  18961. *
  18962. * @type {WeakMap}
  18963. */
  18964. this.weakMap = new WeakMap();
  18965. }
  18966. /**
  18967. * Returns the value for the given array of keys.
  18968. *
  18969. * @param {Array<Object>} keys - List of keys.
  18970. * @return {any} The value. Returns `undefined` if no value was found.
  18971. */
  18972. get( keys ) {
  18973. let map = this.weakMap;
  18974. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18975. map = map.get( keys[ i ] );
  18976. if ( map === undefined ) return undefined;
  18977. }
  18978. return map.get( keys[ keys.length - 1 ] );
  18979. }
  18980. /**
  18981. * Sets the value for the given keys.
  18982. *
  18983. * @param {Array<Object>} keys - List of keys.
  18984. * @param {any} value - The value to set.
  18985. * @return {ChainMap} A reference to this Chain Map.
  18986. */
  18987. set( keys, value ) {
  18988. let map = this.weakMap;
  18989. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18990. const key = keys[ i ];
  18991. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  18992. map = map.get( key );
  18993. }
  18994. map.set( keys[ keys.length - 1 ], value );
  18995. return this;
  18996. }
  18997. /**
  18998. * Deletes a value for the given keys.
  18999. *
  19000. * @param {Array<Object>} keys - The keys.
  19001. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  19002. */
  19003. delete( keys ) {
  19004. let map = this.weakMap;
  19005. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19006. map = map.get( keys[ i ] );
  19007. if ( map === undefined ) return false;
  19008. }
  19009. return map.delete( keys[ keys.length - 1 ] );
  19010. }
  19011. }
  19012. let _id$9 = 0;
  19013. function getKeys( obj ) {
  19014. const keys = Object.keys( obj );
  19015. let proto = Object.getPrototypeOf( obj );
  19016. while ( proto ) {
  19017. const descriptors = Object.getOwnPropertyDescriptors( proto );
  19018. for ( const key in descriptors ) {
  19019. if ( descriptors[ key ] !== undefined ) {
  19020. const descriptor = descriptors[ key ];
  19021. if ( descriptor && typeof descriptor.get === 'function' ) {
  19022. keys.push( key );
  19023. }
  19024. }
  19025. }
  19026. proto = Object.getPrototypeOf( proto );
  19027. }
  19028. return keys;
  19029. }
  19030. /**
  19031. * A render object is the renderer's representation of single entity that gets drawn
  19032. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  19033. * scene since render objects also depend from the used material, the current render context
  19034. * and the current scene's lighting.
  19035. *
  19036. * In general, the basic process of the renderer is:
  19037. *
  19038. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  19039. * - Process the render lists by calling one or more render commands for each render item.
  19040. * - For each render command, request a render object and perform the draw.
  19041. *
  19042. * The module provides an interface to get data required for the draw command like the actual
  19043. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  19044. * creating render objects should only be done when necessary.
  19045. *
  19046. * @private
  19047. */
  19048. class RenderObject {
  19049. /**
  19050. * Constructs a new render object.
  19051. *
  19052. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19053. * @param {Geometries} geometries - Renderer component for managing geometries.
  19054. * @param {Renderer} renderer - The renderer.
  19055. * @param {Object3D} object - The 3D object.
  19056. * @param {Material} material - The 3D object's material.
  19057. * @param {Scene} scene - The scene the 3D object belongs to.
  19058. * @param {Camera} camera - The camera the object should be rendered with.
  19059. * @param {LightsNode} lightsNode - The lights node.
  19060. * @param {RenderContext} renderContext - The render context.
  19061. * @param {ClippingContext} clippingContext - The clipping context.
  19062. */
  19063. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  19064. this.id = _id$9 ++;
  19065. /**
  19066. * Renderer component for managing nodes related logic.
  19067. *
  19068. * @type {Nodes}
  19069. * @private
  19070. */
  19071. this._nodes = nodes;
  19072. /**
  19073. * Renderer component for managing geometries.
  19074. *
  19075. * @type {Geometries}
  19076. * @private
  19077. */
  19078. this._geometries = geometries;
  19079. /**
  19080. * The renderer.
  19081. *
  19082. * @type {Renderer}
  19083. */
  19084. this.renderer = renderer;
  19085. /**
  19086. * The 3D object.
  19087. *
  19088. * @type {Object3D}
  19089. */
  19090. this.object = object;
  19091. /**
  19092. * The 3D object's material.
  19093. *
  19094. * @type {Material}
  19095. */
  19096. this.material = material;
  19097. /**
  19098. * The scene the 3D object belongs to.
  19099. *
  19100. * @type {Scene}
  19101. */
  19102. this.scene = scene;
  19103. /**
  19104. * The camera the 3D object should be rendered with.
  19105. *
  19106. * @type {Camera}
  19107. */
  19108. this.camera = camera;
  19109. /**
  19110. * The lights node.
  19111. *
  19112. * @type {LightsNode}
  19113. */
  19114. this.lightsNode = lightsNode;
  19115. /**
  19116. * The render context.
  19117. *
  19118. * @type {RenderContext}
  19119. */
  19120. this.context = renderContext;
  19121. /**
  19122. * The 3D object's geometry.
  19123. *
  19124. * @type {BufferGeometry}
  19125. */
  19126. this.geometry = object.geometry;
  19127. /**
  19128. * The render object's version.
  19129. *
  19130. * @type {number}
  19131. */
  19132. this.version = material.version;
  19133. /**
  19134. * The draw range of the geometry.
  19135. *
  19136. * @type {?Object}
  19137. * @default null
  19138. */
  19139. this.drawRange = null;
  19140. /**
  19141. * An array holding the buffer attributes
  19142. * of the render object. This entails attribute
  19143. * definitions on geometry and node level.
  19144. *
  19145. * @type {?Array<BufferAttribute>}
  19146. * @default null
  19147. */
  19148. this.attributes = null;
  19149. /**
  19150. * An object holding the version of the
  19151. * attributes. The keys are the attribute names
  19152. * and the values are the attribute versions.
  19153. *
  19154. * @type {?Object<string, number>}
  19155. * @default null
  19156. */
  19157. this.attributesId = null;
  19158. /**
  19159. * A reference to a render pipeline the render
  19160. * object is processed with.
  19161. *
  19162. * @type {RenderPipeline}
  19163. * @default null
  19164. */
  19165. this.pipeline = null;
  19166. /**
  19167. * Only relevant for objects using
  19168. * multiple materials. This represents a group entry
  19169. * from the respective `BufferGeometry`.
  19170. *
  19171. * @type {?{start: number, count: number}}
  19172. * @default null
  19173. */
  19174. this.group = null;
  19175. /**
  19176. * An array holding the vertex buffers which can
  19177. * be buffer attributes but also interleaved buffers.
  19178. *
  19179. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  19180. * @default null
  19181. */
  19182. this.vertexBuffers = null;
  19183. /**
  19184. * The parameters for the draw command.
  19185. *
  19186. * @type {?Object}
  19187. * @default null
  19188. */
  19189. this.drawParams = null;
  19190. /**
  19191. * If this render object is used inside a render bundle,
  19192. * this property points to the respective bundle group.
  19193. *
  19194. * @type {?BundleGroup}
  19195. * @default null
  19196. */
  19197. this.bundle = null;
  19198. /**
  19199. * The clipping context.
  19200. *
  19201. * @type {ClippingContext}
  19202. */
  19203. this.clippingContext = clippingContext;
  19204. /**
  19205. * The clipping context's cache key.
  19206. *
  19207. * @type {string}
  19208. */
  19209. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  19210. /**
  19211. * The initial node cache key.
  19212. *
  19213. * @type {number}
  19214. */
  19215. this.initialNodesCacheKey = this.getDynamicCacheKey();
  19216. /**
  19217. * The initial cache key.
  19218. *
  19219. * @type {number}
  19220. */
  19221. this.initialCacheKey = this.getCacheKey();
  19222. /**
  19223. * The node builder state.
  19224. *
  19225. * @type {?NodeBuilderState}
  19226. * @private
  19227. * @default null
  19228. */
  19229. this._nodeBuilderState = null;
  19230. /**
  19231. * An array of bindings.
  19232. *
  19233. * @type {?Array<BindGroup>}
  19234. * @private
  19235. * @default null
  19236. */
  19237. this._bindings = null;
  19238. /**
  19239. * Reference to the node material observer.
  19240. *
  19241. * @type {?NodeMaterialObserver}
  19242. * @private
  19243. * @default null
  19244. */
  19245. this._monitor = null;
  19246. /**
  19247. * An event listener which is defined by `RenderObjects`. It performs
  19248. * clean up tasks when `dispose()` on this render object.
  19249. *
  19250. * @method
  19251. */
  19252. this.onDispose = null;
  19253. /**
  19254. * This flag can be used for type testing.
  19255. *
  19256. * @type {boolean}
  19257. * @readonly
  19258. * @default true
  19259. */
  19260. this.isRenderObject = true;
  19261. /**
  19262. * An event listener which is executed when `dispose()` is called on
  19263. * the material of this render object.
  19264. *
  19265. * @method
  19266. */
  19267. this.onMaterialDispose = () => {
  19268. this.dispose();
  19269. };
  19270. /**
  19271. * An event listener which is executed when `dispose()` is called on
  19272. * the geometry of this render object.
  19273. *
  19274. * @method
  19275. */
  19276. this.onGeometryDispose = () => {
  19277. // clear geometry cache attributes
  19278. this.attributes = null;
  19279. this.attributesId = null;
  19280. };
  19281. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  19282. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  19283. }
  19284. /**
  19285. * Updates the clipping context.
  19286. *
  19287. * @param {ClippingContext} context - The clipping context to set.
  19288. */
  19289. updateClipping( context ) {
  19290. this.clippingContext = context;
  19291. }
  19292. /**
  19293. * Whether the clipping requires an update or not.
  19294. *
  19295. * @type {boolean}
  19296. * @readonly
  19297. */
  19298. get clippingNeedsUpdate() {
  19299. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  19300. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  19301. return true;
  19302. }
  19303. /**
  19304. * The number of clipping planes defined in context of hardware clipping.
  19305. *
  19306. * @type {number}
  19307. * @readonly
  19308. */
  19309. get hardwareClippingPlanes() {
  19310. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  19311. }
  19312. /**
  19313. * Returns the node builder state of this render object.
  19314. *
  19315. * @return {NodeBuilderState} The node builder state.
  19316. */
  19317. getNodeBuilderState() {
  19318. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  19319. }
  19320. /**
  19321. * Returns the node material observer of this render object.
  19322. *
  19323. * @return {NodeMaterialObserver} The node material observer.
  19324. */
  19325. getMonitor() {
  19326. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  19327. }
  19328. /**
  19329. * Returns an array of bind groups of this render object.
  19330. *
  19331. * @return {Array<BindGroup>} The bindings.
  19332. */
  19333. getBindings() {
  19334. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  19335. }
  19336. /**
  19337. * Returns a binding group by group name of this render object.
  19338. *
  19339. * @param {string} name - The name of the binding group.
  19340. * @return {?BindGroup} The bindings.
  19341. */
  19342. getBindingGroup( name ) {
  19343. for ( const bindingGroup of this.getBindings() ) {
  19344. if ( bindingGroup.name === name ) {
  19345. return bindingGroup;
  19346. }
  19347. }
  19348. }
  19349. /**
  19350. * Returns the index of the render object's geometry.
  19351. *
  19352. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  19353. */
  19354. getIndex() {
  19355. return this._geometries.getIndex( this );
  19356. }
  19357. /**
  19358. * Returns the indirect buffer attribute.
  19359. *
  19360. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  19361. */
  19362. getIndirect() {
  19363. return this._geometries.getIndirect( this );
  19364. }
  19365. /**
  19366. * Returns an array that acts as a key for identifying the render object in a chain map.
  19367. *
  19368. * @return {Array<Object>} An array with object references.
  19369. */
  19370. getChainArray() {
  19371. return [ this.object, this.material, this.context, this.lightsNode ];
  19372. }
  19373. /**
  19374. * This method is used when the geometry of a 3D object has been exchanged and the
  19375. * respective render object now requires an update.
  19376. *
  19377. * @param {BufferGeometry} geometry - The geometry to set.
  19378. */
  19379. setGeometry( geometry ) {
  19380. this.geometry = geometry;
  19381. this.attributes = null;
  19382. this.attributesId = null;
  19383. }
  19384. /**
  19385. * Returns the buffer attributes of the render object. The returned array holds
  19386. * attribute definitions on geometry and node level.
  19387. *
  19388. * @return {Array<BufferAttribute>} An array with buffer attributes.
  19389. */
  19390. getAttributes() {
  19391. if ( this.attributes !== null ) return this.attributes;
  19392. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  19393. const geometry = this.geometry;
  19394. const attributes = [];
  19395. const vertexBuffers = new Set();
  19396. const attributesId = {};
  19397. for ( const nodeAttribute of nodeAttributes ) {
  19398. let attribute;
  19399. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  19400. // node attribute
  19401. attribute = nodeAttribute.node.attribute;
  19402. } else {
  19403. // geometry attribute
  19404. attribute = geometry.getAttribute( nodeAttribute.name );
  19405. attributesId[ nodeAttribute.name ] = attribute.version;
  19406. }
  19407. if ( attribute === undefined ) continue;
  19408. attributes.push( attribute );
  19409. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  19410. vertexBuffers.add( bufferAttribute );
  19411. }
  19412. this.attributes = attributes;
  19413. this.attributesId = attributesId;
  19414. this.vertexBuffers = Array.from( vertexBuffers.values() );
  19415. return attributes;
  19416. }
  19417. /**
  19418. * Returns the vertex buffers of the render object.
  19419. *
  19420. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  19421. */
  19422. getVertexBuffers() {
  19423. if ( this.vertexBuffers === null ) this.getAttributes();
  19424. return this.vertexBuffers;
  19425. }
  19426. /**
  19427. * Returns the draw parameters for the render object.
  19428. *
  19429. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  19430. */
  19431. getDrawParameters() {
  19432. const { object, material, geometry, group, drawRange } = this;
  19433. const drawParams = this.drawParams || ( this.drawParams = {
  19434. vertexCount: 0,
  19435. firstVertex: 0,
  19436. instanceCount: 0,
  19437. firstInstance: 0
  19438. } );
  19439. const index = this.getIndex();
  19440. const hasIndex = ( index !== null );
  19441. let instanceCount = 1;
  19442. if ( geometry.isInstancedBufferGeometry === true ) {
  19443. instanceCount = geometry.instanceCount;
  19444. } else if ( object.count !== undefined ) {
  19445. instanceCount = Math.max( 0, object.count );
  19446. }
  19447. if ( instanceCount === 0 ) return null;
  19448. drawParams.instanceCount = instanceCount;
  19449. if ( object.isBatchedMesh === true ) return drawParams;
  19450. let rangeFactor = 1;
  19451. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  19452. rangeFactor = 2;
  19453. }
  19454. let firstVertex = drawRange.start * rangeFactor;
  19455. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  19456. if ( group !== null ) {
  19457. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  19458. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  19459. }
  19460. const position = geometry.attributes.position;
  19461. let itemCount = Infinity;
  19462. if ( hasIndex ) {
  19463. itemCount = index.count;
  19464. } else if ( position !== undefined && position !== null ) {
  19465. itemCount = position.count;
  19466. }
  19467. firstVertex = Math.max( firstVertex, 0 );
  19468. lastVertex = Math.min( lastVertex, itemCount );
  19469. const count = lastVertex - firstVertex;
  19470. if ( count < 0 || count === Infinity ) return null;
  19471. drawParams.vertexCount = count;
  19472. drawParams.firstVertex = firstVertex;
  19473. return drawParams;
  19474. }
  19475. /**
  19476. * Returns the render object's geometry cache key.
  19477. *
  19478. * The geometry cache key is part of the material cache key.
  19479. *
  19480. * @return {string} The geometry cache key.
  19481. */
  19482. getGeometryCacheKey() {
  19483. const { geometry } = this;
  19484. let cacheKey = '';
  19485. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  19486. const attribute = geometry.attributes[ name ];
  19487. cacheKey += name + ',';
  19488. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  19489. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  19490. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  19491. if ( attribute.normalized ) cacheKey += 'n,';
  19492. }
  19493. // structural equality isn't sufficient for morph targets since the
  19494. // data are maintained in textures. only if the targets are all equal
  19495. // the texture and thus the instance of `MorphNode` can be shared.
  19496. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  19497. const targets = geometry.morphAttributes[ name ];
  19498. cacheKey += 'morph-' + name + ',';
  19499. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  19500. const attribute = targets[ i ];
  19501. cacheKey += attribute.id + ',';
  19502. }
  19503. }
  19504. if ( geometry.index ) {
  19505. cacheKey += 'index,';
  19506. }
  19507. return cacheKey;
  19508. }
  19509. /**
  19510. * Returns the render object's material cache key.
  19511. *
  19512. * The material cache key is part of the render object cache key.
  19513. *
  19514. * @return {number} The material cache key.
  19515. */
  19516. getMaterialCacheKey() {
  19517. const { object, material } = this;
  19518. let cacheKey = material.customProgramCacheKey();
  19519. for ( const property of getKeys( material ) ) {
  19520. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  19521. const value = material[ property ];
  19522. let valueKey;
  19523. if ( value !== null ) {
  19524. // some material values require a formatting
  19525. const type = typeof value;
  19526. if ( type === 'number' ) {
  19527. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  19528. } else if ( type === 'object' ) {
  19529. valueKey = '{';
  19530. if ( value.isTexture ) {
  19531. valueKey += value.mapping;
  19532. }
  19533. valueKey += '}';
  19534. } else {
  19535. valueKey = String( value );
  19536. }
  19537. } else {
  19538. valueKey = String( value );
  19539. }
  19540. cacheKey += /*property + ':' +*/ valueKey + ',';
  19541. }
  19542. cacheKey += this.clippingContextCacheKey + ',';
  19543. if ( object.geometry ) {
  19544. cacheKey += this.getGeometryCacheKey();
  19545. }
  19546. if ( object.skeleton ) {
  19547. cacheKey += object.skeleton.bones.length + ',';
  19548. }
  19549. if ( object.isBatchedMesh ) {
  19550. cacheKey += object._matricesTexture.uuid + ',';
  19551. if ( object._colorsTexture !== null ) {
  19552. cacheKey += object._colorsTexture.uuid + ',';
  19553. }
  19554. }
  19555. if ( object.count > 1 ) {
  19556. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  19557. cacheKey += object.uuid + ',';
  19558. }
  19559. cacheKey += object.receiveShadow + ',';
  19560. return hashString( cacheKey );
  19561. }
  19562. /**
  19563. * Whether the geometry requires an update or not.
  19564. *
  19565. * @type {boolean}
  19566. * @readonly
  19567. */
  19568. get needsGeometryUpdate() {
  19569. if ( this.geometry.id !== this.object.geometry.id ) return true;
  19570. if ( this.attributes !== null ) {
  19571. const attributesId = this.attributesId;
  19572. for ( const name in attributesId ) {
  19573. const attribute = this.geometry.getAttribute( name );
  19574. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  19575. return true;
  19576. }
  19577. }
  19578. }
  19579. return false;
  19580. }
  19581. /**
  19582. * Whether the render object requires an update or not.
  19583. *
  19584. * Note: There are two distinct places where render objects are checked for an update.
  19585. *
  19586. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  19587. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  19588. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  19589. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  19590. * a need for a refresh due to material, geometry or object related value changes.
  19591. *
  19592. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  19593. * that performs the 'needsUpdate' check.
  19594. *
  19595. * @type {boolean}
  19596. * @readonly
  19597. */
  19598. get needsUpdate() {
  19599. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  19600. }
  19601. /**
  19602. * Returns the dynamic cache key which represents a key that is computed per draw command.
  19603. *
  19604. * @return {number} The cache key.
  19605. */
  19606. getDynamicCacheKey() {
  19607. let cacheKey = 0;
  19608. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  19609. // the renderer is inside a shadow pass.
  19610. if ( this.material.isShadowPassMaterial !== true ) {
  19611. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  19612. }
  19613. if ( this.camera.isArrayCamera ) {
  19614. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  19615. }
  19616. if ( this.object.receiveShadow ) {
  19617. cacheKey = hash$1( cacheKey, 1 );
  19618. }
  19619. return cacheKey;
  19620. }
  19621. /**
  19622. * Returns the render object's cache key.
  19623. *
  19624. * @return {number} The cache key.
  19625. */
  19626. getCacheKey() {
  19627. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  19628. }
  19629. /**
  19630. * Frees internal resources.
  19631. */
  19632. dispose() {
  19633. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  19634. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  19635. this.onDispose();
  19636. }
  19637. }
  19638. const _chainKeys$5 = [];
  19639. /**
  19640. * This module manages the render objects of the renderer.
  19641. *
  19642. * @private
  19643. */
  19644. class RenderObjects {
  19645. /**
  19646. * Constructs a new render object management component.
  19647. *
  19648. * @param {Renderer} renderer - The renderer.
  19649. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19650. * @param {Geometries} geometries - Renderer component for managing geometries.
  19651. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  19652. * @param {Bindings} bindings - Renderer component for managing bindings.
  19653. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19654. */
  19655. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  19656. /**
  19657. * The renderer.
  19658. *
  19659. * @type {Renderer}
  19660. */
  19661. this.renderer = renderer;
  19662. /**
  19663. * Renderer component for managing nodes related logic.
  19664. *
  19665. * @type {Nodes}
  19666. */
  19667. this.nodes = nodes;
  19668. /**
  19669. * Renderer component for managing geometries.
  19670. *
  19671. * @type {Geometries}
  19672. */
  19673. this.geometries = geometries;
  19674. /**
  19675. * Renderer component for managing pipelines.
  19676. *
  19677. * @type {Pipelines}
  19678. */
  19679. this.pipelines = pipelines;
  19680. /**
  19681. * Renderer component for managing bindings.
  19682. *
  19683. * @type {Bindings}
  19684. */
  19685. this.bindings = bindings;
  19686. /**
  19687. * Renderer component for managing metrics and monitoring data.
  19688. *
  19689. * @type {Info}
  19690. */
  19691. this.info = info;
  19692. /**
  19693. * A dictionary that manages render contexts in chain maps
  19694. * for each pass ID.
  19695. *
  19696. * @type {Object<string,ChainMap>}
  19697. */
  19698. this.chainMaps = {};
  19699. }
  19700. /**
  19701. * Returns a render object for the given object and state data.
  19702. *
  19703. * @param {Object3D} object - The 3D object.
  19704. * @param {Material} material - The 3D object's material.
  19705. * @param {Scene} scene - The scene the 3D object belongs to.
  19706. * @param {Camera} camera - The camera the 3D object should be rendered with.
  19707. * @param {LightsNode} lightsNode - The lights node.
  19708. * @param {RenderContext} renderContext - The render context.
  19709. * @param {ClippingContext} clippingContext - The clipping context.
  19710. * @param {string} [passId] - An optional ID for identifying the pass.
  19711. * @return {RenderObject} The render object.
  19712. */
  19713. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  19714. const chainMap = this.getChainMap( passId );
  19715. // reuse chainArray
  19716. _chainKeys$5[ 0 ] = object;
  19717. _chainKeys$5[ 1 ] = material;
  19718. _chainKeys$5[ 2 ] = renderContext;
  19719. _chainKeys$5[ 3 ] = lightsNode;
  19720. let renderObject = chainMap.get( _chainKeys$5 );
  19721. if ( renderObject === undefined ) {
  19722. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  19723. chainMap.set( _chainKeys$5, renderObject );
  19724. } else {
  19725. renderObject.updateClipping( clippingContext );
  19726. if ( renderObject.needsGeometryUpdate ) {
  19727. renderObject.setGeometry( object.geometry );
  19728. }
  19729. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  19730. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  19731. renderObject.dispose();
  19732. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  19733. } else {
  19734. renderObject.version = material.version;
  19735. }
  19736. }
  19737. }
  19738. _chainKeys$5.length = 0;
  19739. return renderObject;
  19740. }
  19741. /**
  19742. * Returns a chain map for the given pass ID.
  19743. *
  19744. * @param {string} [passId='default'] - The pass ID.
  19745. * @return {ChainMap} The chain map.
  19746. */
  19747. getChainMap( passId = 'default' ) {
  19748. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  19749. }
  19750. /**
  19751. * Frees internal resources.
  19752. */
  19753. dispose() {
  19754. this.chainMaps = {};
  19755. }
  19756. /**
  19757. * Factory method for creating render objects with the given list of parameters.
  19758. *
  19759. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19760. * @param {Geometries} geometries - Renderer component for managing geometries.
  19761. * @param {Renderer} renderer - The renderer.
  19762. * @param {Object3D} object - The 3D object.
  19763. * @param {Material} material - The object's material.
  19764. * @param {Scene} scene - The scene the 3D object belongs to.
  19765. * @param {Camera} camera - The camera the object should be rendered with.
  19766. * @param {LightsNode} lightsNode - The lights node.
  19767. * @param {RenderContext} renderContext - The render context.
  19768. * @param {ClippingContext} clippingContext - The clipping context.
  19769. * @param {string} [passId] - An optional ID for identifying the pass.
  19770. * @return {RenderObject} The render object.
  19771. */
  19772. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  19773. const chainMap = this.getChainMap( passId );
  19774. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  19775. renderObject.onDispose = () => {
  19776. this.pipelines.delete( renderObject );
  19777. this.bindings.delete( renderObject );
  19778. this.nodes.delete( renderObject );
  19779. chainMap.delete( renderObject.getChainArray() );
  19780. };
  19781. return renderObject;
  19782. }
  19783. }
  19784. /**
  19785. * Data structure for the renderer. It is intended to manage
  19786. * data of objects in dictionaries.
  19787. *
  19788. * @private
  19789. */
  19790. class DataMap {
  19791. /**
  19792. * Constructs a new data map.
  19793. */
  19794. constructor() {
  19795. /**
  19796. * `DataMap` internally uses a weak map
  19797. * to manage its data.
  19798. *
  19799. * @type {WeakMap}
  19800. */
  19801. this.data = new WeakMap();
  19802. }
  19803. /**
  19804. * Returns the dictionary for the given object.
  19805. *
  19806. * @param {Object} object - The object.
  19807. * @return {Object} The dictionary.
  19808. */
  19809. get( object ) {
  19810. let map = this.data.get( object );
  19811. if ( map === undefined ) {
  19812. map = {};
  19813. this.data.set( object, map );
  19814. }
  19815. return map;
  19816. }
  19817. /**
  19818. * Deletes the dictionary for the given object.
  19819. *
  19820. * @param {Object} object - The object.
  19821. * @return {?Object} The deleted dictionary.
  19822. */
  19823. delete( object ) {
  19824. let map = null;
  19825. if ( this.data.has( object ) ) {
  19826. map = this.data.get( object );
  19827. this.data.delete( object );
  19828. }
  19829. return map;
  19830. }
  19831. /**
  19832. * Returns `true` if the given object has a dictionary defined.
  19833. *
  19834. * @param {Object} object - The object to test.
  19835. * @return {boolean} Whether a dictionary is defined or not.
  19836. */
  19837. has( object ) {
  19838. return this.data.has( object );
  19839. }
  19840. /**
  19841. * Frees internal resources.
  19842. */
  19843. dispose() {
  19844. this.data = new WeakMap();
  19845. }
  19846. }
  19847. const AttributeType = {
  19848. VERTEX: 1,
  19849. INDEX: 2,
  19850. STORAGE: 3,
  19851. INDIRECT: 4
  19852. };
  19853. // size of a chunk in bytes (STD140 layout)
  19854. const GPU_CHUNK_BYTES = 16;
  19855. // @TODO: Move to src/constants.js
  19856. const BlendColorFactor = 211;
  19857. const OneMinusBlendColorFactor = 212;
  19858. /**
  19859. * This renderer module manages geometry attributes.
  19860. *
  19861. * @private
  19862. * @augments DataMap
  19863. */
  19864. class Attributes extends DataMap {
  19865. /**
  19866. * Constructs a new attribute management component.
  19867. *
  19868. * @param {Backend} backend - The renderer's backend.
  19869. */
  19870. constructor( backend ) {
  19871. super();
  19872. /**
  19873. * The renderer's backend.
  19874. *
  19875. * @type {Backend}
  19876. */
  19877. this.backend = backend;
  19878. }
  19879. /**
  19880. * Deletes the data for the given attribute.
  19881. *
  19882. * @param {BufferAttribute} attribute - The attribute.
  19883. * @return {Object|null} The deleted attribute data.
  19884. */
  19885. delete( attribute ) {
  19886. const attributeData = super.delete( attribute );
  19887. if ( attributeData !== null ) {
  19888. this.backend.destroyAttribute( attribute );
  19889. }
  19890. return attributeData;
  19891. }
  19892. /**
  19893. * Updates the given attribute. This method creates attribute buffers
  19894. * for new attributes and updates data for existing ones.
  19895. *
  19896. * @param {BufferAttribute} attribute - The attribute to update.
  19897. * @param {number} type - The attribute type.
  19898. */
  19899. update( attribute, type ) {
  19900. const data = this.get( attribute );
  19901. if ( data.version === undefined ) {
  19902. if ( type === AttributeType.VERTEX ) {
  19903. this.backend.createAttribute( attribute );
  19904. } else if ( type === AttributeType.INDEX ) {
  19905. this.backend.createIndexAttribute( attribute );
  19906. } else if ( type === AttributeType.STORAGE ) {
  19907. this.backend.createStorageAttribute( attribute );
  19908. } else if ( type === AttributeType.INDIRECT ) {
  19909. this.backend.createIndirectStorageAttribute( attribute );
  19910. }
  19911. data.version = this._getBufferAttribute( attribute ).version;
  19912. } else {
  19913. const bufferAttribute = this._getBufferAttribute( attribute );
  19914. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  19915. this.backend.updateAttribute( attribute );
  19916. data.version = bufferAttribute.version;
  19917. }
  19918. }
  19919. }
  19920. /**
  19921. * Utility method for handling interleaved buffer attributes correctly.
  19922. * To process them, their `InterleavedBuffer` is returned.
  19923. *
  19924. * @param {BufferAttribute} attribute - The attribute.
  19925. * @return {BufferAttribute|InterleavedBuffer}
  19926. */
  19927. _getBufferAttribute( attribute ) {
  19928. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  19929. return attribute;
  19930. }
  19931. }
  19932. /**
  19933. * Returns the wireframe version for the given geometry.
  19934. *
  19935. * @private
  19936. * @function
  19937. * @param {BufferGeometry} geometry - The geometry.
  19938. * @return {number} The version.
  19939. */
  19940. function getWireframeVersion( geometry ) {
  19941. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  19942. }
  19943. /**
  19944. * Returns a wireframe index attribute for the given geometry.
  19945. *
  19946. * @private
  19947. * @function
  19948. * @param {BufferGeometry} geometry - The geometry.
  19949. * @return {BufferAttribute} The wireframe index attribute.
  19950. */
  19951. function getWireframeIndex( geometry ) {
  19952. const indices = [];
  19953. const geometryIndex = geometry.index;
  19954. const geometryPosition = geometry.attributes.position;
  19955. if ( geometryIndex !== null ) {
  19956. const array = geometryIndex.array;
  19957. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  19958. const a = array[ i + 0 ];
  19959. const b = array[ i + 1 ];
  19960. const c = array[ i + 2 ];
  19961. indices.push( a, b, b, c, c, a );
  19962. }
  19963. } else {
  19964. const array = geometryPosition.array;
  19965. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  19966. const a = i + 0;
  19967. const b = i + 1;
  19968. const c = i + 2;
  19969. indices.push( a, b, b, c, c, a );
  19970. }
  19971. }
  19972. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  19973. attribute.version = getWireframeVersion( geometry );
  19974. return attribute;
  19975. }
  19976. /**
  19977. * This renderer module manages geometries.
  19978. *
  19979. * @private
  19980. * @augments DataMap
  19981. */
  19982. class Geometries extends DataMap {
  19983. /**
  19984. * Constructs a new geometry management component.
  19985. *
  19986. * @param {Attributes} attributes - Renderer component for managing attributes.
  19987. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19988. */
  19989. constructor( attributes, info ) {
  19990. super();
  19991. /**
  19992. * Renderer component for managing attributes.
  19993. *
  19994. * @type {Attributes}
  19995. */
  19996. this.attributes = attributes;
  19997. /**
  19998. * Renderer component for managing metrics and monitoring data.
  19999. *
  20000. * @type {Info}
  20001. */
  20002. this.info = info;
  20003. /**
  20004. * Weak Map for managing attributes for wireframe rendering.
  20005. *
  20006. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  20007. */
  20008. this.wireframes = new WeakMap();
  20009. /**
  20010. * This Weak Map is used to make sure buffer attributes are
  20011. * updated only once per render call.
  20012. *
  20013. * @type {WeakMap<BufferAttribute,number>}
  20014. */
  20015. this.attributeCall = new WeakMap();
  20016. }
  20017. /**
  20018. * Returns `true` if the given render object has an initialized geometry.
  20019. *
  20020. * @param {RenderObject} renderObject - The render object.
  20021. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  20022. */
  20023. has( renderObject ) {
  20024. const geometry = renderObject.geometry;
  20025. return super.has( geometry ) && this.get( geometry ).initialized === true;
  20026. }
  20027. /**
  20028. * Prepares the geometry of the given render object for rendering.
  20029. *
  20030. * @param {RenderObject} renderObject - The render object.
  20031. */
  20032. updateForRender( renderObject ) {
  20033. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  20034. this.updateAttributes( renderObject );
  20035. }
  20036. /**
  20037. * Initializes the geometry of the given render object.
  20038. *
  20039. * @param {RenderObject} renderObject - The render object.
  20040. */
  20041. initGeometry( renderObject ) {
  20042. const geometry = renderObject.geometry;
  20043. const geometryData = this.get( geometry );
  20044. geometryData.initialized = true;
  20045. this.info.memory.geometries ++;
  20046. const onDispose = () => {
  20047. this.info.memory.geometries --;
  20048. const index = geometry.index;
  20049. const geometryAttributes = renderObject.getAttributes();
  20050. if ( index !== null ) {
  20051. this.attributes.delete( index );
  20052. }
  20053. for ( const geometryAttribute of geometryAttributes ) {
  20054. this.attributes.delete( geometryAttribute );
  20055. }
  20056. const wireframeAttribute = this.wireframes.get( geometry );
  20057. if ( wireframeAttribute !== undefined ) {
  20058. this.attributes.delete( wireframeAttribute );
  20059. }
  20060. geometry.removeEventListener( 'dispose', onDispose );
  20061. };
  20062. geometry.addEventListener( 'dispose', onDispose );
  20063. }
  20064. /**
  20065. * Updates the geometry attributes of the given render object.
  20066. *
  20067. * @param {RenderObject} renderObject - The render object.
  20068. */
  20069. updateAttributes( renderObject ) {
  20070. // attributes
  20071. const attributes = renderObject.getAttributes();
  20072. for ( const attribute of attributes ) {
  20073. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  20074. this.updateAttribute( attribute, AttributeType.STORAGE );
  20075. } else {
  20076. this.updateAttribute( attribute, AttributeType.VERTEX );
  20077. }
  20078. }
  20079. // indexes
  20080. const index = this.getIndex( renderObject );
  20081. if ( index !== null ) {
  20082. this.updateAttribute( index, AttributeType.INDEX );
  20083. }
  20084. // indirect
  20085. const indirect = renderObject.geometry.indirect;
  20086. if ( indirect !== null ) {
  20087. this.updateAttribute( indirect, AttributeType.INDIRECT );
  20088. }
  20089. }
  20090. /**
  20091. * Updates the given attribute.
  20092. *
  20093. * @param {BufferAttribute} attribute - The attribute to update.
  20094. * @param {number} type - The attribute type.
  20095. */
  20096. updateAttribute( attribute, type ) {
  20097. const callId = this.info.render.calls;
  20098. if ( ! attribute.isInterleavedBufferAttribute ) {
  20099. if ( this.attributeCall.get( attribute ) !== callId ) {
  20100. this.attributes.update( attribute, type );
  20101. this.attributeCall.set( attribute, callId );
  20102. }
  20103. } else {
  20104. if ( this.attributeCall.get( attribute ) === undefined ) {
  20105. this.attributes.update( attribute, type );
  20106. this.attributeCall.set( attribute, callId );
  20107. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  20108. this.attributes.update( attribute, type );
  20109. this.attributeCall.set( attribute.data, callId );
  20110. this.attributeCall.set( attribute, callId );
  20111. }
  20112. }
  20113. }
  20114. /**
  20115. * Returns the indirect buffer attribute of the given render object.
  20116. *
  20117. * @param {RenderObject} renderObject - The render object.
  20118. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20119. */
  20120. getIndirect( renderObject ) {
  20121. return renderObject.geometry.indirect;
  20122. }
  20123. /**
  20124. * Returns the index of the given render object's geometry. This is implemented
  20125. * in a method to return a wireframe index if necessary.
  20126. *
  20127. * @param {RenderObject} renderObject - The render object.
  20128. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20129. */
  20130. getIndex( renderObject ) {
  20131. const { geometry, material } = renderObject;
  20132. let index = geometry.index;
  20133. if ( material.wireframe === true ) {
  20134. const wireframes = this.wireframes;
  20135. let wireframeAttribute = wireframes.get( geometry );
  20136. if ( wireframeAttribute === undefined ) {
  20137. wireframeAttribute = getWireframeIndex( geometry );
  20138. wireframes.set( geometry, wireframeAttribute );
  20139. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  20140. this.attributes.delete( wireframeAttribute );
  20141. wireframeAttribute = getWireframeIndex( geometry );
  20142. wireframes.set( geometry, wireframeAttribute );
  20143. }
  20144. index = wireframeAttribute;
  20145. }
  20146. return index;
  20147. }
  20148. }
  20149. /**
  20150. * This renderer module provides a series of statistical information
  20151. * about the GPU memory and the rendering process. Useful for debugging
  20152. * and monitoring.
  20153. */
  20154. class Info {
  20155. /**
  20156. * Constructs a new info component.
  20157. */
  20158. constructor() {
  20159. /**
  20160. * Whether frame related metrics should automatically
  20161. * be resetted or not. This property should be set to `false`
  20162. * by apps which manage their own animation loop. They must
  20163. * then call `renderer.info.reset()` once per frame manually.
  20164. *
  20165. * @type {boolean}
  20166. * @default true
  20167. */
  20168. this.autoReset = true;
  20169. /**
  20170. * The current frame ID. This ID is managed
  20171. * by `NodeFrame`.
  20172. *
  20173. * @type {number}
  20174. * @readonly
  20175. * @default 0
  20176. */
  20177. this.frame = 0;
  20178. /**
  20179. * The number of render calls since the
  20180. * app has been started.
  20181. *
  20182. * @type {number}
  20183. * @readonly
  20184. * @default 0
  20185. */
  20186. this.calls = 0;
  20187. /**
  20188. * Render related metrics.
  20189. *
  20190. * @type {Object}
  20191. * @readonly
  20192. * @property {number} calls - The number of render calls since the app has been started.
  20193. * @property {number} frameCalls - The number of render calls of the current frame.
  20194. * @property {number} drawCalls - The number of draw calls of the current frame.
  20195. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  20196. * @property {number} points - The number of rendered point primitives of the current frame.
  20197. * @property {number} lines - The number of rendered line primitives of the current frame.
  20198. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  20199. */
  20200. this.render = {
  20201. calls: 0,
  20202. frameCalls: 0,
  20203. drawCalls: 0,
  20204. triangles: 0,
  20205. points: 0,
  20206. lines: 0,
  20207. timestamp: 0,
  20208. };
  20209. /**
  20210. * Compute related metrics.
  20211. *
  20212. * @type {Object}
  20213. * @readonly
  20214. * @property {number} calls - The number of compute calls since the app has been started.
  20215. * @property {number} frameCalls - The number of compute calls of the current frame.
  20216. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  20217. */
  20218. this.compute = {
  20219. calls: 0,
  20220. frameCalls: 0,
  20221. timestamp: 0
  20222. };
  20223. /**
  20224. * Memory related metrics.
  20225. *
  20226. * @type {Object}
  20227. * @readonly
  20228. * @property {number} geometries - The number of active geometries.
  20229. * @property {number} frameCalls - The number of active textures.
  20230. */
  20231. this.memory = {
  20232. geometries: 0,
  20233. textures: 0
  20234. };
  20235. }
  20236. /**
  20237. * This method should be executed per draw call and updates the corresponding metrics.
  20238. *
  20239. * @param {Object3D} object - The 3D object that is going to be rendered.
  20240. * @param {number} count - The vertex or index count.
  20241. * @param {number} instanceCount - The instance count.
  20242. */
  20243. update( object, count, instanceCount ) {
  20244. this.render.drawCalls ++;
  20245. if ( object.isMesh || object.isSprite ) {
  20246. this.render.triangles += instanceCount * ( count / 3 );
  20247. } else if ( object.isPoints ) {
  20248. this.render.points += instanceCount * count;
  20249. } else if ( object.isLineSegments ) {
  20250. this.render.lines += instanceCount * ( count / 2 );
  20251. } else if ( object.isLine ) {
  20252. this.render.lines += instanceCount * ( count - 1 );
  20253. } else {
  20254. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  20255. }
  20256. }
  20257. /**
  20258. * Resets frame related metrics.
  20259. */
  20260. reset() {
  20261. this.render.drawCalls = 0;
  20262. this.render.frameCalls = 0;
  20263. this.compute.frameCalls = 0;
  20264. this.render.triangles = 0;
  20265. this.render.points = 0;
  20266. this.render.lines = 0;
  20267. }
  20268. /**
  20269. * Performs a complete reset of the object.
  20270. */
  20271. dispose() {
  20272. this.reset();
  20273. this.calls = 0;
  20274. this.render.calls = 0;
  20275. this.compute.calls = 0;
  20276. this.render.timestamp = 0;
  20277. this.compute.timestamp = 0;
  20278. this.memory.geometries = 0;
  20279. this.memory.textures = 0;
  20280. }
  20281. }
  20282. /**
  20283. * Abstract class for representing pipelines.
  20284. *
  20285. * @private
  20286. * @abstract
  20287. */
  20288. class Pipeline {
  20289. /**
  20290. * Constructs a new pipeline.
  20291. *
  20292. * @param {string} cacheKey - The pipeline's cache key.
  20293. */
  20294. constructor( cacheKey ) {
  20295. /**
  20296. * The pipeline's cache key.
  20297. *
  20298. * @type {string}
  20299. */
  20300. this.cacheKey = cacheKey;
  20301. /**
  20302. * How often the pipeline is currently in use.
  20303. *
  20304. * @type {number}
  20305. * @default 0
  20306. */
  20307. this.usedTimes = 0;
  20308. }
  20309. }
  20310. /**
  20311. * Class for representing render pipelines.
  20312. *
  20313. * @private
  20314. * @augments Pipeline
  20315. */
  20316. class RenderPipeline extends Pipeline {
  20317. /**
  20318. * Constructs a new render pipeline.
  20319. *
  20320. * @param {string} cacheKey - The pipeline's cache key.
  20321. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  20322. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  20323. */
  20324. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  20325. super( cacheKey );
  20326. /**
  20327. * The pipeline's vertex shader.
  20328. *
  20329. * @type {ProgrammableStage}
  20330. */
  20331. this.vertexProgram = vertexProgram;
  20332. /**
  20333. * The pipeline's fragment shader.
  20334. *
  20335. * @type {ProgrammableStage}
  20336. */
  20337. this.fragmentProgram = fragmentProgram;
  20338. }
  20339. }
  20340. /**
  20341. * Class for representing compute pipelines.
  20342. *
  20343. * @private
  20344. * @augments Pipeline
  20345. */
  20346. class ComputePipeline extends Pipeline {
  20347. /**
  20348. * Constructs a new render pipeline.
  20349. *
  20350. * @param {string} cacheKey - The pipeline's cache key.
  20351. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  20352. */
  20353. constructor( cacheKey, computeProgram ) {
  20354. super( cacheKey );
  20355. /**
  20356. * The pipeline's compute shader.
  20357. *
  20358. * @type {ProgrammableStage}
  20359. */
  20360. this.computeProgram = computeProgram;
  20361. /**
  20362. * This flag can be used for type testing.
  20363. *
  20364. * @type {boolean}
  20365. * @readonly
  20366. * @default true
  20367. */
  20368. this.isComputePipeline = true;
  20369. }
  20370. }
  20371. let _id$8 = 0;
  20372. /**
  20373. * Class for representing programmable stages which are vertex,
  20374. * fragment or compute shaders. Unlike fixed-function states (like blending),
  20375. * they represent the programmable part of a pipeline.
  20376. *
  20377. * @private
  20378. */
  20379. class ProgrammableStage {
  20380. /**
  20381. * Constructs a new programmable stage.
  20382. *
  20383. * @param {string} code - The shader code.
  20384. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  20385. * @param {string} name - The name of the shader.
  20386. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20387. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20388. */
  20389. constructor( code, stage, name, transforms = null, attributes = null ) {
  20390. /**
  20391. * The id of the programmable stage.
  20392. *
  20393. * @type {number}
  20394. */
  20395. this.id = _id$8 ++;
  20396. /**
  20397. * The shader code.
  20398. *
  20399. * @type {string}
  20400. */
  20401. this.code = code;
  20402. /**
  20403. * The type of stage.
  20404. *
  20405. * @type {string}
  20406. */
  20407. this.stage = stage;
  20408. /**
  20409. * The name of the stage.
  20410. * This is used for debugging purposes.
  20411. *
  20412. * @type {string}
  20413. */
  20414. this.name = name;
  20415. /**
  20416. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20417. *
  20418. * @type {?Array<Object>}
  20419. */
  20420. this.transforms = transforms;
  20421. /**
  20422. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20423. *
  20424. * @type {?Array<Object>}
  20425. */
  20426. this.attributes = attributes;
  20427. /**
  20428. * How often the programmable stage is currently in use.
  20429. *
  20430. * @type {number}
  20431. * @default 0
  20432. */
  20433. this.usedTimes = 0;
  20434. }
  20435. }
  20436. /**
  20437. * This renderer module manages the pipelines of the renderer.
  20438. *
  20439. * @private
  20440. * @augments DataMap
  20441. */
  20442. class Pipelines extends DataMap {
  20443. /**
  20444. * Constructs a new pipeline management component.
  20445. *
  20446. * @param {Backend} backend - The renderer's backend.
  20447. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20448. */
  20449. constructor( backend, nodes ) {
  20450. super();
  20451. /**
  20452. * The renderer's backend.
  20453. *
  20454. * @type {Backend}
  20455. */
  20456. this.backend = backend;
  20457. /**
  20458. * Renderer component for managing nodes related logic.
  20459. *
  20460. * @type {Nodes}
  20461. */
  20462. this.nodes = nodes;
  20463. /**
  20464. * A references to the bindings management component.
  20465. * This reference will be set inside the `Bindings`
  20466. * constructor.
  20467. *
  20468. * @type {?Bindings}
  20469. * @default null
  20470. */
  20471. this.bindings = null;
  20472. /**
  20473. * Internal cache for maintaining pipelines.
  20474. * The key of the map is a cache key, the value the pipeline.
  20475. *
  20476. * @type {Map<string,Pipeline>}
  20477. */
  20478. this.caches = new Map();
  20479. /**
  20480. * This dictionary maintains for each shader stage type (vertex,
  20481. * fragment and compute) the programmable stage objects which
  20482. * represent the actual shader code.
  20483. *
  20484. * @type {Object<string,Map>}
  20485. */
  20486. this.programs = {
  20487. vertex: new Map(),
  20488. fragment: new Map(),
  20489. compute: new Map()
  20490. };
  20491. }
  20492. /**
  20493. * Returns a compute pipeline for the given compute node.
  20494. *
  20495. * @param {Node} computeNode - The compute node.
  20496. * @param {Array<BindGroup>} bindings - The bindings.
  20497. * @return {ComputePipeline} The compute pipeline.
  20498. */
  20499. getForCompute( computeNode, bindings ) {
  20500. const { backend } = this;
  20501. const data = this.get( computeNode );
  20502. if ( this._needsComputeUpdate( computeNode ) ) {
  20503. const previousPipeline = data.pipeline;
  20504. if ( previousPipeline ) {
  20505. previousPipeline.usedTimes --;
  20506. previousPipeline.computeProgram.usedTimes --;
  20507. }
  20508. // get shader
  20509. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  20510. // programmable stage
  20511. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  20512. if ( stageCompute === undefined ) {
  20513. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  20514. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  20515. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  20516. backend.createProgram( stageCompute );
  20517. }
  20518. // determine compute pipeline
  20519. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  20520. let pipeline = this.caches.get( cacheKey );
  20521. if ( pipeline === undefined ) {
  20522. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  20523. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  20524. }
  20525. // keep track of all used times
  20526. pipeline.usedTimes ++;
  20527. stageCompute.usedTimes ++;
  20528. //
  20529. data.version = computeNode.version;
  20530. data.pipeline = pipeline;
  20531. }
  20532. return data.pipeline;
  20533. }
  20534. /**
  20535. * Returns a render pipeline for the given render object.
  20536. *
  20537. * @param {RenderObject} renderObject - The render object.
  20538. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  20539. * @return {RenderPipeline} The render pipeline.
  20540. */
  20541. getForRender( renderObject, promises = null ) {
  20542. const { backend } = this;
  20543. const data = this.get( renderObject );
  20544. if ( this._needsRenderUpdate( renderObject ) ) {
  20545. const previousPipeline = data.pipeline;
  20546. if ( previousPipeline ) {
  20547. previousPipeline.usedTimes --;
  20548. previousPipeline.vertexProgram.usedTimes --;
  20549. previousPipeline.fragmentProgram.usedTimes --;
  20550. }
  20551. // get shader
  20552. const nodeBuilderState = renderObject.getNodeBuilderState();
  20553. const name = renderObject.material ? renderObject.material.name : '';
  20554. // programmable stages
  20555. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  20556. if ( stageVertex === undefined ) {
  20557. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  20558. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  20559. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  20560. backend.createProgram( stageVertex );
  20561. }
  20562. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  20563. if ( stageFragment === undefined ) {
  20564. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  20565. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  20566. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  20567. backend.createProgram( stageFragment );
  20568. }
  20569. // determine render pipeline
  20570. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  20571. let pipeline = this.caches.get( cacheKey );
  20572. if ( pipeline === undefined ) {
  20573. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  20574. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  20575. } else {
  20576. renderObject.pipeline = pipeline;
  20577. }
  20578. // keep track of all used times
  20579. pipeline.usedTimes ++;
  20580. stageVertex.usedTimes ++;
  20581. stageFragment.usedTimes ++;
  20582. //
  20583. data.pipeline = pipeline;
  20584. }
  20585. return data.pipeline;
  20586. }
  20587. /**
  20588. * Deletes the pipeline for the given render object.
  20589. *
  20590. * @param {RenderObject} object - The render object.
  20591. * @return {?Object} The deleted dictionary.
  20592. */
  20593. delete( object ) {
  20594. const pipeline = this.get( object ).pipeline;
  20595. if ( pipeline ) {
  20596. // pipeline
  20597. pipeline.usedTimes --;
  20598. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  20599. // programs
  20600. if ( pipeline.isComputePipeline ) {
  20601. pipeline.computeProgram.usedTimes --;
  20602. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  20603. } else {
  20604. pipeline.fragmentProgram.usedTimes --;
  20605. pipeline.vertexProgram.usedTimes --;
  20606. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  20607. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  20608. }
  20609. }
  20610. return super.delete( object );
  20611. }
  20612. /**
  20613. * Frees internal resources.
  20614. */
  20615. dispose() {
  20616. super.dispose();
  20617. this.caches = new Map();
  20618. this.programs = {
  20619. vertex: new Map(),
  20620. fragment: new Map(),
  20621. compute: new Map()
  20622. };
  20623. }
  20624. /**
  20625. * Updates the pipeline for the given render object.
  20626. *
  20627. * @param {RenderObject} renderObject - The render object.
  20628. */
  20629. updateForRender( renderObject ) {
  20630. this.getForRender( renderObject );
  20631. }
  20632. /**
  20633. * Returns a compute pipeline for the given parameters.
  20634. *
  20635. * @private
  20636. * @param {Node} computeNode - The compute node.
  20637. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  20638. * @param {string} cacheKey - The cache key.
  20639. * @param {Array<BindGroup>} bindings - The bindings.
  20640. * @return {ComputePipeline} The compute pipeline.
  20641. */
  20642. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  20643. // check for existing pipeline
  20644. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  20645. let pipeline = this.caches.get( cacheKey );
  20646. if ( pipeline === undefined ) {
  20647. pipeline = new ComputePipeline( cacheKey, stageCompute );
  20648. this.caches.set( cacheKey, pipeline );
  20649. this.backend.createComputePipeline( pipeline, bindings );
  20650. }
  20651. return pipeline;
  20652. }
  20653. /**
  20654. * Returns a render pipeline for the given parameters.
  20655. *
  20656. * @private
  20657. * @param {RenderObject} renderObject - The render object.
  20658. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  20659. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  20660. * @param {string} cacheKey - The cache key.
  20661. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  20662. * @return {ComputePipeline} The compute pipeline.
  20663. */
  20664. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  20665. // check for existing pipeline
  20666. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  20667. let pipeline = this.caches.get( cacheKey );
  20668. if ( pipeline === undefined ) {
  20669. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  20670. this.caches.set( cacheKey, pipeline );
  20671. renderObject.pipeline = pipeline;
  20672. // The `promises` array is `null` by default and only set to an empty array when
  20673. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  20674. // pending promises that resolve when the render pipelines are ready for rendering.
  20675. this.backend.createRenderPipeline( renderObject, promises );
  20676. }
  20677. return pipeline;
  20678. }
  20679. /**
  20680. * Computes a cache key representing a compute pipeline.
  20681. *
  20682. * @private
  20683. * @param {Node} computeNode - The compute node.
  20684. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  20685. * @return {string} The cache key.
  20686. */
  20687. _getComputeCacheKey( computeNode, stageCompute ) {
  20688. return computeNode.id + ',' + stageCompute.id;
  20689. }
  20690. /**
  20691. * Computes a cache key representing a render pipeline.
  20692. *
  20693. * @private
  20694. * @param {RenderObject} renderObject - The render object.
  20695. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  20696. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  20697. * @return {string} The cache key.
  20698. */
  20699. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  20700. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  20701. }
  20702. /**
  20703. * Releases the given pipeline.
  20704. *
  20705. * @private
  20706. * @param {Pipeline} pipeline - The pipeline to release.
  20707. */
  20708. _releasePipeline( pipeline ) {
  20709. this.caches.delete( pipeline.cacheKey );
  20710. }
  20711. /**
  20712. * Releases the shader program.
  20713. *
  20714. * @private
  20715. * @param {Object} program - The shader program to release.
  20716. */
  20717. _releaseProgram( program ) {
  20718. const code = program.code;
  20719. const stage = program.stage;
  20720. this.programs[ stage ].delete( code );
  20721. }
  20722. /**
  20723. * Returns `true` if the compute pipeline for the given compute node requires an update.
  20724. *
  20725. * @private
  20726. * @param {Node} computeNode - The compute node.
  20727. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  20728. */
  20729. _needsComputeUpdate( computeNode ) {
  20730. const data = this.get( computeNode );
  20731. return data.pipeline === undefined || data.version !== computeNode.version;
  20732. }
  20733. /**
  20734. * Returns `true` if the render pipeline for the given render object requires an update.
  20735. *
  20736. * @private
  20737. * @param {RenderObject} renderObject - The render object.
  20738. * @return {boolean} Whether the render object for the given render object requires an update or not.
  20739. */
  20740. _needsRenderUpdate( renderObject ) {
  20741. const data = this.get( renderObject );
  20742. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  20743. }
  20744. }
  20745. /**
  20746. * This renderer module manages the bindings of the renderer.
  20747. *
  20748. * @private
  20749. * @augments DataMap
  20750. */
  20751. class Bindings extends DataMap {
  20752. /**
  20753. * Constructs a new bindings management component.
  20754. *
  20755. * @param {Backend} backend - The renderer's backend.
  20756. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20757. * @param {Textures} textures - Renderer component for managing textures.
  20758. * @param {Attributes} attributes - Renderer component for managing attributes.
  20759. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20760. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20761. */
  20762. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  20763. super();
  20764. /**
  20765. * The renderer's backend.
  20766. *
  20767. * @type {Backend}
  20768. */
  20769. this.backend = backend;
  20770. /**
  20771. * Renderer component for managing textures.
  20772. *
  20773. * @type {Textures}
  20774. */
  20775. this.textures = textures;
  20776. /**
  20777. * Renderer component for managing pipelines.
  20778. *
  20779. * @type {Pipelines}
  20780. */
  20781. this.pipelines = pipelines;
  20782. /**
  20783. * Renderer component for managing attributes.
  20784. *
  20785. * @type {Attributes}
  20786. */
  20787. this.attributes = attributes;
  20788. /**
  20789. * Renderer component for managing nodes related logic.
  20790. *
  20791. * @type {Nodes}
  20792. */
  20793. this.nodes = nodes;
  20794. /**
  20795. * Renderer component for managing metrics and monitoring data.
  20796. *
  20797. * @type {Info}
  20798. */
  20799. this.info = info;
  20800. this.pipelines.bindings = this; // assign bindings to pipelines
  20801. }
  20802. /**
  20803. * Returns the bind groups for the given render object.
  20804. *
  20805. * @param {RenderObject} renderObject - The render object.
  20806. * @return {Array<BindGroup>} The bind groups.
  20807. */
  20808. getForRender( renderObject ) {
  20809. const bindings = renderObject.getBindings();
  20810. for ( const bindGroup of bindings ) {
  20811. const groupData = this.get( bindGroup );
  20812. if ( groupData.bindGroup === undefined ) {
  20813. // each object defines an array of bindings (ubos, textures, samplers etc.)
  20814. this._init( bindGroup );
  20815. this.backend.createBindings( bindGroup, bindings, 0 );
  20816. groupData.bindGroup = bindGroup;
  20817. }
  20818. }
  20819. return bindings;
  20820. }
  20821. /**
  20822. * Returns the bind groups for the given compute node.
  20823. *
  20824. * @param {Node} computeNode - The compute node.
  20825. * @return {Array<BindGroup>} The bind groups.
  20826. */
  20827. getForCompute( computeNode ) {
  20828. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  20829. for ( const bindGroup of bindings ) {
  20830. const groupData = this.get( bindGroup );
  20831. if ( groupData.bindGroup === undefined ) {
  20832. this._init( bindGroup );
  20833. this.backend.createBindings( bindGroup, bindings, 0 );
  20834. groupData.bindGroup = bindGroup;
  20835. }
  20836. }
  20837. return bindings;
  20838. }
  20839. /**
  20840. * Updates the bindings for the given compute node.
  20841. *
  20842. * @param {Node} computeNode - The compute node.
  20843. */
  20844. updateForCompute( computeNode ) {
  20845. this._updateBindings( this.getForCompute( computeNode ) );
  20846. }
  20847. /**
  20848. * Updates the bindings for the given render object.
  20849. *
  20850. * @param {RenderObject} renderObject - The render object.
  20851. */
  20852. updateForRender( renderObject ) {
  20853. this._updateBindings( this.getForRender( renderObject ) );
  20854. }
  20855. /**
  20856. * Updates the given array of bindings.
  20857. *
  20858. * @param {Array<BindGroup>} bindings - The bind groups.
  20859. */
  20860. _updateBindings( bindings ) {
  20861. for ( const bindGroup of bindings ) {
  20862. this._update( bindGroup, bindings );
  20863. }
  20864. }
  20865. /**
  20866. * Initializes the given bind group.
  20867. *
  20868. * @param {BindGroup} bindGroup - The bind group to initialize.
  20869. */
  20870. _init( bindGroup ) {
  20871. for ( const binding of bindGroup.bindings ) {
  20872. if ( binding.isSampledTexture ) {
  20873. this.textures.updateTexture( binding.texture );
  20874. } else if ( binding.isStorageBuffer ) {
  20875. const attribute = binding.attribute;
  20876. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  20877. this.attributes.update( attribute, attributeType );
  20878. }
  20879. }
  20880. }
  20881. /**
  20882. * Updates the given bind group.
  20883. *
  20884. * @param {BindGroup} bindGroup - The bind group to update.
  20885. * @param {Array<BindGroup>} bindings - The bind groups.
  20886. */
  20887. _update( bindGroup, bindings ) {
  20888. const { backend } = this;
  20889. let needsBindingsUpdate = false;
  20890. let cacheBindings = true;
  20891. let cacheIndex = 0;
  20892. let version = 0;
  20893. // iterate over all bindings and check if buffer updates or a new binding group is required
  20894. for ( const binding of bindGroup.bindings ) {
  20895. if ( binding.isNodeUniformsGroup ) {
  20896. const updated = this.nodes.updateGroup( binding );
  20897. // every uniforms group is a uniform buffer. So if no update is required,
  20898. // we move one with the next binding. Otherwise the next if block will update the group.
  20899. if ( updated === false ) continue;
  20900. }
  20901. if ( binding.isStorageBuffer ) {
  20902. const attribute = binding.attribute;
  20903. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  20904. this.attributes.update( attribute, attributeType );
  20905. }
  20906. if ( binding.isUniformBuffer ) {
  20907. const updated = binding.update();
  20908. if ( updated ) {
  20909. backend.updateBinding( binding );
  20910. }
  20911. } else if ( binding.isSampledTexture ) {
  20912. const updated = binding.update();
  20913. // get the texture data after the update, to sync the texture reference from node
  20914. const texture = binding.texture;
  20915. const texturesTextureData = this.textures.get( texture );
  20916. if ( updated ) {
  20917. // version: update the texture data or create a new one
  20918. this.textures.updateTexture( texture );
  20919. // generation: update the bindings if a new texture has been created
  20920. if ( binding.generation !== texturesTextureData.generation ) {
  20921. binding.generation = texturesTextureData.generation;
  20922. needsBindingsUpdate = true;
  20923. }
  20924. }
  20925. const textureData = backend.get( texture );
  20926. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  20927. cacheBindings = false;
  20928. } else {
  20929. cacheIndex = cacheIndex * 10 + texture.id;
  20930. version += texture.version;
  20931. }
  20932. if ( texture.isStorageTexture === true ) {
  20933. const textureData = this.get( texture );
  20934. if ( binding.store === true ) {
  20935. textureData.needsMipmap = true;
  20936. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  20937. this.backend.generateMipmaps( texture );
  20938. textureData.needsMipmap = false;
  20939. }
  20940. }
  20941. } else if ( binding.isSampler ) {
  20942. binding.update();
  20943. }
  20944. }
  20945. if ( needsBindingsUpdate === true ) {
  20946. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  20947. }
  20948. }
  20949. }
  20950. /**
  20951. * Default sorting function for opaque render items.
  20952. *
  20953. * @private
  20954. * @function
  20955. * @param {Object} a - The first render item.
  20956. * @param {Object} b - The second render item.
  20957. * @return {number} A numeric value which defines the sort order.
  20958. */
  20959. function painterSortStable( a, b ) {
  20960. if ( a.groupOrder !== b.groupOrder ) {
  20961. return a.groupOrder - b.groupOrder;
  20962. } else if ( a.renderOrder !== b.renderOrder ) {
  20963. return a.renderOrder - b.renderOrder;
  20964. } else if ( a.z !== b.z ) {
  20965. return a.z - b.z;
  20966. } else {
  20967. return a.id - b.id;
  20968. }
  20969. }
  20970. /**
  20971. * Default sorting function for transparent render items.
  20972. *
  20973. * @private
  20974. * @function
  20975. * @param {Object} a - The first render item.
  20976. * @param {Object} b - The second render item.
  20977. * @return {number} A numeric value which defines the sort order.
  20978. */
  20979. function reversePainterSortStable( a, b ) {
  20980. if ( a.groupOrder !== b.groupOrder ) {
  20981. return a.groupOrder - b.groupOrder;
  20982. } else if ( a.renderOrder !== b.renderOrder ) {
  20983. return a.renderOrder - b.renderOrder;
  20984. } else if ( a.z !== b.z ) {
  20985. return b.z - a.z;
  20986. } else {
  20987. return a.id - b.id;
  20988. }
  20989. }
  20990. /**
  20991. * Returns `true` if the given transparent material requires a double pass.
  20992. *
  20993. * @private
  20994. * @function
  20995. * @param {Material} material - The transparent material.
  20996. * @return {boolean} Whether the given material requires a double pass or not.
  20997. */
  20998. function needsDoublePass( material ) {
  20999. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  21000. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  21001. }
  21002. /**
  21003. * When the renderer analyzes the scene at the beginning of a render call,
  21004. * it stores 3D object for further processing in render lists. Depending on the
  21005. * properties of a 3D objects (like their transformation or material state), the
  21006. * objects are maintained in ordered lists for the actual rendering.
  21007. *
  21008. * Render lists are unique per scene and camera combination.
  21009. *
  21010. * @private
  21011. * @augments Pipeline
  21012. */
  21013. class RenderList {
  21014. /**
  21015. * Constructs a render list.
  21016. *
  21017. * @param {Lighting} lighting - The lighting management component.
  21018. * @param {Scene} scene - The scene.
  21019. * @param {Camera} camera - The camera the scene is rendered with.
  21020. */
  21021. constructor( lighting, scene, camera ) {
  21022. /**
  21023. * 3D objects are transformed into render items and stored in this array.
  21024. *
  21025. * @type {Array<Object>}
  21026. */
  21027. this.renderItems = [];
  21028. /**
  21029. * The current render items index.
  21030. *
  21031. * @type {number}
  21032. * @default 0
  21033. */
  21034. this.renderItemsIndex = 0;
  21035. /**
  21036. * A list with opaque render items.
  21037. *
  21038. * @type {Array<Object>}
  21039. */
  21040. this.opaque = [];
  21041. /**
  21042. * A list with transparent render items which require
  21043. * double pass rendering (e.g. transmissive objects).
  21044. *
  21045. * @type {Array<Object>}
  21046. */
  21047. this.transparentDoublePass = [];
  21048. /**
  21049. * A list with transparent render items.
  21050. *
  21051. * @type {Array<Object>}
  21052. */
  21053. this.transparent = [];
  21054. /**
  21055. * A list with transparent render bundle data.
  21056. *
  21057. * @type {Array<Object>}
  21058. */
  21059. this.bundles = [];
  21060. /**
  21061. * The render list's lights node. This node is later
  21062. * relevant for the actual analytical light nodes which
  21063. * compute the scene's lighting in the shader.
  21064. *
  21065. * @type {LightsNode}
  21066. */
  21067. this.lightsNode = lighting.getNode( scene, camera );
  21068. /**
  21069. * The scene's lights stored in an array. This array
  21070. * is used to setup the lights node.
  21071. *
  21072. * @type {Array<Light>}
  21073. */
  21074. this.lightsArray = [];
  21075. /**
  21076. * The scene.
  21077. *
  21078. * @type {Scene}
  21079. */
  21080. this.scene = scene;
  21081. /**
  21082. * The camera the scene is rendered with.
  21083. *
  21084. * @type {Camera}
  21085. */
  21086. this.camera = camera;
  21087. /**
  21088. * How many objects perform occlusion query tests.
  21089. *
  21090. * @type {number}
  21091. * @default 0
  21092. */
  21093. this.occlusionQueryCount = 0;
  21094. }
  21095. /**
  21096. * This method is called right at the beginning of a render call
  21097. * before the scene is analyzed. It prepares the internal data
  21098. * structures for the upcoming render lists generation.
  21099. *
  21100. * @return {RenderList} A reference to this render list.
  21101. */
  21102. begin() {
  21103. this.renderItemsIndex = 0;
  21104. this.opaque.length = 0;
  21105. this.transparentDoublePass.length = 0;
  21106. this.transparent.length = 0;
  21107. this.bundles.length = 0;
  21108. this.lightsArray.length = 0;
  21109. this.occlusionQueryCount = 0;
  21110. return this;
  21111. }
  21112. /**
  21113. * Returns a render item for the giving render item state. The state is defined
  21114. * by a series of object-related parameters.
  21115. *
  21116. * The method avoids object creation by holding render items and reusing them in
  21117. * subsequent render calls (just with different property values).
  21118. *
  21119. * @param {Object3D} object - The 3D object.
  21120. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21121. * @param {Material} material - The 3D object's material.
  21122. * @param {number} groupOrder - The current group order.
  21123. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21124. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21125. * @param {ClippingContext} clippingContext - The current clipping context.
  21126. * @return {Object} The render item.
  21127. */
  21128. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21129. let renderItem = this.renderItems[ this.renderItemsIndex ];
  21130. if ( renderItem === undefined ) {
  21131. renderItem = {
  21132. id: object.id,
  21133. object: object,
  21134. geometry: geometry,
  21135. material: material,
  21136. groupOrder: groupOrder,
  21137. renderOrder: object.renderOrder,
  21138. z: z,
  21139. group: group,
  21140. clippingContext: clippingContext
  21141. };
  21142. this.renderItems[ this.renderItemsIndex ] = renderItem;
  21143. } else {
  21144. renderItem.id = object.id;
  21145. renderItem.object = object;
  21146. renderItem.geometry = geometry;
  21147. renderItem.material = material;
  21148. renderItem.groupOrder = groupOrder;
  21149. renderItem.renderOrder = object.renderOrder;
  21150. renderItem.z = z;
  21151. renderItem.group = group;
  21152. renderItem.clippingContext = clippingContext;
  21153. }
  21154. this.renderItemsIndex ++;
  21155. return renderItem;
  21156. }
  21157. /**
  21158. * Pushes the given object as a render item to the internal render lists.
  21159. * The selected lists depend on the object properties.
  21160. *
  21161. * @param {Object3D} object - The 3D object.
  21162. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21163. * @param {Material} material - The 3D object's material.
  21164. * @param {number} groupOrder - The current group order.
  21165. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21166. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21167. * @param {ClippingContext} clippingContext - The current clipping context.
  21168. */
  21169. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21170. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21171. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  21172. if ( material.transparent === true || material.transmission > 0 ) {
  21173. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  21174. this.transparent.push( renderItem );
  21175. } else {
  21176. this.opaque.push( renderItem );
  21177. }
  21178. }
  21179. /**
  21180. * Inserts the given object as a render item at the start of the internal render lists.
  21181. * The selected lists depend on the object properties.
  21182. *
  21183. * @param {Object3D} object - The 3D object.
  21184. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21185. * @param {Material} material - The 3D object's material.
  21186. * @param {number} groupOrder - The current group order.
  21187. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21188. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21189. * @param {ClippingContext} clippingContext - The current clipping context.
  21190. */
  21191. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21192. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21193. if ( material.transparent === true || material.transmission > 0 ) {
  21194. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  21195. this.transparent.unshift( renderItem );
  21196. } else {
  21197. this.opaque.unshift( renderItem );
  21198. }
  21199. }
  21200. /**
  21201. * Pushes render bundle group data into the render list.
  21202. *
  21203. * @param {Object} group - Bundle group data.
  21204. */
  21205. pushBundle( group ) {
  21206. this.bundles.push( group );
  21207. }
  21208. /**
  21209. * Pushes a light into the render list.
  21210. *
  21211. * @param {Light} light - The light.
  21212. */
  21213. pushLight( light ) {
  21214. this.lightsArray.push( light );
  21215. }
  21216. /**
  21217. * Sorts the internal render lists.
  21218. *
  21219. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  21220. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  21221. */
  21222. sort( customOpaqueSort, customTransparentSort ) {
  21223. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  21224. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  21225. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  21226. }
  21227. /**
  21228. * This method performs finalizing tasks right after the render lists
  21229. * have been generated.
  21230. */
  21231. finish() {
  21232. // update lights
  21233. this.lightsNode.setLights( this.lightsArray );
  21234. // Clear references from inactive renderItems in the list
  21235. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  21236. const renderItem = this.renderItems[ i ];
  21237. if ( renderItem.id === null ) break;
  21238. renderItem.id = null;
  21239. renderItem.object = null;
  21240. renderItem.geometry = null;
  21241. renderItem.material = null;
  21242. renderItem.groupOrder = null;
  21243. renderItem.renderOrder = null;
  21244. renderItem.z = null;
  21245. renderItem.group = null;
  21246. renderItem.clippingContext = null;
  21247. }
  21248. }
  21249. }
  21250. const _chainKeys$4 = [];
  21251. /**
  21252. * This renderer module manages the render lists which are unique
  21253. * per scene and camera combination.
  21254. *
  21255. * @private
  21256. */
  21257. class RenderLists {
  21258. /**
  21259. * Constructs a render lists management component.
  21260. *
  21261. * @param {Lighting} lighting - The lighting management component.
  21262. */
  21263. constructor( lighting ) {
  21264. /**
  21265. * The lighting management component.
  21266. *
  21267. * @type {Lighting}
  21268. */
  21269. this.lighting = lighting;
  21270. /**
  21271. * The internal chain map which holds the render lists.
  21272. *
  21273. * @type {ChainMap}
  21274. */
  21275. this.lists = new ChainMap();
  21276. }
  21277. /**
  21278. * Returns a render list for the given scene and camera.
  21279. *
  21280. * @param {Scene} scene - The scene.
  21281. * @param {Camera} camera - The camera.
  21282. * @return {RenderList} The render list.
  21283. */
  21284. get( scene, camera ) {
  21285. const lists = this.lists;
  21286. _chainKeys$4[ 0 ] = scene;
  21287. _chainKeys$4[ 1 ] = camera;
  21288. let list = lists.get( _chainKeys$4 );
  21289. if ( list === undefined ) {
  21290. list = new RenderList( this.lighting, scene, camera );
  21291. lists.set( _chainKeys$4, list );
  21292. }
  21293. _chainKeys$4.length = 0;
  21294. return list;
  21295. }
  21296. /**
  21297. * Frees all internal resources.
  21298. */
  21299. dispose() {
  21300. this.lists = new ChainMap();
  21301. }
  21302. }
  21303. let _id$7 = 0;
  21304. /**
  21305. * Any render or compute command is executed in a specific context that defines
  21306. * the state of the renderer and its backend. Typical examples for such context
  21307. * data are the current clear values or data from the active framebuffer. This
  21308. * module is used to represent these contexts as objects.
  21309. *
  21310. * @private
  21311. */
  21312. class RenderContext {
  21313. /**
  21314. * Constructs a new render context.
  21315. */
  21316. constructor() {
  21317. /**
  21318. * The context's ID.
  21319. *
  21320. * @type {number}
  21321. */
  21322. this.id = _id$7 ++;
  21323. /**
  21324. * Whether the current active framebuffer has a color attachment.
  21325. *
  21326. * @type {boolean}
  21327. * @default true
  21328. */
  21329. this.color = true;
  21330. /**
  21331. * Whether the color attachment should be cleared or not.
  21332. *
  21333. * @type {boolean}
  21334. * @default true
  21335. */
  21336. this.clearColor = true;
  21337. /**
  21338. * The clear color value.
  21339. *
  21340. * @type {Object}
  21341. * @default true
  21342. */
  21343. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  21344. /**
  21345. * Whether the current active framebuffer has a depth attachment.
  21346. *
  21347. * @type {boolean}
  21348. * @default true
  21349. */
  21350. this.depth = true;
  21351. /**
  21352. * Whether the depth attachment should be cleared or not.
  21353. *
  21354. * @type {boolean}
  21355. * @default true
  21356. */
  21357. this.clearDepth = true;
  21358. /**
  21359. * The clear depth value.
  21360. *
  21361. * @type {number}
  21362. * @default 1
  21363. */
  21364. this.clearDepthValue = 1;
  21365. /**
  21366. * Whether the current active framebuffer has a stencil attachment.
  21367. *
  21368. * @type {boolean}
  21369. * @default false
  21370. */
  21371. this.stencil = false;
  21372. /**
  21373. * Whether the stencil attachment should be cleared or not.
  21374. *
  21375. * @type {boolean}
  21376. * @default true
  21377. */
  21378. this.clearStencil = true;
  21379. /**
  21380. * The clear stencil value.
  21381. *
  21382. * @type {number}
  21383. * @default 1
  21384. */
  21385. this.clearStencilValue = 1;
  21386. /**
  21387. * By default the viewport encloses the entire framebuffer If a smaller
  21388. * viewport is manually defined, this property is to `true` by the renderer.
  21389. *
  21390. * @type {boolean}
  21391. * @default false
  21392. */
  21393. this.viewport = false;
  21394. /**
  21395. * The viewport value. This value is in physical pixels meaning it incorporates
  21396. * the renderer's pixel ratio. The viewport property of render targets or
  21397. * the renderer is in logical pixels.
  21398. *
  21399. * @type {Vector4}
  21400. */
  21401. this.viewportValue = new Vector4();
  21402. /**
  21403. * When the scissor test is active and scissor rectangle smaller than the
  21404. * framebuffers dimensions, this property is to `true` by the renderer.
  21405. *
  21406. * @type {boolean}
  21407. * @default false
  21408. */
  21409. this.scissor = false;
  21410. /**
  21411. * The scissor rectangle.
  21412. *
  21413. * @type {Vector4}
  21414. */
  21415. this.scissorValue = new Vector4();
  21416. /**
  21417. * The active render target.
  21418. *
  21419. * @type {?RenderTarget}
  21420. * @default null
  21421. */
  21422. this.renderTarget = null;
  21423. /**
  21424. * The textures of the active render target.
  21425. * `null` when no render target is set.
  21426. *
  21427. * @type {?Array<Texture>}
  21428. * @default null
  21429. */
  21430. this.textures = null;
  21431. /**
  21432. * The depth texture of the active render target.
  21433. * `null` when no render target is set.
  21434. *
  21435. * @type {?DepthTexture}
  21436. * @default null
  21437. */
  21438. this.depthTexture = null;
  21439. /**
  21440. * The active cube face.
  21441. *
  21442. * @type {number}
  21443. * @default 0
  21444. */
  21445. this.activeCubeFace = 0;
  21446. /**
  21447. * The active mipmap level.
  21448. *
  21449. * @type {number}
  21450. * @default 0
  21451. */
  21452. this.activeMipmapLevel = 0;
  21453. /**
  21454. * The number of MSAA samples. This value is always `1` when
  21455. * MSAA isn't used.
  21456. *
  21457. * @type {number}
  21458. * @default 1
  21459. */
  21460. this.sampleCount = 1;
  21461. /**
  21462. * The active render target's width in physical pixels.
  21463. *
  21464. * @type {number}
  21465. * @default 0
  21466. */
  21467. this.width = 0;
  21468. /**
  21469. * The active render target's height in physical pixels.
  21470. *
  21471. * @type {number}
  21472. * @default 0
  21473. */
  21474. this.height = 0;
  21475. /**
  21476. * The occlusion query count.
  21477. *
  21478. * @type {number}
  21479. * @default 0
  21480. */
  21481. this.occlusionQueryCount = 0;
  21482. /**
  21483. * The current clipping context.
  21484. *
  21485. * @type {?ClippingContext}
  21486. * @default null
  21487. */
  21488. this.clippingContext = null;
  21489. /**
  21490. * This flag can be used for type testing.
  21491. *
  21492. * @type {boolean}
  21493. * @readonly
  21494. * @default true
  21495. */
  21496. this.isRenderContext = true;
  21497. }
  21498. /**
  21499. * Returns the cache key of this render context.
  21500. *
  21501. * @return {number} The cache key.
  21502. */
  21503. getCacheKey() {
  21504. return getCacheKey( this );
  21505. }
  21506. }
  21507. /**
  21508. * Computes a cache key for the given render context. This key
  21509. * should identify the render target state so it is possible to
  21510. * configure the correct attachments in the respective backend.
  21511. *
  21512. * @param {RenderContext} renderContext - The render context.
  21513. * @return {number} The cache key.
  21514. */
  21515. function getCacheKey( renderContext ) {
  21516. const { textures, activeCubeFace } = renderContext;
  21517. const values = [ activeCubeFace ];
  21518. for ( const texture of textures ) {
  21519. values.push( texture.id );
  21520. }
  21521. return hashArray( values );
  21522. }
  21523. const _chainKeys$3 = [];
  21524. const _defaultScene = /*@__PURE__*/ new Scene();
  21525. const _defaultCamera = /*@__PURE__*/ new Camera();
  21526. /**
  21527. * This module manages the render contexts of the renderer.
  21528. *
  21529. * @private
  21530. */
  21531. class RenderContexts {
  21532. /**
  21533. * Constructs a new render context management component.
  21534. */
  21535. constructor() {
  21536. /**
  21537. * A dictionary that manages render contexts in chain maps
  21538. * for each attachment state.
  21539. *
  21540. * @type {Object<string,ChainMap>}
  21541. */
  21542. this.chainMaps = {};
  21543. }
  21544. /**
  21545. * Returns a render context for the given scene, camera and render target.
  21546. *
  21547. * @param {Scene} scene - The scene.
  21548. * @param {Camera} camera - The camera that is used to render the scene.
  21549. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  21550. * @return {RenderContext} The render context.
  21551. */
  21552. get( scene, camera, renderTarget = null ) {
  21553. _chainKeys$3[ 0 ] = scene;
  21554. _chainKeys$3[ 1 ] = camera;
  21555. let attachmentState;
  21556. if ( renderTarget === null ) {
  21557. attachmentState = 'default';
  21558. } else {
  21559. const format = renderTarget.texture.format;
  21560. const count = renderTarget.textures.length;
  21561. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  21562. }
  21563. const chainMap = this._getChainMap( attachmentState );
  21564. let renderState = chainMap.get( _chainKeys$3 );
  21565. if ( renderState === undefined ) {
  21566. renderState = new RenderContext();
  21567. chainMap.set( _chainKeys$3, renderState );
  21568. }
  21569. _chainKeys$3.length = 0;
  21570. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  21571. return renderState;
  21572. }
  21573. /**
  21574. * Returns a render context intended for clear operations.
  21575. *
  21576. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  21577. * @return {RenderContext} The render context.
  21578. */
  21579. getForClear( renderTarget = null ) {
  21580. return this.get( _defaultScene, _defaultCamera, renderTarget );
  21581. }
  21582. /**
  21583. * Returns a chain map for the given attachment state.
  21584. *
  21585. * @private
  21586. * @param {string} attachmentState - The attachment state.
  21587. * @return {ChainMap} The chain map.
  21588. */
  21589. _getChainMap( attachmentState ) {
  21590. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  21591. }
  21592. /**
  21593. * Frees internal resources.
  21594. */
  21595. dispose() {
  21596. this.chainMaps = {};
  21597. }
  21598. }
  21599. const _size$3 = /*@__PURE__*/ new Vector3();
  21600. /**
  21601. * This module manages the textures of the renderer.
  21602. *
  21603. * @private
  21604. * @augments DataMap
  21605. */
  21606. class Textures extends DataMap {
  21607. /**
  21608. * Constructs a new texture management component.
  21609. *
  21610. * @param {Renderer} renderer - The renderer.
  21611. * @param {Backend} backend - The renderer's backend.
  21612. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21613. */
  21614. constructor( renderer, backend, info ) {
  21615. super();
  21616. /**
  21617. * The renderer.
  21618. *
  21619. * @type {Renderer}
  21620. */
  21621. this.renderer = renderer;
  21622. /**
  21623. * The backend.
  21624. *
  21625. * @type {Backend}
  21626. */
  21627. this.backend = backend;
  21628. /**
  21629. * Renderer component for managing metrics and monitoring data.
  21630. *
  21631. * @type {Info}
  21632. */
  21633. this.info = info;
  21634. }
  21635. /**
  21636. * Updates the given render target. Based on the given render target configuration,
  21637. * it updates the texture states representing the attachments of the framebuffer.
  21638. *
  21639. * @param {RenderTarget} renderTarget - The render target to update.
  21640. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  21641. */
  21642. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  21643. const renderTargetData = this.get( renderTarget );
  21644. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  21645. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  21646. const textures = renderTarget.textures;
  21647. const size = this.getSize( textures[ 0 ] );
  21648. const mipWidth = size.width >> activeMipmapLevel;
  21649. const mipHeight = size.height >> activeMipmapLevel;
  21650. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  21651. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  21652. let textureNeedsUpdate = false;
  21653. if ( depthTexture === undefined && useDepthTexture ) {
  21654. depthTexture = new DepthTexture();
  21655. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  21656. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  21657. depthTexture.image.width = mipWidth;
  21658. depthTexture.image.height = mipHeight;
  21659. depthTexture.image.depth = size.depth;
  21660. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  21661. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  21662. }
  21663. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  21664. textureNeedsUpdate = true;
  21665. if ( depthTexture ) {
  21666. depthTexture.needsUpdate = true;
  21667. depthTexture.image.width = mipWidth;
  21668. depthTexture.image.height = mipHeight;
  21669. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  21670. }
  21671. }
  21672. renderTargetData.width = size.width;
  21673. renderTargetData.height = size.height;
  21674. renderTargetData.textures = textures;
  21675. renderTargetData.depthTexture = depthTexture || null;
  21676. renderTargetData.depth = renderTarget.depthBuffer;
  21677. renderTargetData.stencil = renderTarget.stencilBuffer;
  21678. renderTargetData.renderTarget = renderTarget;
  21679. if ( renderTargetData.sampleCount !== sampleCount ) {
  21680. textureNeedsUpdate = true;
  21681. if ( depthTexture ) {
  21682. depthTexture.needsUpdate = true;
  21683. }
  21684. renderTargetData.sampleCount = sampleCount;
  21685. }
  21686. //
  21687. const options = { sampleCount };
  21688. // XR render targets require no texture updates
  21689. if ( renderTarget.isXRRenderTarget !== true ) {
  21690. for ( let i = 0; i < textures.length; i ++ ) {
  21691. const texture = textures[ i ];
  21692. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  21693. this.updateTexture( texture, options );
  21694. }
  21695. if ( depthTexture ) {
  21696. this.updateTexture( depthTexture, options );
  21697. }
  21698. }
  21699. // dispose handler
  21700. if ( renderTargetData.initialized !== true ) {
  21701. renderTargetData.initialized = true;
  21702. // dispose
  21703. const onDispose = () => {
  21704. renderTarget.removeEventListener( 'dispose', onDispose );
  21705. for ( let i = 0; i < textures.length; i ++ ) {
  21706. this._destroyTexture( textures[ i ] );
  21707. }
  21708. if ( depthTexture ) {
  21709. this._destroyTexture( depthTexture );
  21710. }
  21711. this.delete( renderTarget );
  21712. };
  21713. renderTarget.addEventListener( 'dispose', onDispose );
  21714. }
  21715. }
  21716. /**
  21717. * Updates the given texture. Depending on the texture state, this method
  21718. * triggers the upload of texture data to the GPU memory. If the texture data are
  21719. * not yet ready for the upload, it uses default texture data for as a placeholder.
  21720. *
  21721. * @param {Texture} texture - The texture to update.
  21722. * @param {Object} [options={}] - The options.
  21723. */
  21724. updateTexture( texture, options = {} ) {
  21725. const textureData = this.get( texture );
  21726. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  21727. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  21728. const backend = this.backend;
  21729. if ( isRenderTarget && textureData.initialized === true ) {
  21730. // it's an update
  21731. backend.destroySampler( texture );
  21732. backend.destroyTexture( texture );
  21733. }
  21734. //
  21735. if ( texture.isFramebufferTexture ) {
  21736. const renderTarget = this.renderer.getRenderTarget();
  21737. if ( renderTarget ) {
  21738. texture.type = renderTarget.texture.type;
  21739. } else {
  21740. texture.type = UnsignedByteType;
  21741. }
  21742. }
  21743. //
  21744. const { width, height, depth } = this.getSize( texture );
  21745. options.width = width;
  21746. options.height = height;
  21747. options.depth = depth;
  21748. options.needsMipmaps = this.needsMipmaps( texture );
  21749. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  21750. //
  21751. if ( isRenderTarget || texture.isStorageTexture === true ) {
  21752. backend.createSampler( texture );
  21753. backend.createTexture( texture, options );
  21754. textureData.generation = texture.version;
  21755. } else {
  21756. const needsCreate = textureData.initialized !== true;
  21757. if ( needsCreate ) backend.createSampler( texture );
  21758. if ( texture.version > 0 ) {
  21759. const image = texture.image;
  21760. if ( image === undefined ) {
  21761. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  21762. } else if ( image.complete === false ) {
  21763. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  21764. } else {
  21765. if ( texture.images ) {
  21766. const images = [];
  21767. for ( const image of texture.images ) {
  21768. images.push( image );
  21769. }
  21770. options.images = images;
  21771. } else {
  21772. options.image = image;
  21773. }
  21774. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  21775. backend.createTexture( texture, options );
  21776. textureData.isDefaultTexture = false;
  21777. textureData.generation = texture.version;
  21778. }
  21779. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  21780. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  21781. }
  21782. } else {
  21783. // async update
  21784. backend.createDefaultTexture( texture );
  21785. textureData.isDefaultTexture = true;
  21786. textureData.generation = texture.version;
  21787. }
  21788. }
  21789. // dispose handler
  21790. if ( textureData.initialized !== true ) {
  21791. textureData.initialized = true;
  21792. textureData.generation = texture.version;
  21793. //
  21794. this.info.memory.textures ++;
  21795. // dispose
  21796. const onDispose = () => {
  21797. texture.removeEventListener( 'dispose', onDispose );
  21798. this._destroyTexture( texture );
  21799. };
  21800. texture.addEventListener( 'dispose', onDispose );
  21801. }
  21802. //
  21803. textureData.version = texture.version;
  21804. }
  21805. /**
  21806. * Computes the size of the given texture and writes the result
  21807. * into the target vector. This vector is also returned by the
  21808. * method.
  21809. *
  21810. * If no texture data are available for the compute yet, the method
  21811. * returns default size values.
  21812. *
  21813. * @param {Texture} texture - The texture to compute the size for.
  21814. * @param {Vector3} target - The target vector.
  21815. * @return {Vector3} The target vector.
  21816. */
  21817. getSize( texture, target = _size$3 ) {
  21818. let image = texture.images ? texture.images[ 0 ] : texture.image;
  21819. if ( image ) {
  21820. if ( image.image !== undefined ) image = image.image;
  21821. if ( image instanceof HTMLVideoElement ) {
  21822. target.width = image.videoWidth || 1;
  21823. target.height = image.videoHeight || 1;
  21824. target.depth = 1;
  21825. } else if ( image instanceof VideoFrame ) {
  21826. target.width = image.displayWidth || 1;
  21827. target.height = image.displayHeight || 1;
  21828. target.depth = 1;
  21829. } else {
  21830. target.width = image.width || 1;
  21831. target.height = image.height || 1;
  21832. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  21833. }
  21834. } else {
  21835. target.width = target.height = target.depth = 1;
  21836. }
  21837. return target;
  21838. }
  21839. /**
  21840. * Computes the number of mipmap levels for the given texture.
  21841. *
  21842. * @param {Texture} texture - The texture.
  21843. * @param {number} width - The texture's width.
  21844. * @param {number} height - The texture's height.
  21845. * @return {number} The number of mipmap levels.
  21846. */
  21847. getMipLevels( texture, width, height ) {
  21848. let mipLevelCount;
  21849. if ( texture.isCompressedTexture ) {
  21850. if ( texture.mipmaps ) {
  21851. mipLevelCount = texture.mipmaps.length;
  21852. } else {
  21853. mipLevelCount = 1;
  21854. }
  21855. } else {
  21856. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  21857. }
  21858. return mipLevelCount;
  21859. }
  21860. /**
  21861. * Returns `true` if the given texture requires mipmaps.
  21862. *
  21863. * @param {Texture} texture - The texture.
  21864. * @return {boolean} Whether mipmaps are required or not.
  21865. */
  21866. needsMipmaps( texture ) {
  21867. return texture.isCompressedTexture === true || texture.generateMipmaps;
  21868. }
  21869. /**
  21870. * Frees internal resource when the given texture isn't
  21871. * required anymore.
  21872. *
  21873. * @param {Texture} texture - The texture to destroy.
  21874. */
  21875. _destroyTexture( texture ) {
  21876. if ( this.has( texture ) === true ) {
  21877. this.backend.destroySampler( texture );
  21878. this.backend.destroyTexture( texture );
  21879. this.delete( texture );
  21880. this.info.memory.textures --;
  21881. }
  21882. }
  21883. }
  21884. /**
  21885. * A four-component version of {@link Color} which is internally
  21886. * used by the renderer to represents clear color with alpha as
  21887. * one object.
  21888. *
  21889. * @private
  21890. * @augments Color
  21891. */
  21892. class Color4 extends Color {
  21893. /**
  21894. * Constructs a new four-component color.
  21895. * You can also pass a single THREE.Color, hex or
  21896. * string argument to this constructor.
  21897. *
  21898. * @param {number|string} [r=1] - The red value.
  21899. * @param {number} [g=1] - The green value.
  21900. * @param {number} [b=1] - The blue value.
  21901. * @param {number} [a=1] - The alpha value.
  21902. */
  21903. constructor( r, g, b, a = 1 ) {
  21904. super( r, g, b );
  21905. this.a = a;
  21906. }
  21907. /**
  21908. * Overwrites the default to honor alpha.
  21909. * You can also pass a single THREE.Color, hex or
  21910. * string argument to this method.
  21911. *
  21912. * @param {number|string|Color} r - The red value.
  21913. * @param {number} [g] - The green value.
  21914. * @param {number} [b] - The blue value.
  21915. * @param {number} [a=1] - The alpha value.
  21916. * @return {Color4} A reference to this object.
  21917. */
  21918. set( r, g, b, a = 1 ) {
  21919. this.a = a;
  21920. return super.set( r, g, b );
  21921. }
  21922. /**
  21923. * Overwrites the default to honor alpha.
  21924. *
  21925. * @param {Color4} color - The color to copy.
  21926. * @return {Color4} A reference to this object.
  21927. */
  21928. copy( color ) {
  21929. if ( color.a !== undefined ) this.a = color.a;
  21930. return super.copy( color );
  21931. }
  21932. /**
  21933. * Overwrites the default to honor alpha.
  21934. *
  21935. * @return {Color4} The cloned color.
  21936. */
  21937. clone() {
  21938. return new this.constructor( this.r, this.g, this.b, this.a );
  21939. }
  21940. }
  21941. /**
  21942. * Special version of {@link PropertyNode} which is used for parameters.
  21943. *
  21944. * @augments PropertyNode
  21945. */
  21946. class ParameterNode extends PropertyNode {
  21947. static get type() {
  21948. return 'ParameterNode';
  21949. }
  21950. /**
  21951. * Constructs a new parameter node.
  21952. *
  21953. * @param {string} nodeType - The type of the node.
  21954. * @param {?string} [name=null] - The name of the parameter in the shader.
  21955. */
  21956. constructor( nodeType, name = null ) {
  21957. super( nodeType, name );
  21958. /**
  21959. * This flag can be used for type testing.
  21960. *
  21961. * @type {boolean}
  21962. * @readonly
  21963. * @default true
  21964. */
  21965. this.isParameterNode = true;
  21966. }
  21967. getHash() {
  21968. return this.uuid;
  21969. }
  21970. generate() {
  21971. return this.name;
  21972. }
  21973. }
  21974. /**
  21975. * TSL function for creating a parameter node.
  21976. *
  21977. * @tsl
  21978. * @function
  21979. * @param {string} type - The type of the node.
  21980. * @param {?string} name - The name of the parameter in the shader.
  21981. * @returns {ParameterNode}
  21982. */
  21983. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  21984. /**
  21985. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  21986. * They are usually needed in cases like `If`, `Else`.
  21987. *
  21988. * @augments Node
  21989. */
  21990. class StackNode extends Node {
  21991. static get type() {
  21992. return 'StackNode';
  21993. }
  21994. /**
  21995. * Constructs a new stack node.
  21996. *
  21997. * @param {?StackNode} [parent=null] - The parent stack node.
  21998. */
  21999. constructor( parent = null ) {
  22000. super();
  22001. /**
  22002. * List of nodes.
  22003. *
  22004. * @type {Array<Node>}
  22005. */
  22006. this.nodes = [];
  22007. /**
  22008. * The output node.
  22009. *
  22010. * @type {?Node}
  22011. * @default null
  22012. */
  22013. this.outputNode = null;
  22014. /**
  22015. * The parent stack node.
  22016. *
  22017. * @type {?StackNode}
  22018. * @default null
  22019. */
  22020. this.parent = parent;
  22021. /**
  22022. * The current conditional node.
  22023. *
  22024. * @private
  22025. * @type {ConditionalNode}
  22026. * @default null
  22027. */
  22028. this._currentCond = null;
  22029. /**
  22030. * The expression node. Only
  22031. * relevant for Switch/Case.
  22032. *
  22033. * @private
  22034. * @type {Node}
  22035. * @default null
  22036. */
  22037. this._expressionNode = null;
  22038. /**
  22039. * This flag can be used for type testing.
  22040. *
  22041. * @type {boolean}
  22042. * @readonly
  22043. * @default true
  22044. */
  22045. this.isStackNode = true;
  22046. }
  22047. getNodeType( builder ) {
  22048. return this.hasOutput ? this.outputNode.getNodeType( builder ) : 'void';
  22049. }
  22050. getMemberType( builder, name ) {
  22051. return this.hasOutput ? this.outputNode.getMemberType( builder, name ) : 'void';
  22052. }
  22053. /**
  22054. * Adds a node to this stack.
  22055. *
  22056. * @param {Node} node - The node to add.
  22057. * @return {StackNode} A reference to this stack node.
  22058. */
  22059. add( node ) {
  22060. if ( node.isNode !== true ) {
  22061. console.error( 'THREE.TSL: Invalid node added to stack.' );
  22062. return this;
  22063. }
  22064. this.nodes.push( node );
  22065. return this;
  22066. }
  22067. /**
  22068. * Represent an `if` statement in TSL.
  22069. *
  22070. * @param {Node} boolNode - Represents the condition.
  22071. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22072. * @return {StackNode} A reference to this stack node.
  22073. */
  22074. If( boolNode, method ) {
  22075. const methodNode = new ShaderNode( method );
  22076. this._currentCond = select( boolNode, methodNode );
  22077. return this.add( this._currentCond );
  22078. }
  22079. /**
  22080. * Represent an `elseif` statement in TSL.
  22081. *
  22082. * @param {Node} boolNode - Represents the condition.
  22083. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22084. * @return {StackNode} A reference to this stack node.
  22085. */
  22086. ElseIf( boolNode, method ) {
  22087. const methodNode = new ShaderNode( method );
  22088. const ifNode = select( boolNode, methodNode );
  22089. this._currentCond.elseNode = ifNode;
  22090. this._currentCond = ifNode;
  22091. return this;
  22092. }
  22093. /**
  22094. * Represent an `else` statement in TSL.
  22095. *
  22096. * @param {Function} method - TSL code which is executed in the `else` case.
  22097. * @return {StackNode} A reference to this stack node.
  22098. */
  22099. Else( method ) {
  22100. this._currentCond.elseNode = new ShaderNode( method );
  22101. return this;
  22102. }
  22103. /**
  22104. * Represents a `switch` statement in TSL.
  22105. *
  22106. * @param {any} expression - Represents the expression.
  22107. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22108. * @return {StackNode} A reference to this stack node.
  22109. */
  22110. Switch( expression ) {
  22111. this._expressionNode = nodeObject( expression );
  22112. return this;
  22113. }
  22114. /**
  22115. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  22116. * The last parameter must be the callback method that should be executed in the `true` case.
  22117. *
  22118. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  22119. * @return {StackNode} A reference to this stack node.
  22120. */
  22121. Case( ...params ) {
  22122. const caseNodes = [];
  22123. // extract case nodes from the parameter list
  22124. if ( params.length >= 2 ) {
  22125. for ( let i = 0; i < params.length - 1; i ++ ) {
  22126. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  22127. }
  22128. } else {
  22129. console.error( 'THREE.TSL: Invalid parameter length. Case() requires at least two parameters.' );
  22130. }
  22131. // extract method
  22132. const method = params[ params.length - 1 ];
  22133. const methodNode = new ShaderNode( method );
  22134. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  22135. let caseNode = caseNodes[ 0 ];
  22136. for ( let i = 1; i < caseNodes.length; i ++ ) {
  22137. caseNode = caseNode.or( caseNodes[ i ] );
  22138. }
  22139. // build condition
  22140. const condNode = select( caseNode, methodNode );
  22141. if ( this._currentCond === null ) {
  22142. this._currentCond = condNode;
  22143. return this.add( this._currentCond );
  22144. } else {
  22145. this._currentCond.elseNode = condNode;
  22146. this._currentCond = condNode;
  22147. return this;
  22148. }
  22149. }
  22150. /**
  22151. * Represents the default code block of a Switch/Case statement.
  22152. *
  22153. * @param {Function} method - TSL code which is executed in the `else` case.
  22154. * @return {StackNode} A reference to this stack node.
  22155. */
  22156. Default( method ) {
  22157. this.Else( method );
  22158. return this;
  22159. }
  22160. setup( builder ) {
  22161. const nodeProperties = builder.getNodeProperties( this );
  22162. let index = 0;
  22163. for ( const childNode of this.getChildren() ) {
  22164. if ( childNode.isVarNode && childNode.intent === true ) {
  22165. const properties = builder.getNodeProperties( childNode );
  22166. if ( properties.assign !== true ) {
  22167. continue;
  22168. }
  22169. }
  22170. nodeProperties[ 'node' + index ++ ] = childNode;
  22171. }
  22172. // return a outputNode if exists or null
  22173. return nodeProperties.outputNode || null;
  22174. }
  22175. get hasOutput() {
  22176. return this.outputNode && this.outputNode.isNode;
  22177. }
  22178. build( builder, ...params ) {
  22179. const previousBuildStack = builder.currentStack;
  22180. const previousStack = getCurrentStack();
  22181. setCurrentStack( this );
  22182. builder.currentStack = this;
  22183. const buildStage = builder.buildStage;
  22184. for ( const node of this.nodes ) {
  22185. if ( node.isVarNode && node.intent === true ) {
  22186. const properties = builder.getNodeProperties( node );
  22187. if ( properties.assign !== true ) {
  22188. continue;
  22189. }
  22190. }
  22191. if ( buildStage === 'setup' ) {
  22192. node.build( builder );
  22193. } else if ( buildStage === 'analyze' ) {
  22194. node.build( builder, this );
  22195. } else if ( buildStage === 'generate' ) {
  22196. const stages = builder.getDataFromNode( node, 'any' ).stages;
  22197. const parents = stages && stages[ builder.shaderStage ];
  22198. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  22199. continue; // skip var nodes that are only used in .toVarying()
  22200. }
  22201. node.build( builder, 'void' );
  22202. }
  22203. }
  22204. //
  22205. let result;
  22206. if ( this.hasOutput ) {
  22207. result = this.outputNode.build( builder, ...params );
  22208. } else {
  22209. result = super.build( builder, ...params );
  22210. }
  22211. setCurrentStack( previousStack );
  22212. builder.currentStack = previousBuildStack;
  22213. return result;
  22214. }
  22215. }
  22216. /**
  22217. * TSL function for creating a stack node.
  22218. *
  22219. * @tsl
  22220. * @function
  22221. * @param {?StackNode} [parent=null] - The parent stack node.
  22222. * @returns {StackNode}
  22223. */
  22224. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  22225. /**
  22226. * Generates a layout for struct members.
  22227. * This function takes an object representing struct members and returns an array of member layouts.
  22228. * Each member layout includes the member's name, type, and whether it is atomic.
  22229. *
  22230. * @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.
  22231. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  22232. */
  22233. function getMembersLayout( members ) {
  22234. return Object.entries( members ).map( ( [ name, value ] ) => {
  22235. if ( typeof value === 'string' ) {
  22236. return { name, type: value, atomic: false };
  22237. }
  22238. return { name, type: value.type, atomic: value.atomic || false };
  22239. } );
  22240. }
  22241. /**
  22242. * Represents a struct type node in the node-based system.
  22243. * This class is used to define and manage the layout and types of struct members.
  22244. * It extends the base Node class and provides methods to get the length of the struct,
  22245. * retrieve member types, and generate the struct type for a builder.
  22246. *
  22247. * @augments Node
  22248. */
  22249. class StructTypeNode extends Node {
  22250. static get type() {
  22251. return 'StructTypeNode';
  22252. }
  22253. /**
  22254. * Creates an instance of StructTypeNode.
  22255. *
  22256. * @param {Object} membersLayout - The layout of the members for the struct.
  22257. * @param {?string} [name=null] - The optional name of the struct.
  22258. */
  22259. constructor( membersLayout, name = null ) {
  22260. super( 'struct' );
  22261. /**
  22262. * The layout of the members for the struct
  22263. *
  22264. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  22265. */
  22266. this.membersLayout = getMembersLayout( membersLayout );
  22267. /**
  22268. * The name of the struct.
  22269. *
  22270. * @type {?string}
  22271. * @default null
  22272. */
  22273. this.name = name;
  22274. /**
  22275. * This flag can be used for type testing.
  22276. *
  22277. * @type {boolean}
  22278. * @readonly
  22279. * @default true
  22280. */
  22281. this.isStructLayoutNode = true;
  22282. }
  22283. /**
  22284. * Returns the length of the struct.
  22285. * The length is calculated by summing the lengths of the struct's members.
  22286. *
  22287. * @returns {number} The length of the struct.
  22288. */
  22289. getLength() {
  22290. const GPU_CHUNK_BYTES = 8;
  22291. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  22292. let offset = 0; // global buffer offset in bytes
  22293. for ( const member of this.membersLayout ) {
  22294. const type = member.type;
  22295. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  22296. const boundary = getByteBoundaryFromType( type );
  22297. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  22298. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  22299. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  22300. offset += chunkPadding;
  22301. // Check for chunk overflow
  22302. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  22303. // Add padding to the end of the chunk
  22304. offset += ( GPU_CHUNK_BYTES - chunkStart );
  22305. }
  22306. offset += itemSize;
  22307. }
  22308. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  22309. }
  22310. getMemberType( builder, name ) {
  22311. const member = this.membersLayout.find( m => m.name === name );
  22312. return member ? member.type : 'void';
  22313. }
  22314. getNodeType( builder ) {
  22315. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  22316. return structType.name;
  22317. }
  22318. setup( builder ) {
  22319. builder.addInclude( this );
  22320. }
  22321. generate( builder ) {
  22322. return this.getNodeType( builder );
  22323. }
  22324. }
  22325. /**
  22326. * StructNode allows to create custom structures with multiple members.
  22327. * This can also be used to define structures in attribute and uniform data.
  22328. *
  22329. * ```js
  22330. * // Define a custom struct
  22331. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  22332. *
  22333. * // Create a new instance of the struct
  22334. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  22335. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  22336. *
  22337. * // Access the struct members
  22338. * const min = bb.get( 'min' );
  22339. *
  22340. * // Assign a new value to a member
  22341. * min.assign( vec3() );
  22342. * ```
  22343. * @augments Node
  22344. */
  22345. class StructNode extends Node {
  22346. static get type() {
  22347. return 'StructNode';
  22348. }
  22349. constructor( structLayoutNode, values ) {
  22350. super( 'vec3' );
  22351. this.structLayoutNode = structLayoutNode;
  22352. this.values = values;
  22353. this.isStructNode = true;
  22354. }
  22355. getNodeType( builder ) {
  22356. return this.structLayoutNode.getNodeType( builder );
  22357. }
  22358. getMemberType( builder, name ) {
  22359. return this.structLayoutNode.getMemberType( builder, name );
  22360. }
  22361. generate( builder ) {
  22362. const nodeVar = builder.getVarFromNode( this );
  22363. const structType = nodeVar.type;
  22364. const propertyName = builder.getPropertyName( nodeVar );
  22365. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structLayoutNode.membersLayout, this.values ) }`, this );
  22366. return nodeVar.name;
  22367. }
  22368. }
  22369. /**
  22370. * TSL function for creating a struct node.
  22371. *
  22372. * @tsl
  22373. * @function
  22374. * @param {Object} membersLayout - The layout of the struct members.
  22375. * @param {?string} [name=null] - The name of the struct.
  22376. * @returns {Function} The struct function.
  22377. */
  22378. const struct = ( membersLayout, name = null ) => {
  22379. const structLayout = new StructTypeNode( membersLayout, name );
  22380. const struct = ( ...params ) => {
  22381. let values = null;
  22382. if ( params.length > 0 ) {
  22383. if ( params[ 0 ].isNode ) {
  22384. values = {};
  22385. const names = Object.keys( membersLayout );
  22386. for ( let i = 0; i < params.length; i ++ ) {
  22387. values[ names[ i ] ] = params[ i ];
  22388. }
  22389. } else {
  22390. values = params[ 0 ];
  22391. }
  22392. }
  22393. return nodeObject( new StructNode( structLayout, values ) );
  22394. };
  22395. struct.layout = structLayout;
  22396. struct.isStruct = true;
  22397. return struct;
  22398. };
  22399. /**
  22400. * This node can be used to define multiple outputs in a shader programs.
  22401. *
  22402. * @augments Node
  22403. */
  22404. class OutputStructNode extends Node {
  22405. static get type() {
  22406. return 'OutputStructNode';
  22407. }
  22408. /**
  22409. * Constructs a new output struct node. The constructor can be invoked with an
  22410. * arbitrary number of nodes representing the members.
  22411. *
  22412. * @param {...Node} members - A parameter list of nodes.
  22413. */
  22414. constructor( ...members ) {
  22415. super();
  22416. /**
  22417. * An array of nodes which defines the output.
  22418. *
  22419. * @type {Array<Node>}
  22420. */
  22421. this.members = members;
  22422. /**
  22423. * This flag can be used for type testing.
  22424. *
  22425. * @type {boolean}
  22426. * @readonly
  22427. * @default true
  22428. */
  22429. this.isOutputStructNode = true;
  22430. }
  22431. getNodeType( builder ) {
  22432. const properties = builder.getNodeProperties( this );
  22433. if ( properties.membersLayout === undefined ) {
  22434. const members = this.members;
  22435. const membersLayout = [];
  22436. for ( let i = 0; i < members.length; i ++ ) {
  22437. const name = 'm' + i;
  22438. const type = members[ i ].getNodeType( builder );
  22439. membersLayout.push( { name, type, index: i } );
  22440. }
  22441. properties.membersLayout = membersLayout;
  22442. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  22443. }
  22444. return properties.structType.name;
  22445. }
  22446. generate( builder ) {
  22447. const propertyName = builder.getOutputStructName();
  22448. const members = this.members;
  22449. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  22450. for ( let i = 0; i < members.length; i ++ ) {
  22451. const snippet = members[ i ].build( builder );
  22452. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  22453. }
  22454. return propertyName;
  22455. }
  22456. }
  22457. /**
  22458. * TSL function for creating an output struct node.
  22459. *
  22460. * @tsl
  22461. * @function
  22462. * @param {...Node} members - A parameter list of nodes.
  22463. * @returns {OutputStructNode}
  22464. */
  22465. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  22466. /**
  22467. * Returns the MRT texture index for the given name.
  22468. *
  22469. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  22470. * @param {string} name - The name of the MRT texture which index is requested.
  22471. * @return {number} The texture index.
  22472. */
  22473. function getTextureIndex( textures, name ) {
  22474. for ( let i = 0; i < textures.length; i ++ ) {
  22475. if ( textures[ i ].name === name ) {
  22476. return i;
  22477. }
  22478. }
  22479. return -1;
  22480. }
  22481. /**
  22482. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  22483. * post-processing is shown below:
  22484. * ```js
  22485. * const mrtNode = mrt( {
  22486. * output: output,
  22487. * normal: normalView
  22488. * } ) );
  22489. * ```
  22490. * The MRT output is defined as a dictionary.
  22491. *
  22492. * @augments OutputStructNode
  22493. */
  22494. class MRTNode extends OutputStructNode {
  22495. static get type() {
  22496. return 'MRTNode';
  22497. }
  22498. /**
  22499. * Constructs a new output struct node.
  22500. *
  22501. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  22502. */
  22503. constructor( outputNodes ) {
  22504. super();
  22505. /**
  22506. * A dictionary representing the MRT outputs. The key
  22507. * is the name of the output, the value the node which produces
  22508. * the output result.
  22509. *
  22510. * @type {Object<string, Node>}
  22511. */
  22512. this.outputNodes = outputNodes;
  22513. /**
  22514. * This flag can be used for type testing.
  22515. *
  22516. * @type {boolean}
  22517. * @readonly
  22518. * @default true
  22519. */
  22520. this.isMRTNode = true;
  22521. }
  22522. /**
  22523. * Returns `true` if the MRT node has an output with the given name.
  22524. *
  22525. * @param {string} name - The name of the output.
  22526. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  22527. */
  22528. has( name ) {
  22529. return this.outputNodes[ name ] !== undefined;
  22530. }
  22531. /**
  22532. * Returns the output node for the given name.
  22533. *
  22534. * @param {string} name - The name of the output.
  22535. * @return {Node} The output node.
  22536. */
  22537. get( name ) {
  22538. return this.outputNodes[ name ];
  22539. }
  22540. /**
  22541. * Merges the outputs of the given MRT node with the outputs of this node.
  22542. *
  22543. * @param {MRTNode} mrtNode - The MRT to merge.
  22544. * @return {MRTNode} A new MRT node with merged outputs..
  22545. */
  22546. merge( mrtNode ) {
  22547. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  22548. return mrt( outputs );
  22549. }
  22550. setup( builder ) {
  22551. const outputNodes = this.outputNodes;
  22552. const mrt = builder.renderer.getRenderTarget();
  22553. const members = [];
  22554. const textures = mrt.textures;
  22555. for ( const name in outputNodes ) {
  22556. const index = getTextureIndex( textures, name );
  22557. members[ index ] = vec4( outputNodes[ name ] );
  22558. }
  22559. this.members = members;
  22560. return super.setup( builder );
  22561. }
  22562. }
  22563. /**
  22564. * TSL function for creating a MRT node.
  22565. *
  22566. * @tsl
  22567. * @function
  22568. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  22569. * @returns {MRTNode}
  22570. */
  22571. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  22572. /**
  22573. * Generates a hash value in the range `[0, 1]` from the given seed.
  22574. *
  22575. * @tsl
  22576. * @function
  22577. * @param {Node<float>} seed - The seed.
  22578. * @return {Node<float>} The hash value.
  22579. */
  22580. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  22581. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  22582. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  22583. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  22584. const result = word.shiftRight( 22 ).bitXor( word );
  22585. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  22586. } );
  22587. /**
  22588. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22589. * The corners are mapped to `0` and the center to `1`.
  22590. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22591. *
  22592. * @tsl
  22593. * @function
  22594. * @param {Node<float>} x - The value to remap.
  22595. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  22596. * @return {Node<float>} The remapped value.
  22597. */
  22598. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  22599. /**
  22600. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22601. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  22602. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22603. *
  22604. * @tsl
  22605. * @function
  22606. * @param {Node<float>} x - The value to remap.
  22607. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  22608. * @return {Node<float>} The remapped value.
  22609. */
  22610. 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 ) );
  22611. /**
  22612. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22613. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  22614. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22615. *
  22616. * @tsl
  22617. * @function
  22618. * @param {Node<float>} x - The value to remap.
  22619. * @param {Node<float>} a - First control parameter.
  22620. * @param {Node<float>} b - Second control parameter.
  22621. * @return {Node<float>} The remapped value.
  22622. */
  22623. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  22624. /**
  22625. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  22626. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22627. *
  22628. * @tsl
  22629. * @function
  22630. * @param {Node<float>} x - The value to compute the sin for.
  22631. * @param {Node<float>} k - Controls the amount of bounces.
  22632. * @return {Node<float>} The result value.
  22633. */
  22634. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  22635. // https://github.com/cabbibo/glsl-tri-noise-3d
  22636. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  22637. return x.fract().sub( .5 ).abs();
  22638. } ).setLayout( {
  22639. name: 'tri',
  22640. type: 'float',
  22641. inputs: [
  22642. { name: 'x', type: 'float' }
  22643. ]
  22644. } );
  22645. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  22646. 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. ) ) ) ) );
  22647. } ).setLayout( {
  22648. name: 'tri3',
  22649. type: 'vec3',
  22650. inputs: [
  22651. { name: 'p', type: 'vec3' }
  22652. ]
  22653. } );
  22654. /**
  22655. * Generates a noise value from the given position, speed and time parameters.
  22656. *
  22657. * @tsl
  22658. * @function
  22659. * @param {Node<vec3>} position - The position.
  22660. * @param {Node<float>} speed - The speed.
  22661. * @param {Node<float>} time - The time.
  22662. * @return {Node<float>} The generated noise.
  22663. */
  22664. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  22665. const p = vec3( position ).toVar();
  22666. const z = float( 1.4 ).toVar();
  22667. const rz = float( 0.0 ).toVar();
  22668. const bp = vec3( p ).toVar();
  22669. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  22670. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  22671. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  22672. bp.mulAssign( 1.8 );
  22673. z.mulAssign( 1.5 );
  22674. p.mulAssign( 1.2 );
  22675. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  22676. rz.addAssign( t.div( z ) );
  22677. bp.addAssign( 0.14 );
  22678. } );
  22679. return rz;
  22680. } ).setLayout( {
  22681. name: 'triNoise3D',
  22682. type: 'float',
  22683. inputs: [
  22684. { name: 'position', type: 'vec3' },
  22685. { name: 'speed', type: 'float' },
  22686. { name: 'time', type: 'float' }
  22687. ]
  22688. } );
  22689. /**
  22690. * This class allows to define multiple overloaded versions
  22691. * of the same function. Depending on the parameters of the function
  22692. * call, the node picks the best-fit overloaded version.
  22693. *
  22694. * @augments Node
  22695. */
  22696. class FunctionOverloadingNode extends Node {
  22697. static get type() {
  22698. return 'FunctionOverloadingNode';
  22699. }
  22700. /**
  22701. * Constructs a new function overloading node.
  22702. *
  22703. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  22704. * @param {...Node} parametersNodes - A list of parameter nodes.
  22705. */
  22706. constructor( functionNodes = [], ...parametersNodes ) {
  22707. super();
  22708. /**
  22709. * Array of `Fn` function definitions.
  22710. *
  22711. * @type {Array<Function>}
  22712. */
  22713. this.functionNodes = functionNodes;
  22714. /**
  22715. * A list of parameter nodes.
  22716. *
  22717. * @type {Array<Node>}
  22718. */
  22719. this.parametersNodes = parametersNodes;
  22720. /**
  22721. * The selected overloaded function call.
  22722. *
  22723. * @private
  22724. * @type {ShaderCallNodeInternal}
  22725. */
  22726. this._candidateFnCall = null;
  22727. /**
  22728. * This node is marked as global.
  22729. *
  22730. * @type {boolean}
  22731. * @default true
  22732. */
  22733. this.global = true;
  22734. }
  22735. /**
  22736. * This method is overwritten since the node type is inferred from
  22737. * the function's return type.
  22738. *
  22739. * @param {NodeBuilder} builder - The current node builder.
  22740. * @return {string} The node type.
  22741. */
  22742. getNodeType() {
  22743. return this.functionNodes[ 0 ].shaderNode.layout.type;
  22744. }
  22745. setup( builder ) {
  22746. const params = this.parametersNodes;
  22747. let candidateFnCall = this._candidateFnCall;
  22748. if ( candidateFnCall === null ) {
  22749. let candidateFn = null;
  22750. let candidateScore = -1;
  22751. for ( const functionNode of this.functionNodes ) {
  22752. const shaderNode = functionNode.shaderNode;
  22753. const layout = shaderNode.layout;
  22754. if ( layout === null ) {
  22755. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  22756. }
  22757. const inputs = layout.inputs;
  22758. if ( params.length === inputs.length ) {
  22759. let score = 0;
  22760. for ( let i = 0; i < params.length; i ++ ) {
  22761. const param = params[ i ];
  22762. const input = inputs[ i ];
  22763. if ( param.getNodeType( builder ) === input.type ) {
  22764. score ++;
  22765. } else {
  22766. score = 0;
  22767. }
  22768. }
  22769. if ( score > candidateScore ) {
  22770. candidateFn = functionNode;
  22771. candidateScore = score;
  22772. }
  22773. }
  22774. }
  22775. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  22776. }
  22777. return candidateFnCall;
  22778. }
  22779. }
  22780. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  22781. /**
  22782. * TSL function for creating a function overloading node.
  22783. *
  22784. * @tsl
  22785. * @function
  22786. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  22787. * @returns {FunctionOverloadingNode}
  22788. */
  22789. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  22790. /**
  22791. * Represents the elapsed time in seconds.
  22792. *
  22793. * @tsl
  22794. * @type {UniformNode<float>}
  22795. */
  22796. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  22797. /**
  22798. * Represents the delta time in seconds.
  22799. *
  22800. * @tsl
  22801. * @type {UniformNode<float>}
  22802. */
  22803. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  22804. /**
  22805. * Represents the current frame ID.
  22806. *
  22807. * @tsl
  22808. * @type {UniformNode<uint>}
  22809. */
  22810. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  22811. /**
  22812. * Generates a sine wave oscillation based on a timer.
  22813. *
  22814. * @tsl
  22815. * @function
  22816. * @param {Node<float>} t - The timer to generate the oscillation with.
  22817. * @return {Node<float>} The oscillation node.
  22818. */
  22819. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  22820. /**
  22821. * Generates a square wave oscillation based on a timer.
  22822. *
  22823. * @tsl
  22824. * @function
  22825. * @param {Node<float>} t - The timer to generate the oscillation with.
  22826. * @return {Node<float>} The oscillation node.
  22827. */
  22828. const oscSquare = ( t = time ) => t.fract().round();
  22829. /**
  22830. * Generates a triangle wave oscillation based on a timer.
  22831. *
  22832. * @tsl
  22833. * @function
  22834. * @param {Node<float>} t - The timer to generate the oscillation with.
  22835. * @return {Node<float>} The oscillation node.
  22836. */
  22837. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  22838. /**
  22839. * Generates a sawtooth wave oscillation based on a timer.
  22840. *
  22841. * @tsl
  22842. * @function
  22843. * @param {Node<float>} t - The timer to generate the oscillation with.
  22844. * @return {Node<float>} The oscillation node.
  22845. */
  22846. const oscSawtooth = ( t = time ) => t.fract();
  22847. /**
  22848. * Rotates the given uv coordinates around a center point
  22849. *
  22850. * @tsl
  22851. * @function
  22852. * @param {Node<vec2>} uv - The uv coordinates.
  22853. * @param {Node<float>} rotation - The rotation defined in radians.
  22854. * @param {Node<vec2>} center - The center of rotation
  22855. * @return {Node<vec2>} The rotated uv coordinates.
  22856. */
  22857. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  22858. return rotate( uv.sub( center ), rotation ).add( center );
  22859. } );
  22860. /**
  22861. * Applies a spherical warping effect to the given uv coordinates.
  22862. *
  22863. * @tsl
  22864. * @function
  22865. * @param {Node<vec2>} uv - The uv coordinates.
  22866. * @param {Node<float>} strength - The strength of the effect.
  22867. * @param {Node<vec2>} center - The center point
  22868. * @return {Node<vec2>} The updated uv coordinates.
  22869. */
  22870. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  22871. const delta = uv.sub( center );
  22872. const delta2 = delta.dot( delta );
  22873. const delta4 = delta2.mul( delta2 );
  22874. const deltaOffset = delta4.mul( strength );
  22875. return uv.add( delta.mul( deltaOffset ) );
  22876. } );
  22877. /**
  22878. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  22879. * oriented always towards the camera.
  22880. *
  22881. * ```js
  22882. * material.vertexNode = billboarding();
  22883. * ```
  22884. *
  22885. * @tsl
  22886. * @function
  22887. * @param {Object} config - The configuration object.
  22888. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  22889. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  22890. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  22891. * @return {Node<vec3>} The updated vertex position in clip space.
  22892. */
  22893. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  22894. let worldMatrix;
  22895. if ( position !== null ) {
  22896. worldMatrix = modelWorldMatrix.toVar();
  22897. worldMatrix[ 3 ][ 0 ] = position.x;
  22898. worldMatrix[ 3 ][ 1 ] = position.y;
  22899. worldMatrix[ 3 ][ 2 ] = position.z;
  22900. } else {
  22901. worldMatrix = modelWorldMatrix;
  22902. }
  22903. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  22904. if ( defined( horizontal ) ) {
  22905. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  22906. modelViewMatrix[ 0 ][ 1 ] = 0;
  22907. modelViewMatrix[ 0 ][ 2 ] = 0;
  22908. }
  22909. if ( defined( vertical ) ) {
  22910. modelViewMatrix[ 1 ][ 0 ] = 0;
  22911. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  22912. modelViewMatrix[ 1 ][ 2 ] = 0;
  22913. }
  22914. modelViewMatrix[ 2 ][ 0 ] = 0;
  22915. modelViewMatrix[ 2 ][ 1 ] = 0;
  22916. modelViewMatrix[ 2 ][ 2 ] = 1;
  22917. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  22918. } );
  22919. /**
  22920. * A special version of a screen uv function that involves a depth comparison
  22921. * when computing the final uvs. The function mitigates visual errors when
  22922. * using viewport texture nodes for refraction purposes. Without this function
  22923. * objects in front of a refractive surface might appear on the refractive surface
  22924. * which is incorrect.
  22925. *
  22926. * @tsl
  22927. * @function
  22928. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  22929. * @return {Node<vec2>} The update uv coordinates.
  22930. */
  22931. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  22932. const depth = linearDepth();
  22933. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  22934. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  22935. return finalUV;
  22936. } );
  22937. /**
  22938. * Can be used to compute texture coordinates for animated sprite sheets.
  22939. *
  22940. * ```js
  22941. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  22942. *
  22943. * material.colorNode = texture( spriteSheet, uvNode );
  22944. * ```
  22945. *
  22946. * @augments Node
  22947. */
  22948. class SpriteSheetUVNode extends Node {
  22949. static get type() {
  22950. return 'SpriteSheetUVNode';
  22951. }
  22952. /**
  22953. * Constructs a new sprite sheet uv node.
  22954. *
  22955. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22956. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  22957. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  22958. */
  22959. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  22960. super( 'vec2' );
  22961. /**
  22962. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22963. *
  22964. * @type {Node<vec2>}
  22965. */
  22966. this.countNode = countNode;
  22967. /**
  22968. * The uv node.
  22969. *
  22970. * @type {Node<vec2>}
  22971. */
  22972. this.uvNode = uvNode;
  22973. /**
  22974. * The node that defines the current frame/sprite.
  22975. *
  22976. * @type {Node<float>}
  22977. */
  22978. this.frameNode = frameNode;
  22979. }
  22980. setup() {
  22981. const { frameNode, uvNode, countNode } = this;
  22982. const { width, height } = countNode;
  22983. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  22984. const column = frameNum.mod( width );
  22985. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  22986. const scale = countNode.reciprocal();
  22987. const uvFrameOffset = vec2( column, row );
  22988. return uvNode.add( uvFrameOffset ).mul( scale );
  22989. }
  22990. }
  22991. /**
  22992. * TSL function for creating a sprite sheet uv node.
  22993. *
  22994. * @tsl
  22995. * @function
  22996. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22997. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  22998. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  22999. * @returns {SpriteSheetUVNode}
  23000. */
  23001. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  23002. /**
  23003. * TSL function for creating a triplanar textures node.
  23004. *
  23005. * Can be used for triplanar texture mapping.
  23006. *
  23007. * ```js
  23008. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  23009. * ```
  23010. *
  23011. * @tsl
  23012. * @function
  23013. * @param {Node} textureXNode - First texture node.
  23014. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23015. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23016. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23017. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23018. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23019. * @returns {Node<vec4>}
  23020. */
  23021. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  23022. // Reference: https://github.com/keijiro/StandardTriplanar
  23023. // Blending factor of triplanar mapping
  23024. let bf = normalNode.abs().normalize();
  23025. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  23026. // Triplanar mapping
  23027. const tx = positionNode.yz.mul( scaleNode );
  23028. const ty = positionNode.zx.mul( scaleNode );
  23029. const tz = positionNode.xy.mul( scaleNode );
  23030. // Base color
  23031. const textureX = textureXNode.value;
  23032. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  23033. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  23034. const cx = texture( textureX, tx ).mul( bf.x );
  23035. const cy = texture( textureY, ty ).mul( bf.y );
  23036. const cz = texture( textureZ, tz ).mul( bf.z );
  23037. return add( cx, cy, cz );
  23038. } );
  23039. /**
  23040. * TSL function for creating a triplanar textures node.
  23041. *
  23042. * @tsl
  23043. * @function
  23044. * @param {Node} textureXNode - First texture node.
  23045. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23046. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23047. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23048. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23049. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23050. * @returns {Node<vec4>}
  23051. */
  23052. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  23053. const _reflectorPlane = new Plane();
  23054. const _normal = new Vector3();
  23055. const _reflectorWorldPosition = new Vector3();
  23056. const _cameraWorldPosition = new Vector3();
  23057. const _rotationMatrix = new Matrix4();
  23058. const _lookAtPosition = new Vector3( 0, 0, -1 );
  23059. const clipPlane = new Vector4();
  23060. const _view = new Vector3();
  23061. const _target = new Vector3();
  23062. const _q = new Vector4();
  23063. const _size$2 = new Vector2();
  23064. const _defaultRT = new RenderTarget();
  23065. const _defaultUV = screenUV.flipX();
  23066. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  23067. let _inReflector = false;
  23068. /**
  23069. * This node can be used to implement mirror-like flat reflective surfaces.
  23070. *
  23071. * ```js
  23072. * const groundReflector = reflector();
  23073. * material.colorNode = groundReflector;
  23074. *
  23075. * const plane = new Mesh( geometry, material );
  23076. * plane.add( groundReflector.target );
  23077. * ```
  23078. *
  23079. * @augments TextureNode
  23080. */
  23081. class ReflectorNode extends TextureNode {
  23082. static get type() {
  23083. return 'ReflectorNode';
  23084. }
  23085. /**
  23086. * Constructs a new reflector node.
  23087. *
  23088. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23089. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23090. * @param {number} [parameters.resolution=1] - The resolution scale.
  23091. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23092. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23093. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23094. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  23095. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  23096. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  23097. */
  23098. constructor( parameters = {} ) {
  23099. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  23100. /**
  23101. * A reference to the internal reflector base node which holds the actual implementation.
  23102. *
  23103. * @private
  23104. * @type {ReflectorBaseNode}
  23105. * @default ReflectorBaseNode
  23106. */
  23107. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  23108. /**
  23109. * A reference to the internal depth node.
  23110. *
  23111. * @private
  23112. * @type {?Node}
  23113. * @default null
  23114. */
  23115. this._depthNode = null;
  23116. this.setUpdateMatrix( false );
  23117. }
  23118. /**
  23119. * A reference to the internal reflector node.
  23120. *
  23121. * @type {ReflectorBaseNode}
  23122. */
  23123. get reflector() {
  23124. return this._reflectorBaseNode;
  23125. }
  23126. /**
  23127. * A reference to 3D object the reflector is linked to.
  23128. *
  23129. * @type {Object3D}
  23130. */
  23131. get target() {
  23132. return this._reflectorBaseNode.target;
  23133. }
  23134. /**
  23135. * Returns a node representing the mirror's depth. That can be used
  23136. * to implement more advanced reflection effects like distance attenuation.
  23137. *
  23138. * @return {Node} The depth node.
  23139. */
  23140. getDepthNode() {
  23141. if ( this._depthNode === null ) {
  23142. if ( this._reflectorBaseNode.depth !== true ) {
  23143. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  23144. }
  23145. this._depthNode = nodeObject( new ReflectorNode( {
  23146. defaultTexture: _defaultRT.depthTexture,
  23147. reflector: this._reflectorBaseNode
  23148. } ) );
  23149. }
  23150. return this._depthNode;
  23151. }
  23152. setup( builder ) {
  23153. // ignore if used in post-processing
  23154. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  23155. return super.setup( builder );
  23156. }
  23157. clone() {
  23158. const newNode = new this.constructor( this.reflectorNode );
  23159. newNode.uvNode = this.uvNode;
  23160. newNode.levelNode = this.levelNode;
  23161. newNode.biasNode = this.biasNode;
  23162. newNode.sampler = this.sampler;
  23163. newNode.depthNode = this.depthNode;
  23164. newNode.compareNode = this.compareNode;
  23165. newNode.gradNode = this.gradNode;
  23166. newNode._reflectorBaseNode = this._reflectorBaseNode;
  23167. return newNode;
  23168. }
  23169. /**
  23170. * Frees internal resources. Should be called when the node is no longer in use.
  23171. */
  23172. dispose() {
  23173. super.dispose();
  23174. this._reflectorBaseNode.dispose();
  23175. }
  23176. }
  23177. /**
  23178. * Holds the actual implementation of the reflector.
  23179. *
  23180. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  23181. * in `ReflectorNode`, see #29619.
  23182. *
  23183. * @private
  23184. * @augments Node
  23185. */
  23186. class ReflectorBaseNode extends Node {
  23187. static get type() {
  23188. return 'ReflectorBaseNode';
  23189. }
  23190. /**
  23191. * Constructs a new reflector base node.
  23192. *
  23193. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  23194. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23195. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23196. * @param {number} [parameters.resolution=1] - The resolution scale.
  23197. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23198. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23199. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23200. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  23201. */
  23202. constructor( textureNode, parameters = {} ) {
  23203. super();
  23204. const {
  23205. target = new Object3D(),
  23206. resolution = 1,
  23207. generateMipmaps = false,
  23208. bounces = true,
  23209. depth = false,
  23210. samples = 0
  23211. } = parameters;
  23212. /**
  23213. * Represents the rendered reflections as a texture node.
  23214. *
  23215. * @type {TextureNode}
  23216. */
  23217. this.textureNode = textureNode;
  23218. /**
  23219. * The 3D object the reflector is linked to.
  23220. *
  23221. * @type {Object3D}
  23222. * @default {new Object3D()}
  23223. */
  23224. this.target = target;
  23225. /**
  23226. * The resolution scale.
  23227. *
  23228. * @type {number}
  23229. * @default {1}
  23230. */
  23231. this.resolution = resolution;
  23232. /**
  23233. * Whether mipmaps should be generated or not.
  23234. *
  23235. * @type {boolean}
  23236. * @default {false}
  23237. */
  23238. this.generateMipmaps = generateMipmaps;
  23239. /**
  23240. * Whether reflectors can render other reflector nodes or not.
  23241. *
  23242. * @type {boolean}
  23243. * @default {true}
  23244. */
  23245. this.bounces = bounces;
  23246. /**
  23247. * Whether depth data should be generated or not.
  23248. *
  23249. * @type {boolean}
  23250. * @default {false}
  23251. */
  23252. this.depth = depth;
  23253. /**
  23254. * The number of anti-aliasing samples for the render-target
  23255. *
  23256. * @type {number}
  23257. * @default {0}
  23258. */
  23259. this.samples = samples;
  23260. /**
  23261. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  23262. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  23263. *
  23264. * @type {string}
  23265. * @default 'render'
  23266. */
  23267. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  23268. /**
  23269. * Weak map for managing virtual cameras.
  23270. *
  23271. * @type {WeakMap<Camera, Camera>}
  23272. */
  23273. this.virtualCameras = new WeakMap();
  23274. /**
  23275. * Weak map for managing render targets.
  23276. *
  23277. * @type {Map<Camera, RenderTarget>}
  23278. */
  23279. this.renderTargets = new Map();
  23280. /**
  23281. * Force render even if reflector is facing away from camera.
  23282. *
  23283. * @type {boolean}
  23284. * @default {false}
  23285. */
  23286. this.forceUpdate = false;
  23287. /**
  23288. * Whether the reflector has been rendered or not.
  23289. *
  23290. * When the reflector is facing away from the camera,
  23291. * this flag is set to `false` and the texture will be empty(black).
  23292. *
  23293. * @type {boolean}
  23294. * @default {false}
  23295. */
  23296. this.hasOutput = false;
  23297. }
  23298. /**
  23299. * Updates the resolution of the internal render target.
  23300. *
  23301. * @private
  23302. * @param {RenderTarget} renderTarget - The render target to resize.
  23303. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  23304. */
  23305. _updateResolution( renderTarget, renderer ) {
  23306. const resolution = this.resolution;
  23307. renderer.getDrawingBufferSize( _size$2 );
  23308. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  23309. }
  23310. setup( builder ) {
  23311. this._updateResolution( _defaultRT, builder.renderer );
  23312. return super.setup( builder );
  23313. }
  23314. /**
  23315. * Frees internal resources. Should be called when the node is no longer in use.
  23316. */
  23317. dispose() {
  23318. super.dispose();
  23319. for ( const renderTarget of this.renderTargets.values() ) {
  23320. renderTarget.dispose();
  23321. }
  23322. }
  23323. /**
  23324. * Returns a virtual camera for the given camera. The virtual camera is used to
  23325. * render the scene from the reflector's view so correct reflections can be produced.
  23326. *
  23327. * @param {Camera} camera - The scene's camera.
  23328. * @return {Camera} The corresponding virtual camera.
  23329. */
  23330. getVirtualCamera( camera ) {
  23331. let virtualCamera = this.virtualCameras.get( camera );
  23332. if ( virtualCamera === undefined ) {
  23333. virtualCamera = camera.clone();
  23334. this.virtualCameras.set( camera, virtualCamera );
  23335. }
  23336. return virtualCamera;
  23337. }
  23338. /**
  23339. * Returns a render target for the given camera. The reflections are rendered
  23340. * into this render target.
  23341. *
  23342. * @param {Camera} camera - The scene's camera.
  23343. * @return {RenderTarget} The render target.
  23344. */
  23345. getRenderTarget( camera ) {
  23346. let renderTarget = this.renderTargets.get( camera );
  23347. if ( renderTarget === undefined ) {
  23348. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  23349. if ( this.generateMipmaps === true ) {
  23350. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  23351. renderTarget.texture.generateMipmaps = true;
  23352. }
  23353. if ( this.depth === true ) {
  23354. renderTarget.depthTexture = new DepthTexture();
  23355. }
  23356. this.renderTargets.set( camera, renderTarget );
  23357. }
  23358. return renderTarget;
  23359. }
  23360. updateBefore( frame ) {
  23361. if ( this.bounces === false && _inReflector ) return false;
  23362. _inReflector = true;
  23363. const { scene, camera, renderer, material } = frame;
  23364. const { target } = this;
  23365. const virtualCamera = this.getVirtualCamera( camera );
  23366. const renderTarget = this.getRenderTarget( virtualCamera );
  23367. renderer.getDrawingBufferSize( _size$2 );
  23368. this._updateResolution( renderTarget, renderer );
  23369. //
  23370. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  23371. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  23372. _rotationMatrix.extractRotation( target.matrixWorld );
  23373. _normal.set( 0, 0, 1 );
  23374. _normal.applyMatrix4( _rotationMatrix );
  23375. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  23376. // Avoid rendering when reflector is facing away unless forcing an update
  23377. const isFacingAway = _view.dot( _normal ) > 0;
  23378. let needsClear = false;
  23379. if ( isFacingAway === true && this.forceUpdate === false ) {
  23380. if ( this.hasOutput === false ) {
  23381. _inReflector = false;
  23382. return;
  23383. }
  23384. needsClear = true;
  23385. }
  23386. _view.reflect( _normal ).negate();
  23387. _view.add( _reflectorWorldPosition );
  23388. _rotationMatrix.extractRotation( camera.matrixWorld );
  23389. _lookAtPosition.set( 0, 0, -1 );
  23390. _lookAtPosition.applyMatrix4( _rotationMatrix );
  23391. _lookAtPosition.add( _cameraWorldPosition );
  23392. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  23393. _target.reflect( _normal ).negate();
  23394. _target.add( _reflectorWorldPosition );
  23395. //
  23396. virtualCamera.coordinateSystem = camera.coordinateSystem;
  23397. virtualCamera.position.copy( _view );
  23398. virtualCamera.up.set( 0, 1, 0 );
  23399. virtualCamera.up.applyMatrix4( _rotationMatrix );
  23400. virtualCamera.up.reflect( _normal );
  23401. virtualCamera.lookAt( _target );
  23402. virtualCamera.near = camera.near;
  23403. virtualCamera.far = camera.far;
  23404. virtualCamera.updateMatrixWorld();
  23405. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  23406. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  23407. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  23408. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  23409. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  23410. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  23411. const projectionMatrix = virtualCamera.projectionMatrix;
  23412. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  23413. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  23414. _q.z = -1;
  23415. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  23416. // Calculate the scaled plane vector
  23417. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  23418. const clipBias = 0;
  23419. // Replacing the third row of the projection matrix
  23420. projectionMatrix.elements[ 2 ] = clipPlane.x;
  23421. projectionMatrix.elements[ 6 ] = clipPlane.y;
  23422. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  23423. projectionMatrix.elements[ 14 ] = clipPlane.w;
  23424. //
  23425. this.textureNode.value = renderTarget.texture;
  23426. if ( this.depth === true ) {
  23427. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  23428. }
  23429. material.visible = false;
  23430. const currentRenderTarget = renderer.getRenderTarget();
  23431. const currentMRT = renderer.getMRT();
  23432. const currentAutoClear = renderer.autoClear;
  23433. renderer.setMRT( null );
  23434. renderer.setRenderTarget( renderTarget );
  23435. renderer.autoClear = true;
  23436. if ( needsClear ) {
  23437. renderer.clear();
  23438. this.hasOutput = false;
  23439. } else {
  23440. renderer.render( scene, virtualCamera );
  23441. this.hasOutput = true;
  23442. }
  23443. renderer.setMRT( currentMRT );
  23444. renderer.setRenderTarget( currentRenderTarget );
  23445. renderer.autoClear = currentAutoClear;
  23446. material.visible = true;
  23447. _inReflector = false;
  23448. this.forceUpdate = false;
  23449. }
  23450. }
  23451. /**
  23452. * TSL function for creating a reflector node.
  23453. *
  23454. * @tsl
  23455. * @function
  23456. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23457. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23458. * @param {number} [parameters.resolution=1] - The resolution scale.
  23459. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23460. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23461. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23462. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  23463. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  23464. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  23465. * @returns {ReflectorNode}
  23466. */
  23467. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  23468. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  23469. /**
  23470. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  23471. *
  23472. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  23473. *
  23474. * @private
  23475. * @augments BufferGeometry
  23476. */
  23477. class QuadGeometry extends BufferGeometry {
  23478. /**
  23479. * Constructs a new quad geometry.
  23480. *
  23481. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  23482. */
  23483. constructor( flipY = false ) {
  23484. super();
  23485. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  23486. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  23487. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  23488. }
  23489. }
  23490. const _geometry = /*@__PURE__*/ new QuadGeometry();
  23491. /**
  23492. * This module is a helper for passes which need to render a full
  23493. * screen effect which is quite common in context of post processing.
  23494. *
  23495. * The intended usage is to reuse a single quad mesh for rendering
  23496. * subsequent passes by just reassigning the `material` reference.
  23497. *
  23498. * Note: This module can only be used with `WebGPURenderer`.
  23499. *
  23500. * @augments Mesh
  23501. */
  23502. class QuadMesh extends Mesh {
  23503. /**
  23504. * Constructs a new quad mesh.
  23505. *
  23506. * @param {?Material} [material=null] - The material to render the quad mesh with.
  23507. */
  23508. constructor( material = null ) {
  23509. super( _geometry, material );
  23510. /**
  23511. * The camera to render the quad mesh with.
  23512. *
  23513. * @type {OrthographicCamera}
  23514. * @readonly
  23515. */
  23516. this.camera = _camera;
  23517. /**
  23518. * This flag can be used for type testing.
  23519. *
  23520. * @type {boolean}
  23521. * @readonly
  23522. * @default true
  23523. */
  23524. this.isQuadMesh = true;
  23525. }
  23526. /**
  23527. * Async version of `render()`.
  23528. *
  23529. * @async
  23530. * @param {Renderer} renderer - The renderer.
  23531. * @return {Promise} A Promise that resolves when the render has been finished.
  23532. */
  23533. async renderAsync( renderer ) {
  23534. return renderer.renderAsync( this, _camera );
  23535. }
  23536. /**
  23537. * Renders the quad mesh
  23538. *
  23539. * @param {Renderer} renderer - The renderer.
  23540. */
  23541. render( renderer ) {
  23542. renderer.render( this, _camera );
  23543. }
  23544. }
  23545. const _size$1 = /*@__PURE__*/ new Vector2();
  23546. /**
  23547. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  23548. * This module is especially relevant in context of post processing where certain nodes require
  23549. * texture input for their effects. With the helper function `convertToTexture()` which is based
  23550. * on this module, the node system can automatically ensure texture input if required.
  23551. *
  23552. * @augments TextureNode
  23553. */
  23554. class RTTNode extends TextureNode {
  23555. static get type() {
  23556. return 'RTTNode';
  23557. }
  23558. /**
  23559. * Constructs a new RTT node.
  23560. *
  23561. * @param {Node} node - The node to render a texture with.
  23562. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23563. * @param {?number} [height=null] - The height of the internal render target.
  23564. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23565. */
  23566. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  23567. const renderTarget = new RenderTarget( width, height, options );
  23568. super( renderTarget.texture, uv$1() );
  23569. /**
  23570. * This flag can be used for type testing.
  23571. *
  23572. * @type {boolean}
  23573. * @readonly
  23574. * @default true
  23575. */
  23576. this.isRTTNode = true;
  23577. /**
  23578. * The node to render a texture with.
  23579. *
  23580. * @type {Node}
  23581. */
  23582. this.node = node;
  23583. /**
  23584. * The width of the internal render target.
  23585. * If not width is applied, the render target is automatically resized.
  23586. *
  23587. * @type {?number}
  23588. * @default null
  23589. */
  23590. this.width = width;
  23591. /**
  23592. * The height of the internal render target.
  23593. *
  23594. * @type {?number}
  23595. * @default null
  23596. */
  23597. this.height = height;
  23598. /**
  23599. * The pixel ratio
  23600. *
  23601. * @type {number}
  23602. * @default 1
  23603. */
  23604. this.pixelRatio = 1;
  23605. /**
  23606. * The render target
  23607. *
  23608. * @type {RenderTarget}
  23609. */
  23610. this.renderTarget = renderTarget;
  23611. /**
  23612. * Whether the texture requires an update or not.
  23613. *
  23614. * @type {boolean}
  23615. * @default true
  23616. */
  23617. this.textureNeedsUpdate = true;
  23618. /**
  23619. * Whether the texture should automatically be updated or not.
  23620. *
  23621. * @type {boolean}
  23622. * @default true
  23623. */
  23624. this.autoUpdate = true;
  23625. /**
  23626. * The node which is used with the quad mesh for RTT.
  23627. *
  23628. * @private
  23629. * @type {Node}
  23630. * @default null
  23631. */
  23632. this._rttNode = null;
  23633. /**
  23634. * The internal quad mesh for RTT.
  23635. *
  23636. * @private
  23637. * @type {QuadMesh}
  23638. */
  23639. this._quadMesh = new QuadMesh( new NodeMaterial() );
  23640. /**
  23641. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  23642. * the texture once per render in its {@link RTTNode#updateBefore} method.
  23643. *
  23644. * @type {string}
  23645. * @default 'render'
  23646. */
  23647. this.updateBeforeType = NodeUpdateType.RENDER;
  23648. }
  23649. /**
  23650. * Whether the internal render target should automatically be resized or not.
  23651. *
  23652. * @type {boolean}
  23653. * @readonly
  23654. * @default true
  23655. */
  23656. get autoResize() {
  23657. return this.width === null;
  23658. }
  23659. setup( builder ) {
  23660. this._rttNode = this.node.context( builder.getSharedContext() );
  23661. this._quadMesh.material.name = 'RTT';
  23662. this._quadMesh.material.needsUpdate = true;
  23663. return super.setup( builder );
  23664. }
  23665. /**
  23666. * Sets the size of the internal render target
  23667. *
  23668. * @param {number} width - The width to set.
  23669. * @param {number} height - The width to set.
  23670. */
  23671. setSize( width, height ) {
  23672. this.width = width;
  23673. this.height = height;
  23674. const effectiveWidth = width * this.pixelRatio;
  23675. const effectiveHeight = height * this.pixelRatio;
  23676. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23677. this.textureNeedsUpdate = true;
  23678. }
  23679. /**
  23680. * Sets the pixel ratio. This will also resize the render target.
  23681. *
  23682. * @param {number} pixelRatio - The pixel ratio to set.
  23683. */
  23684. setPixelRatio( pixelRatio ) {
  23685. this.pixelRatio = pixelRatio;
  23686. this.setSize( this.width, this.height );
  23687. }
  23688. updateBefore( { renderer } ) {
  23689. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  23690. this.textureNeedsUpdate = false;
  23691. //
  23692. if ( this.autoResize === true ) {
  23693. const pixelRatio = renderer.getPixelRatio();
  23694. const size = renderer.getSize( _size$1 );
  23695. const effectiveWidth = size.width * pixelRatio;
  23696. const effectiveHeight = size.height * pixelRatio;
  23697. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  23698. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23699. this.textureNeedsUpdate = true;
  23700. }
  23701. }
  23702. //
  23703. this._quadMesh.material.fragmentNode = this._rttNode;
  23704. //
  23705. const currentRenderTarget = renderer.getRenderTarget();
  23706. renderer.setRenderTarget( this.renderTarget );
  23707. this._quadMesh.render( renderer );
  23708. renderer.setRenderTarget( currentRenderTarget );
  23709. }
  23710. clone() {
  23711. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  23712. newNode.sampler = this.sampler;
  23713. newNode.referenceNode = this;
  23714. return newNode;
  23715. }
  23716. }
  23717. /**
  23718. * TSL function for creating a RTT node.
  23719. *
  23720. * @tsl
  23721. * @function
  23722. * @param {Node} node - The node to render a texture with.
  23723. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23724. * @param {?number} [height=null] - The height of the internal render target.
  23725. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23726. * @returns {RTTNode}
  23727. */
  23728. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  23729. /**
  23730. * TSL function for converting nodes to textures nodes.
  23731. *
  23732. * @tsl
  23733. * @function
  23734. * @param {Node} node - The node to render a texture with.
  23735. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23736. * @param {?number} [height=null] - The height of the internal render target.
  23737. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23738. * @returns {RTTNode}
  23739. */
  23740. const convertToTexture = ( node, ...params ) => {
  23741. if ( node.isTextureNode ) return node;
  23742. if ( node.isPassNode ) return node.getTextureNode();
  23743. return rtt( node, ...params );
  23744. };
  23745. /**
  23746. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  23747. * depth value and the camera's inverse projection matrix.
  23748. *
  23749. * @tsl
  23750. * @function
  23751. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  23752. * @param {Node<float>} depth - The fragment's depth value.
  23753. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  23754. * @return {Node<vec3>} The fragments position in view space.
  23755. */
  23756. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  23757. let clipSpacePosition;
  23758. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  23759. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  23760. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  23761. } else {
  23762. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  23763. }
  23764. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  23765. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  23766. } );
  23767. /**
  23768. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  23769. * and the camera's projection matrix
  23770. *
  23771. * @tsl
  23772. * @function
  23773. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  23774. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  23775. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  23776. */
  23777. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  23778. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  23779. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  23780. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  23781. } );
  23782. /**
  23783. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  23784. * target is available or if flat surface normals are required.
  23785. *
  23786. * @tsl
  23787. * @function
  23788. * @param {Node<vec2>} uv - The texture coordinate.
  23789. * @param {DepthTexture} depthTexture - The depth texture.
  23790. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  23791. * @return {Node<vec3>} The computed normal vector.
  23792. */
  23793. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  23794. const size = textureSize( textureLoad( depthTexture ) );
  23795. const p = ivec2( uv.mul( size ) ).toVar();
  23796. const c0 = textureLoad( depthTexture, p ).toVar();
  23797. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  23798. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  23799. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  23800. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  23801. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  23802. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  23803. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  23804. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  23805. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  23806. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  23807. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  23808. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  23809. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  23810. 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 ) ) );
  23811. 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 ) ) );
  23812. return normalize( cross( dpdx, dpdy ) );
  23813. } );
  23814. /**
  23815. * Class representing a node that samples a value using a provided callback function.
  23816. *
  23817. * @extends Node
  23818. */
  23819. class SampleNode extends Node {
  23820. /**
  23821. * Returns the type of the node.
  23822. *
  23823. * @type {string}
  23824. * @readonly
  23825. * @static
  23826. */
  23827. static get type() {
  23828. return 'SampleNode';
  23829. }
  23830. /**
  23831. * Creates an instance of SampleNode.
  23832. *
  23833. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  23834. */
  23835. constructor( callback ) {
  23836. super();
  23837. this.callback = callback;
  23838. /**
  23839. * This flag can be used for type testing.
  23840. *
  23841. * @type {boolean}
  23842. * @readonly
  23843. * @default true
  23844. */
  23845. this.isSampleNode = true;
  23846. }
  23847. /**
  23848. * Sets up the node by sampling with the default UV accessor.
  23849. *
  23850. * @returns {Node} The result of the callback function when called with the UV node.
  23851. */
  23852. setup() {
  23853. return this.sample( uv$1() );
  23854. }
  23855. /**
  23856. * Calls the callback function with the provided UV node.
  23857. *
  23858. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  23859. * @returns {Node} The result of the callback function.
  23860. */
  23861. sample( uv ) {
  23862. return this.callback( uv );
  23863. }
  23864. }
  23865. /**
  23866. * Helper function to create a SampleNode wrapped as a node object.
  23867. *
  23868. * @function
  23869. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  23870. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  23871. */
  23872. const sample = ( callback ) => nodeObject( new SampleNode( callback ) );
  23873. /**
  23874. * EventNode is a node that executes a callback during specific update phases.
  23875. *
  23876. * @augments Node
  23877. */
  23878. class EventNode extends Node {
  23879. static get type() {
  23880. return 'EventNode';
  23881. }
  23882. /**
  23883. * Creates an EventNode.
  23884. *
  23885. * @param {string} eventType - The type of event
  23886. * @param {Function} callback - The callback to execute on update.
  23887. */
  23888. constructor( eventType, callback ) {
  23889. super( 'void' );
  23890. this.eventType = eventType;
  23891. this.callback = callback;
  23892. if ( eventType === EventNode.OBJECT ) {
  23893. this.updateType = NodeUpdateType.OBJECT;
  23894. } else if ( eventType === EventNode.MATERIAL ) {
  23895. this.updateType = NodeUpdateType.RENDER;
  23896. }
  23897. }
  23898. update( frame ) {
  23899. this.callback( frame );
  23900. }
  23901. }
  23902. EventNode.OBJECT = 'object';
  23903. EventNode.MATERIAL = 'material';
  23904. /**
  23905. * Helper to create an EventNode and add it to the stack.
  23906. *
  23907. * @param {string} type - The event type.
  23908. * @param {Function} callback - The callback function.
  23909. * @returns {EventNode}
  23910. */
  23911. const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack();
  23912. /**
  23913. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  23914. *
  23915. * 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.
  23916. *
  23917. * @param {Function} callback - The callback function.
  23918. * @returns {EventNode}
  23919. */
  23920. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  23921. /**
  23922. * Creates an event that triggers a function when the first object that uses the material is rendered.
  23923. *
  23924. * 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.
  23925. *
  23926. * @param {Function} callback - The callback function.
  23927. * @returns {EventNode}
  23928. */
  23929. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  23930. /**
  23931. * This special type of instanced buffer attribute is intended for compute shaders.
  23932. * In earlier three.js versions it was only possible to update attribute data
  23933. * on the CPU via JavaScript and then upload the data to the GPU. With the
  23934. * new material system and renderer it is now possible to use compute shaders
  23935. * to compute the data for an attribute more efficiently on the GPU.
  23936. *
  23937. * The idea is to create an instance of this class and provide it as an input
  23938. * to {@link StorageBufferNode}.
  23939. *
  23940. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  23941. *
  23942. * @augments InstancedBufferAttribute
  23943. */
  23944. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  23945. /**
  23946. * Constructs a new storage instanced buffer attribute.
  23947. *
  23948. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  23949. * The subsequent parameters are then obsolete.
  23950. * @param {number} itemSize - The item size.
  23951. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  23952. */
  23953. constructor( count, itemSize, typeClass = Float32Array ) {
  23954. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  23955. super( array, itemSize );
  23956. /**
  23957. * This flag can be used for type testing.
  23958. *
  23959. * @type {boolean}
  23960. * @readonly
  23961. * @default true
  23962. */
  23963. this.isStorageInstancedBufferAttribute = true;
  23964. }
  23965. }
  23966. /**
  23967. * This special type of buffer attribute is intended for compute shaders.
  23968. * In earlier three.js versions it was only possible to update attribute data
  23969. * on the CPU via JavaScript and then upload the data to the GPU. With the
  23970. * new material system and renderer it is now possible to use compute shaders
  23971. * to compute the data for an attribute more efficiently on the GPU.
  23972. *
  23973. * The idea is to create an instance of this class and provide it as an input
  23974. * to {@link StorageBufferNode}.
  23975. *
  23976. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  23977. *
  23978. * @augments BufferAttribute
  23979. */
  23980. class StorageBufferAttribute extends BufferAttribute {
  23981. /**
  23982. * Constructs a new storage buffer attribute.
  23983. *
  23984. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  23985. * The subsequent parameters are then obsolete.
  23986. * @param {number} itemSize - The item size.
  23987. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  23988. */
  23989. constructor( count, itemSize, typeClass = Float32Array ) {
  23990. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  23991. super( array, itemSize );
  23992. /**
  23993. * This flag can be used for type testing.
  23994. *
  23995. * @type {boolean}
  23996. * @readonly
  23997. * @default true
  23998. */
  23999. this.isStorageBufferAttribute = true;
  24000. }
  24001. }
  24002. /**
  24003. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  24004. *
  24005. * @tsl
  24006. * @function
  24007. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24008. * @param {string|Struct} [type='float'] - The data type.
  24009. * @returns {StorageBufferNode}
  24010. */
  24011. const attributeArray = ( count, type = 'float' ) => {
  24012. let itemSize, typedArray;
  24013. if ( type.isStruct === true ) {
  24014. itemSize = type.layout.getLength();
  24015. typedArray = getTypedArrayFromType( 'float' );
  24016. } else {
  24017. itemSize = getLengthFromType( type );
  24018. typedArray = getTypedArrayFromType( type );
  24019. }
  24020. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  24021. const node = storage( buffer, type, count );
  24022. return node;
  24023. };
  24024. /**
  24025. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  24026. *
  24027. * @tsl
  24028. * @function
  24029. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24030. * @param {string|Struct} [type='float'] - The data type.
  24031. * @returns {StorageBufferNode}
  24032. */
  24033. const instancedArray = ( count, type = 'float' ) => {
  24034. let itemSize, typedArray;
  24035. if ( type.isStruct === true ) {
  24036. itemSize = type.layout.getLength();
  24037. typedArray = getTypedArrayFromType( 'float' );
  24038. } else {
  24039. itemSize = getLengthFromType( type );
  24040. typedArray = getTypedArrayFromType( type );
  24041. }
  24042. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  24043. const node = storage( buffer, type, count );
  24044. return node;
  24045. };
  24046. /**
  24047. * A node for representing the uv coordinates of points.
  24048. *
  24049. * Can only be used with a WebGL backend. In WebGPU, point
  24050. * primitives always have the size of one pixel and can thus
  24051. * can't be used as sprite-like objects that display textures.
  24052. *
  24053. * @augments Node
  24054. */
  24055. class PointUVNode extends Node {
  24056. static get type() {
  24057. return 'PointUVNode';
  24058. }
  24059. /**
  24060. * Constructs a new point uv node.
  24061. */
  24062. constructor() {
  24063. super( 'vec2' );
  24064. /**
  24065. * This flag can be used for type testing.
  24066. *
  24067. * @type {boolean}
  24068. * @readonly
  24069. * @default true
  24070. */
  24071. this.isPointUVNode = true;
  24072. }
  24073. generate( /*builder*/ ) {
  24074. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  24075. }
  24076. }
  24077. /**
  24078. * TSL object that represents the uv coordinates of points.
  24079. *
  24080. * @tsl
  24081. * @type {PointUVNode}
  24082. */
  24083. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  24084. const _e1 = /*@__PURE__*/ new Euler();
  24085. const _m1 = /*@__PURE__*/ new Matrix4();
  24086. /**
  24087. * This module allows access to a collection of scene properties. The following predefined TSL objects
  24088. * are available for easier use:
  24089. *
  24090. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  24091. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  24092. * - `backgroundRotation`: A node that represents the scene's background rotation.
  24093. *
  24094. * @augments Node
  24095. */
  24096. class SceneNode extends Node {
  24097. static get type() {
  24098. return 'SceneNode';
  24099. }
  24100. /**
  24101. * Constructs a new scene node.
  24102. *
  24103. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  24104. * @param {?Scene} [scene=null] - A reference to the scene.
  24105. */
  24106. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  24107. super();
  24108. /**
  24109. * The scope defines the type of scene property that is accessed.
  24110. *
  24111. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  24112. */
  24113. this.scope = scope;
  24114. /**
  24115. * A reference to the scene that is going to be accessed.
  24116. *
  24117. * @type {?Scene}
  24118. * @default null
  24119. */
  24120. this.scene = scene;
  24121. }
  24122. /**
  24123. * Depending on the scope, the method returns a different type of node that represents
  24124. * the respective scene property.
  24125. *
  24126. * @param {NodeBuilder} builder - The current node builder.
  24127. * @return {Node} The output node.
  24128. */
  24129. setup( builder ) {
  24130. const scope = this.scope;
  24131. const scene = this.scene !== null ? this.scene : builder.scene;
  24132. let output;
  24133. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  24134. output = reference( 'backgroundBlurriness', 'float', scene );
  24135. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  24136. output = reference( 'backgroundIntensity', 'float', scene );
  24137. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  24138. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24139. const background = scene.background;
  24140. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  24141. _e1.copy( scene.backgroundRotation );
  24142. // accommodate left-handed frame
  24143. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  24144. _m1.makeRotationFromEuler( _e1 );
  24145. } else {
  24146. _m1.identity();
  24147. }
  24148. return _m1;
  24149. } );
  24150. } else {
  24151. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  24152. }
  24153. return output;
  24154. }
  24155. }
  24156. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  24157. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  24158. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  24159. /**
  24160. * TSL object that represents the scene's background blurriness.
  24161. *
  24162. * @tsl
  24163. * @type {SceneNode}
  24164. */
  24165. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  24166. /**
  24167. * TSL object that represents the scene's background intensity.
  24168. *
  24169. * @tsl
  24170. * @type {SceneNode}
  24171. */
  24172. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  24173. /**
  24174. * TSL object that represents the scene's background rotation.
  24175. *
  24176. * @tsl
  24177. * @type {SceneNode}
  24178. */
  24179. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  24180. /**
  24181. * This special version of a texture node can be used to
  24182. * write data into a storage texture with a compute shader.
  24183. *
  24184. * ```js
  24185. * const storageTexture = new THREE.StorageTexture( width, height );
  24186. *
  24187. * const computeTexture = Fn( ( { storageTexture } ) => {
  24188. *
  24189. * const posX = instanceIndex.mod( width );
  24190. * const posY = instanceIndex.div( width );
  24191. * const indexUV = uvec2( posX, posY );
  24192. *
  24193. * // generate RGB values
  24194. *
  24195. * const r = 1;
  24196. * const g = 1;
  24197. * const b = 1;
  24198. *
  24199. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  24200. *
  24201. * } );
  24202. *
  24203. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  24204. * renderer.computeAsync( computeNode );
  24205. * ```
  24206. *
  24207. * This node can only be used with a WebGPU backend.
  24208. *
  24209. * @augments TextureNode
  24210. */
  24211. class StorageTextureNode extends TextureNode {
  24212. static get type() {
  24213. return 'StorageTextureNode';
  24214. }
  24215. /**
  24216. * Constructs a new storage texture node.
  24217. *
  24218. * @param {StorageTexture} value - The storage texture.
  24219. * @param {Node<vec2|vec3>} uvNode - The uv node.
  24220. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24221. */
  24222. constructor( value, uvNode, storeNode = null ) {
  24223. super( value, uvNode );
  24224. /**
  24225. * The value node that should be stored in the texture.
  24226. *
  24227. * @type {?Node}
  24228. * @default null
  24229. */
  24230. this.storeNode = storeNode;
  24231. /**
  24232. * This flag can be used for type testing.
  24233. *
  24234. * @type {boolean}
  24235. * @readonly
  24236. * @default true
  24237. */
  24238. this.isStorageTextureNode = true;
  24239. /**
  24240. * The access type of the texture node.
  24241. *
  24242. * @type {string}
  24243. * @default 'writeOnly'
  24244. */
  24245. this.access = NodeAccess.WRITE_ONLY;
  24246. }
  24247. /**
  24248. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  24249. *
  24250. * @param {NodeBuilder} builder - The current node builder.
  24251. * @return {string} The input type.
  24252. */
  24253. getInputType( /*builder*/ ) {
  24254. return 'storageTexture';
  24255. }
  24256. setup( builder ) {
  24257. super.setup( builder );
  24258. const properties = builder.getNodeProperties( this );
  24259. properties.storeNode = this.storeNode;
  24260. return properties;
  24261. }
  24262. /**
  24263. * Defines the node access.
  24264. *
  24265. * @param {string} value - The node access.
  24266. * @return {StorageTextureNode} A reference to this node.
  24267. */
  24268. setAccess( value ) {
  24269. this.access = value;
  24270. return this;
  24271. }
  24272. /**
  24273. * Generates the code snippet of the storage node. If no `storeNode`
  24274. * is defined, the texture node is generated as normal texture.
  24275. *
  24276. * @param {NodeBuilder} builder - The current node builder.
  24277. * @param {string} output - The current output.
  24278. * @return {string} The generated code snippet.
  24279. */
  24280. generate( builder, output ) {
  24281. let snippet;
  24282. if ( this.storeNode !== null ) {
  24283. snippet = this.generateStore( builder );
  24284. } else {
  24285. snippet = super.generate( builder, output );
  24286. }
  24287. return snippet;
  24288. }
  24289. /**
  24290. * Convenience method for configuring a read/write node access.
  24291. *
  24292. * @return {StorageTextureNode} A reference to this node.
  24293. */
  24294. toReadWrite() {
  24295. return this.setAccess( NodeAccess.READ_WRITE );
  24296. }
  24297. /**
  24298. * Convenience method for configuring a read-only node access.
  24299. *
  24300. * @return {StorageTextureNode} A reference to this node.
  24301. */
  24302. toReadOnly() {
  24303. return this.setAccess( NodeAccess.READ_ONLY );
  24304. }
  24305. /**
  24306. * Convenience method for configuring a write-only node access.
  24307. *
  24308. * @return {StorageTextureNode} A reference to this node.
  24309. */
  24310. toWriteOnly() {
  24311. return this.setAccess( NodeAccess.WRITE_ONLY );
  24312. }
  24313. /**
  24314. * Generates the code snippet of the storage texture node.
  24315. *
  24316. * @param {NodeBuilder} builder - The current node builder.
  24317. */
  24318. generateStore( builder ) {
  24319. const properties = builder.getNodeProperties( this );
  24320. const { uvNode, storeNode, depthNode } = properties;
  24321. const textureProperty = super.generate( builder, 'property' );
  24322. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  24323. const storeSnippet = storeNode.build( builder, 'vec4' );
  24324. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24325. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  24326. builder.addLineFlowCode( snippet, this );
  24327. }
  24328. clone() {
  24329. const newNode = super.clone();
  24330. newNode.storeNode = this.storeNode;
  24331. return newNode;
  24332. }
  24333. }
  24334. /**
  24335. * TSL function for creating a storage texture node.
  24336. *
  24337. * @tsl
  24338. * @function
  24339. * @param {StorageTexture} value - The storage texture.
  24340. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  24341. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24342. * @returns {StorageTextureNode}
  24343. */
  24344. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  24345. /**
  24346. * TODO: Explain difference to `storageTexture()`.
  24347. *
  24348. * @tsl
  24349. * @function
  24350. * @param {StorageTexture} value - The storage texture.
  24351. * @param {Node<vec2|vec3>} uvNode - The uv node.
  24352. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24353. * @returns {StorageTextureNode}
  24354. */
  24355. const textureStore = ( value, uvNode, storeNode ) => {
  24356. const node = storageTexture( value, uvNode, storeNode );
  24357. if ( storeNode !== null ) node.toStack();
  24358. return node;
  24359. };
  24360. const normal = Fn( ( { texture, uv } ) => {
  24361. const epsilon = 0.0001;
  24362. const ret = vec3().toVar();
  24363. If( uv.x.lessThan( epsilon ), () => {
  24364. ret.assign( vec3( 1, 0, 0 ) );
  24365. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  24366. ret.assign( vec3( 0, 1, 0 ) );
  24367. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  24368. ret.assign( vec3( 0, 0, 1 ) );
  24369. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  24370. ret.assign( vec3( -1, 0, 0 ) );
  24371. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  24372. ret.assign( vec3( 0, -1, 0 ) );
  24373. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  24374. ret.assign( vec3( 0, 0, -1 ) );
  24375. } ).Else( () => {
  24376. const step = 0.01;
  24377. 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 );
  24378. 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 );
  24379. 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 );
  24380. ret.assign( vec3( x, y, z ) );
  24381. } );
  24382. return ret.normalize();
  24383. } );
  24384. /**
  24385. * This type of uniform node represents a 3D texture.
  24386. *
  24387. * @augments TextureNode
  24388. */
  24389. class Texture3DNode extends TextureNode {
  24390. static get type() {
  24391. return 'Texture3DNode';
  24392. }
  24393. /**
  24394. * Constructs a new 3D texture node.
  24395. *
  24396. * @param {Data3DTexture} value - The 3D texture.
  24397. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  24398. * @param {?Node<int>} [levelNode=null] - The level node.
  24399. */
  24400. constructor( value, uvNode = null, levelNode = null ) {
  24401. super( value, uvNode, levelNode );
  24402. /**
  24403. * This flag can be used for type testing.
  24404. *
  24405. * @type {boolean}
  24406. * @readonly
  24407. * @default true
  24408. */
  24409. this.isTexture3DNode = true;
  24410. }
  24411. /**
  24412. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  24413. *
  24414. * @param {NodeBuilder} builder - The current node builder.
  24415. * @return {string} The input type.
  24416. */
  24417. getInputType( /*builder*/ ) {
  24418. return 'texture3D';
  24419. }
  24420. /**
  24421. * Returns a default uv node which is in context of 3D textures a three-dimensional
  24422. * uv node.
  24423. *
  24424. * @return {Node<vec3>} The default uv node.
  24425. */
  24426. getDefaultUV() {
  24427. return vec3( 0.5, 0.5, 0.5 );
  24428. }
  24429. /**
  24430. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  24431. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  24432. *
  24433. * @param {boolean} value - The update toggle.
  24434. */
  24435. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  24436. /**
  24437. * Overwrites the default implementation to return the unmodified uv node.
  24438. *
  24439. * @param {NodeBuilder} builder - The current node builder.
  24440. * @param {Node} uvNode - The uv node to setup.
  24441. * @return {Node} The unmodified uv node.
  24442. */
  24443. setupUV( builder, uvNode ) {
  24444. const texture = this.value;
  24445. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  24446. if ( this.sampler ) {
  24447. uvNode = uvNode.flipY();
  24448. } else {
  24449. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  24450. }
  24451. }
  24452. return uvNode;
  24453. }
  24454. /**
  24455. * Generates the uv code snippet.
  24456. *
  24457. * @param {NodeBuilder} builder - The current node builder.
  24458. * @param {Node} uvNode - The uv node to generate code for.
  24459. * @return {string} The generated code snippet.
  24460. */
  24461. generateUV( builder, uvNode ) {
  24462. return uvNode.build( builder, 'vec3' );
  24463. }
  24464. /**
  24465. * TODO.
  24466. *
  24467. * @param {Node<vec3>} uvNode - The uv node .
  24468. * @return {Node<vec3>} TODO.
  24469. */
  24470. normal( uvNode ) {
  24471. return normal( { texture: this, uv: uvNode } );
  24472. }
  24473. }
  24474. /**
  24475. * TSL function for creating a 3D texture node.
  24476. *
  24477. * @tsl
  24478. * @function
  24479. * @param {Data3DTexture} value - The 3D texture.
  24480. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  24481. * @param {?Node<int>} [levelNode=null] - The level node.
  24482. * @returns {Texture3DNode}
  24483. */
  24484. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  24485. /**
  24486. * A special type of reference node that allows to link values in
  24487. * `userData` fields to node objects.
  24488. * ```js
  24489. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  24490. *
  24491. * const material = new THREE.SpriteNodeMaterial();
  24492. * material.rotationNode = userData( 'rotation', 'float' );
  24493. * ```
  24494. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  24495. * will automatically be updated when the `rotation` user data field changes.
  24496. *
  24497. * @augments ReferenceNode
  24498. */
  24499. class UserDataNode extends ReferenceNode {
  24500. static get type() {
  24501. return 'UserDataNode';
  24502. }
  24503. /**
  24504. * Constructs a new user data node.
  24505. *
  24506. * @param {string} property - The property name that should be referenced by the node.
  24507. * @param {string} inputType - The node data type of the reference.
  24508. * @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.
  24509. */
  24510. constructor( property, inputType, userData = null ) {
  24511. super( property, inputType, userData );
  24512. /**
  24513. * A reference to the `userData` object. If not provided, the `userData`
  24514. * property of the 3D object that uses the node material is evaluated.
  24515. *
  24516. * @type {?Object}
  24517. * @default null
  24518. */
  24519. this.userData = userData;
  24520. }
  24521. /**
  24522. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  24523. * `userData` field.
  24524. *
  24525. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  24526. * @return {Object} A reference to the `userData` field.
  24527. */
  24528. updateReference( state ) {
  24529. this.reference = this.userData !== null ? this.userData : state.object.userData;
  24530. return this.reference;
  24531. }
  24532. }
  24533. /**
  24534. * TSL function for creating a user data node.
  24535. *
  24536. * @tsl
  24537. * @function
  24538. * @param {string} name - The property name that should be referenced by the node.
  24539. * @param {string} inputType - The node data type of the reference.
  24540. * @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.
  24541. * @returns {UserDataNode}
  24542. */
  24543. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  24544. const _objectData = new WeakMap();
  24545. /**
  24546. * A node for representing motion or velocity vectors. Foundation
  24547. * for advanced post processing effects like motion blur or TRAA.
  24548. *
  24549. * The node keeps track of the model, view and projection matrices
  24550. * of the previous frame and uses them to compute offsets in NDC space.
  24551. * These offsets represent the final velocity.
  24552. *
  24553. * @augments TempNode
  24554. */
  24555. class VelocityNode extends TempNode {
  24556. static get type() {
  24557. return 'VelocityNode';
  24558. }
  24559. /**
  24560. * Constructs a new vertex color node.
  24561. */
  24562. constructor() {
  24563. super( 'vec2' );
  24564. /**
  24565. * The current projection matrix.
  24566. *
  24567. * @type {?Matrix4}
  24568. * @default null
  24569. */
  24570. this.projectionMatrix = null;
  24571. /**
  24572. * Overwritten since velocity nodes are updated per object.
  24573. *
  24574. * @type {string}
  24575. * @default 'object'
  24576. */
  24577. this.updateType = NodeUpdateType.OBJECT;
  24578. /**
  24579. * Overwritten since velocity nodes save data after the update.
  24580. *
  24581. * @type {string}
  24582. * @default 'object'
  24583. */
  24584. this.updateAfterType = NodeUpdateType.OBJECT;
  24585. /**
  24586. * Uniform node representing the previous model matrix in world space.
  24587. *
  24588. * @type {UniformNode<mat4>}
  24589. * @default null
  24590. */
  24591. this.previousModelWorldMatrix = uniform( new Matrix4() );
  24592. /**
  24593. * Uniform node representing the previous projection matrix.
  24594. *
  24595. * @type {UniformNode<mat4>}
  24596. * @default null
  24597. */
  24598. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  24599. /**
  24600. * Uniform node representing the previous view matrix.
  24601. *
  24602. * @type {UniformNode<mat4>}
  24603. * @default null
  24604. */
  24605. this.previousCameraViewMatrix = uniform( new Matrix4() );
  24606. }
  24607. /**
  24608. * Sets the given projection matrix.
  24609. *
  24610. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  24611. */
  24612. setProjectionMatrix( projectionMatrix ) {
  24613. this.projectionMatrix = projectionMatrix;
  24614. }
  24615. /**
  24616. * Updates velocity specific uniforms.
  24617. *
  24618. * @param {NodeFrame} frame - A reference to the current node frame.
  24619. */
  24620. update( { frameId, camera, object } ) {
  24621. const previousModelMatrix = getPreviousMatrix( object );
  24622. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  24623. //
  24624. const cameraData = getData( camera );
  24625. if ( cameraData.frameId !== frameId ) {
  24626. cameraData.frameId = frameId;
  24627. if ( cameraData.previousProjectionMatrix === undefined ) {
  24628. cameraData.previousProjectionMatrix = new Matrix4();
  24629. cameraData.previousCameraViewMatrix = new Matrix4();
  24630. cameraData.currentProjectionMatrix = new Matrix4();
  24631. cameraData.currentCameraViewMatrix = new Matrix4();
  24632. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  24633. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  24634. } else {
  24635. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  24636. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  24637. }
  24638. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  24639. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  24640. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  24641. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  24642. }
  24643. }
  24644. /**
  24645. * Overwritten to updated velocity specific uniforms.
  24646. *
  24647. * @param {NodeFrame} frame - A reference to the current node frame.
  24648. */
  24649. updateAfter( { object } ) {
  24650. getPreviousMatrix( object ).copy( object.matrixWorld );
  24651. }
  24652. /**
  24653. * Implements the velocity computation based on the previous and current vertex data.
  24654. *
  24655. * @param {NodeBuilder} builder - A reference to the current node builder.
  24656. * @return {Node<vec2>} The motion vector.
  24657. */
  24658. setup( /*builder*/ ) {
  24659. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  24660. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  24661. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  24662. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  24663. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  24664. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  24665. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  24666. return velocity;
  24667. }
  24668. }
  24669. function getData( object ) {
  24670. let objectData = _objectData.get( object );
  24671. if ( objectData === undefined ) {
  24672. objectData = {};
  24673. _objectData.set( object, objectData );
  24674. }
  24675. return objectData;
  24676. }
  24677. function getPreviousMatrix( object, index = 0 ) {
  24678. const objectData = getData( object );
  24679. let matrix = objectData[ index ];
  24680. if ( matrix === undefined ) {
  24681. objectData[ index ] = matrix = new Matrix4();
  24682. objectData[ index ].copy( object.matrixWorld );
  24683. }
  24684. return matrix;
  24685. }
  24686. /**
  24687. * TSL object that represents the velocity of a render pass.
  24688. *
  24689. * @tsl
  24690. * @type {VelocityNode}
  24691. */
  24692. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  24693. /**
  24694. * Computes a grayscale value for the given RGB color value.
  24695. *
  24696. * @tsl
  24697. * @function
  24698. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  24699. * @return {Node<vec3>} The grayscale color.
  24700. */
  24701. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24702. return luminance( color.rgb );
  24703. } );
  24704. /**
  24705. * Super-saturates or desaturates the given RGB color.
  24706. *
  24707. * @tsl
  24708. * @function
  24709. * @param {Node<vec3>} color - The input color.
  24710. * @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.
  24711. * @return {Node<vec3>} The saturated color.
  24712. */
  24713. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24714. return adjustment.mix( luminance( color.rgb ), color.rgb );
  24715. } );
  24716. /**
  24717. * Selectively enhance the intensity of less saturated RGB colors. Can result
  24718. * in a more natural and visually appealing image with enhanced color depth
  24719. * compared to {@link ColorAdjustment#saturation}.
  24720. *
  24721. * @tsl
  24722. * @function
  24723. * @param {Node<vec3>} color - The input color.
  24724. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  24725. * @return {Node<vec3>} The updated color.
  24726. */
  24727. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24728. const average = add( color.r, color.g, color.b ).div( 3.0 );
  24729. const mx = color.r.max( color.g.max( color.b ) );
  24730. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  24731. return mix( color.rgb, mx, amt );
  24732. } );
  24733. /**
  24734. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  24735. *
  24736. * @tsl
  24737. * @function
  24738. * @param {Node<vec3>} color - The input color.
  24739. * @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.
  24740. * @return {Node<vec3>} The updated color.
  24741. */
  24742. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24743. const k = vec3( 0.57735, 0.57735, 0.57735 );
  24744. const cosAngle = adjustment.cos();
  24745. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  24746. } );
  24747. /**
  24748. * Computes the luminance for the given RGB color value.
  24749. *
  24750. * @tsl
  24751. * @function
  24752. * @param {Node<vec3>} color - The color value to compute the luminance for.
  24753. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  24754. * @return {Node<vec3>} The luminance.
  24755. */
  24756. const luminance = (
  24757. color,
  24758. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  24759. ) => dot( color, luminanceCoefficients );
  24760. /**
  24761. * Color Decision List (CDL) v1.2
  24762. *
  24763. * Compact representation of color grading information, defined by slope, offset, power, and
  24764. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  24765. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  24766. *
  24767. * @tsl
  24768. * @function
  24769. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  24770. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  24771. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  24772. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  24773. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  24774. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  24775. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  24776. *
  24777. * References:
  24778. * - ASC CDL v1.2
  24779. * - {@link https://blender.stackexchange.com/a/55239/43930}
  24780. * - {@link https://docs.acescentral.com/specifications/acescc/}
  24781. */
  24782. const cdl = /*@__PURE__*/ Fn( ( [
  24783. color,
  24784. slope = vec3( 1 ),
  24785. offset = vec3( 0 ),
  24786. power = vec3( 1 ),
  24787. saturation = float( 1 ),
  24788. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  24789. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  24790. ] ) => {
  24791. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  24792. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  24793. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  24794. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  24795. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  24796. const pv = v.pow( power ).toVar();
  24797. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  24798. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  24799. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  24800. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  24801. return vec4( v.rgb, color.a );
  24802. } );
  24803. /**
  24804. * Represents a posterize effect which reduces the number of colors
  24805. * in an image, resulting in a more blocky and stylized appearance.
  24806. *
  24807. * @augments TempNode
  24808. */
  24809. class PosterizeNode extends TempNode {
  24810. static get type() {
  24811. return 'PosterizeNode';
  24812. }
  24813. /**
  24814. * Constructs a new posterize node.
  24815. *
  24816. * @param {Node} sourceNode - The input color.
  24817. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24818. */
  24819. constructor( sourceNode, stepsNode ) {
  24820. super();
  24821. /**
  24822. * The input color.
  24823. *
  24824. * @type {Node}
  24825. */
  24826. this.sourceNode = sourceNode;
  24827. /**
  24828. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24829. *
  24830. * @type {Node}
  24831. */
  24832. this.stepsNode = stepsNode;
  24833. }
  24834. setup() {
  24835. const { sourceNode, stepsNode } = this;
  24836. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  24837. }
  24838. }
  24839. /**
  24840. * TSL function for creating a posterize node.
  24841. *
  24842. * @tsl
  24843. * @function
  24844. * @param {Node} sourceNode - The input color.
  24845. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24846. * @returns {PosterizeNode}
  24847. */
  24848. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  24849. const _size = /*@__PURE__*/ new Vector2();
  24850. /**
  24851. * Represents the texture of a pass node.
  24852. *
  24853. * @augments TextureNode
  24854. */
  24855. class PassTextureNode extends TextureNode {
  24856. static get type() {
  24857. return 'PassTextureNode';
  24858. }
  24859. /**
  24860. * Constructs a new pass texture node.
  24861. *
  24862. * @param {PassNode} passNode - The pass node.
  24863. * @param {Texture} texture - The output texture.
  24864. */
  24865. constructor( passNode, texture ) {
  24866. super( texture );
  24867. /**
  24868. * A reference to the pass node.
  24869. *
  24870. * @type {PassNode}
  24871. */
  24872. this.passNode = passNode;
  24873. this.setUpdateMatrix( false );
  24874. }
  24875. setup( builder ) {
  24876. this.passNode.build( builder );
  24877. return super.setup( builder );
  24878. }
  24879. clone() {
  24880. return new this.constructor( this.passNode, this.value );
  24881. }
  24882. }
  24883. /**
  24884. * An extension of `PassTextureNode` which allows to manage more than one
  24885. * internal texture. Relevant for the `getPreviousTexture()` related API.
  24886. *
  24887. * @augments PassTextureNode
  24888. */
  24889. class PassMultipleTextureNode extends PassTextureNode {
  24890. static get type() {
  24891. return 'PassMultipleTextureNode';
  24892. }
  24893. /**
  24894. * Constructs a new pass texture node.
  24895. *
  24896. * @param {PassNode} passNode - The pass node.
  24897. * @param {string} textureName - The output texture name.
  24898. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  24899. */
  24900. constructor( passNode, textureName, previousTexture = false ) {
  24901. // null is passed to the super call since this class does not
  24902. // use an external texture for rendering pass data into. Instead
  24903. // the texture is managed by the pass node itself
  24904. super( passNode, null );
  24905. /**
  24906. * The output texture name.
  24907. *
  24908. * @type {string}
  24909. */
  24910. this.textureName = textureName;
  24911. /**
  24912. * Whether previous frame data should be used or not.
  24913. *
  24914. * @type {boolean}
  24915. */
  24916. this.previousTexture = previousTexture;
  24917. }
  24918. /**
  24919. * Updates the texture reference of this node.
  24920. */
  24921. updateTexture() {
  24922. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  24923. }
  24924. setup( builder ) {
  24925. this.updateTexture();
  24926. return super.setup( builder );
  24927. }
  24928. clone() {
  24929. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  24930. newNode.uvNode = this.uvNode;
  24931. newNode.levelNode = this.levelNode;
  24932. newNode.biasNode = this.biasNode;
  24933. newNode.sampler = this.sampler;
  24934. newNode.depthNode = this.depthNode;
  24935. newNode.compareNode = this.compareNode;
  24936. newNode.gradNode = this.gradNode;
  24937. return newNode;
  24938. }
  24939. }
  24940. /**
  24941. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  24942. * This pass produces a render for the given scene and camera and can provide multiple outputs
  24943. * via MRT for further processing.
  24944. *
  24945. * ```js
  24946. * const postProcessing = new PostProcessing( renderer );
  24947. *
  24948. * const scenePass = pass( scene, camera );
  24949. *
  24950. * postProcessing.outputNode = scenePass;
  24951. * ```
  24952. *
  24953. * @augments TempNode
  24954. */
  24955. class PassNode extends TempNode {
  24956. static get type() {
  24957. return 'PassNode';
  24958. }
  24959. /**
  24960. * Constructs a new pass node.
  24961. *
  24962. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  24963. * @param {Scene} scene - A reference to the scene.
  24964. * @param {Camera} camera - A reference to the camera.
  24965. * @param {Object} options - Options for the internal render target.
  24966. */
  24967. constructor( scope, scene, camera, options = {} ) {
  24968. super( 'vec4' );
  24969. /**
  24970. * The scope of the pass. The scope determines whether the node outputs color or depth.
  24971. *
  24972. * @type {('color'|'depth')}
  24973. */
  24974. this.scope = scope;
  24975. /**
  24976. * A reference to the scene.
  24977. *
  24978. * @type {Scene}
  24979. */
  24980. this.scene = scene;
  24981. /**
  24982. * A reference to the camera.
  24983. *
  24984. * @type {Camera}
  24985. */
  24986. this.camera = camera;
  24987. /**
  24988. * Options for the internal render target.
  24989. *
  24990. * @type {Object}
  24991. */
  24992. this.options = options;
  24993. /**
  24994. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  24995. *
  24996. * @private
  24997. * @type {number}
  24998. * @default 1
  24999. */
  25000. this._pixelRatio = 1;
  25001. /**
  25002. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  25003. * @private
  25004. * @type {number}
  25005. * @default 1
  25006. */
  25007. this._width = 1;
  25008. /**
  25009. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  25010. * @private
  25011. * @type {number}
  25012. * @default 1
  25013. */
  25014. this._height = 1;
  25015. const depthTexture = new DepthTexture();
  25016. depthTexture.isRenderTargetTexture = true;
  25017. //depthTexture.type = FloatType;
  25018. depthTexture.name = 'depth';
  25019. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  25020. renderTarget.texture.name = 'output';
  25021. renderTarget.depthTexture = depthTexture;
  25022. /**
  25023. * The pass's render target.
  25024. *
  25025. * @type {RenderTarget}
  25026. */
  25027. this.renderTarget = renderTarget;
  25028. /**
  25029. * A dictionary holding the internal result textures.
  25030. *
  25031. * @private
  25032. * @type {Object<string, Texture>}
  25033. */
  25034. this._textures = {
  25035. output: renderTarget.texture,
  25036. depth: depthTexture
  25037. };
  25038. /**
  25039. * A dictionary holding the internal texture nodes.
  25040. *
  25041. * @private
  25042. * @type {Object<string, TextureNode>}
  25043. */
  25044. this._textureNodes = {};
  25045. /**
  25046. * A dictionary holding the internal depth nodes.
  25047. *
  25048. * @private
  25049. * @type {Object}
  25050. */
  25051. this._linearDepthNodes = {};
  25052. /**
  25053. * A dictionary holding the internal viewZ nodes.
  25054. *
  25055. * @private
  25056. * @type {Object}
  25057. */
  25058. this._viewZNodes = {};
  25059. /**
  25060. * A dictionary holding the texture data of the previous frame.
  25061. * Used for computing velocity/motion vectors.
  25062. *
  25063. * @private
  25064. * @type {Object<string, Texture>}
  25065. */
  25066. this._previousTextures = {};
  25067. /**
  25068. * A dictionary holding the texture nodes of the previous frame.
  25069. * Used for computing velocity/motion vectors.
  25070. *
  25071. * @private
  25072. * @type {Object<string, TextureNode>}
  25073. */
  25074. this._previousTextureNodes = {};
  25075. /**
  25076. * The `near` property of the camera as a uniform.
  25077. *
  25078. * @private
  25079. * @type {UniformNode}
  25080. */
  25081. this._cameraNear = uniform( 0 );
  25082. /**
  25083. * The `far` property of the camera as a uniform.
  25084. *
  25085. * @private
  25086. * @type {UniformNode}
  25087. */
  25088. this._cameraFar = uniform( 0 );
  25089. /**
  25090. * A MRT node configuring the MRT settings.
  25091. *
  25092. * @private
  25093. * @type {?MRTNode}
  25094. * @default null
  25095. */
  25096. this._mrt = null;
  25097. /**
  25098. * Layer object for configuring the camera that is used
  25099. * to produce the pass.
  25100. *
  25101. * @private
  25102. * @type {?Layers}
  25103. * @default null
  25104. */
  25105. this._layers = null;
  25106. /**
  25107. * Scales the resolution of the internal render target.
  25108. *
  25109. * @private
  25110. * @type {number}
  25111. * @default 1
  25112. */
  25113. this._resolution = 1;
  25114. /**
  25115. * Custom viewport definition.
  25116. *
  25117. * @private
  25118. * @type {?Vector4}
  25119. * @default null
  25120. */
  25121. this._viewport = null;
  25122. /**
  25123. * Custom scissor definition.
  25124. *
  25125. * @private
  25126. * @type {?Vector4}
  25127. * @default null
  25128. */
  25129. this._scissor = null;
  25130. /**
  25131. * This flag can be used for type testing.
  25132. *
  25133. * @type {boolean}
  25134. * @readonly
  25135. * @default true
  25136. */
  25137. this.isPassNode = true;
  25138. /**
  25139. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  25140. * scene once per frame in its {@link PassNode#updateBefore} method.
  25141. *
  25142. * @type {string}
  25143. * @default 'frame'
  25144. */
  25145. this.updateBeforeType = NodeUpdateType.FRAME;
  25146. /**
  25147. * This flag is used for global cache.
  25148. *
  25149. * @type {boolean}
  25150. * @default true
  25151. */
  25152. this.global = true;
  25153. }
  25154. /**
  25155. * Sets the resolution for the pass.
  25156. * The resolution is a factor that is multiplied with the renderer's width and height.
  25157. *
  25158. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  25159. * @return {PassNode} A reference to this pass.
  25160. */
  25161. setResolution( resolution ) {
  25162. this._resolution = resolution;
  25163. return this;
  25164. }
  25165. /**
  25166. * Gets the current resolution of the pass.
  25167. *
  25168. * @return {number} The current resolution. A value of `1` means full resolution.
  25169. */
  25170. getResolution() {
  25171. return this._resolution;
  25172. }
  25173. /**
  25174. * Sets the layer configuration that should be used when rendering the pass.
  25175. *
  25176. * @param {Layers} layers - The layers object to set.
  25177. * @return {PassNode} A reference to this pass.
  25178. */
  25179. setLayers( layers ) {
  25180. this._layers = layers;
  25181. return this;
  25182. }
  25183. /**
  25184. * Gets the current layer configuration of the pass.
  25185. *
  25186. * @return {?Layers} .
  25187. */
  25188. getLayers() {
  25189. return this._layers;
  25190. }
  25191. /**
  25192. * Sets the given MRT node to setup MRT for this pass.
  25193. *
  25194. * @param {MRTNode} mrt - The MRT object.
  25195. * @return {PassNode} A reference to this pass.
  25196. */
  25197. setMRT( mrt ) {
  25198. this._mrt = mrt;
  25199. return this;
  25200. }
  25201. /**
  25202. * Returns the current MRT node.
  25203. *
  25204. * @return {MRTNode} The current MRT node.
  25205. */
  25206. getMRT() {
  25207. return this._mrt;
  25208. }
  25209. /**
  25210. * Returns the texture for the given output name.
  25211. *
  25212. * @param {string} name - The output name to get the texture for.
  25213. * @return {Texture} The texture.
  25214. */
  25215. getTexture( name ) {
  25216. let texture = this._textures[ name ];
  25217. if ( texture === undefined ) {
  25218. const refTexture = this.renderTarget.texture;
  25219. texture = refTexture.clone();
  25220. texture.name = name;
  25221. this._textures[ name ] = texture;
  25222. this.renderTarget.textures.push( texture );
  25223. }
  25224. return texture;
  25225. }
  25226. /**
  25227. * Returns the texture holding the data of the previous frame for the given output name.
  25228. *
  25229. * @param {string} name - The output name to get the texture for.
  25230. * @return {Texture} The texture holding the data of the previous frame.
  25231. */
  25232. getPreviousTexture( name ) {
  25233. let texture = this._previousTextures[ name ];
  25234. if ( texture === undefined ) {
  25235. texture = this.getTexture( name ).clone();
  25236. this._previousTextures[ name ] = texture;
  25237. }
  25238. return texture;
  25239. }
  25240. /**
  25241. * Switches current and previous textures for the given output name.
  25242. *
  25243. * @param {string} name - The output name.
  25244. */
  25245. toggleTexture( name ) {
  25246. const prevTexture = this._previousTextures[ name ];
  25247. if ( prevTexture !== undefined ) {
  25248. const texture = this._textures[ name ];
  25249. const index = this.renderTarget.textures.indexOf( texture );
  25250. this.renderTarget.textures[ index ] = prevTexture;
  25251. this._textures[ name ] = prevTexture;
  25252. this._previousTextures[ name ] = texture;
  25253. this._textureNodes[ name ].updateTexture();
  25254. this._previousTextureNodes[ name ].updateTexture();
  25255. }
  25256. }
  25257. /**
  25258. * Returns the texture node for the given output name.
  25259. *
  25260. * @param {string} [name='output'] - The output name to get the texture node for.
  25261. * @return {TextureNode} The texture node.
  25262. */
  25263. getTextureNode( name = 'output' ) {
  25264. let textureNode = this._textureNodes[ name ];
  25265. if ( textureNode === undefined ) {
  25266. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  25267. textureNode.updateTexture();
  25268. this._textureNodes[ name ] = textureNode;
  25269. }
  25270. return textureNode;
  25271. }
  25272. /**
  25273. * Returns the previous texture node for the given output name.
  25274. *
  25275. * @param {string} [name='output'] - The output name to get the previous texture node for.
  25276. * @return {TextureNode} The previous texture node.
  25277. */
  25278. getPreviousTextureNode( name = 'output' ) {
  25279. let textureNode = this._previousTextureNodes[ name ];
  25280. if ( textureNode === undefined ) {
  25281. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  25282. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  25283. textureNode.updateTexture();
  25284. this._previousTextureNodes[ name ] = textureNode;
  25285. }
  25286. return textureNode;
  25287. }
  25288. /**
  25289. * Returns a viewZ node of this pass.
  25290. *
  25291. * @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.
  25292. * @return {Node} The viewZ node.
  25293. */
  25294. getViewZNode( name = 'depth' ) {
  25295. let viewZNode = this._viewZNodes[ name ];
  25296. if ( viewZNode === undefined ) {
  25297. const cameraNear = this._cameraNear;
  25298. const cameraFar = this._cameraFar;
  25299. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  25300. }
  25301. return viewZNode;
  25302. }
  25303. /**
  25304. * Returns a linear depth node of this pass.
  25305. *
  25306. * @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.
  25307. * @return {Node} The linear depth node.
  25308. */
  25309. getLinearDepthNode( name = 'depth' ) {
  25310. let linearDepthNode = this._linearDepthNodes[ name ];
  25311. if ( linearDepthNode === undefined ) {
  25312. const cameraNear = this._cameraNear;
  25313. const cameraFar = this._cameraFar;
  25314. const viewZNode = this.getViewZNode( name );
  25315. // TODO: just if ( builder.camera.isPerspectiveCamera )
  25316. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  25317. }
  25318. return linearDepthNode;
  25319. }
  25320. /**
  25321. * Precompiles the pass.
  25322. *
  25323. * Note that this method must be called after the pass configuartion is complete.
  25324. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  25325. *
  25326. * @async
  25327. * @param {Renderer} renderer - The renderer.
  25328. * @return {Promise} A Promise that resolves when the compile has been finished.
  25329. * @see {@link Renderer#compileAsync}
  25330. */
  25331. async compileAsync( renderer ) {
  25332. const currentRenderTarget = renderer.getRenderTarget();
  25333. const currentMRT = renderer.getMRT();
  25334. renderer.setRenderTarget( this.renderTarget );
  25335. renderer.setMRT( this._mrt );
  25336. await renderer.compileAsync( this.scene, this.camera );
  25337. renderer.setRenderTarget( currentRenderTarget );
  25338. renderer.setMRT( currentMRT );
  25339. }
  25340. setup( { renderer } ) {
  25341. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  25342. this.renderTarget.texture.type = renderer.getColorBufferType();
  25343. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  25344. }
  25345. updateBefore( frame ) {
  25346. const { renderer } = frame;
  25347. const { scene } = this;
  25348. let camera;
  25349. let pixelRatio;
  25350. const outputRenderTarget = renderer.getOutputRenderTarget();
  25351. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  25352. pixelRatio = 1;
  25353. camera = renderer.xr.getCamera();
  25354. renderer.xr.updateCamera( camera );
  25355. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  25356. } else {
  25357. camera = this.camera;
  25358. pixelRatio = renderer.getPixelRatio();
  25359. renderer.getSize( _size );
  25360. }
  25361. this._pixelRatio = pixelRatio;
  25362. this.setSize( _size.width, _size.height );
  25363. const currentRenderTarget = renderer.getRenderTarget();
  25364. const currentMRT = renderer.getMRT();
  25365. const currentMask = camera.layers.mask;
  25366. this._cameraNear.value = camera.near;
  25367. this._cameraFar.value = camera.far;
  25368. if ( this._layers !== null ) {
  25369. camera.layers.mask = this._layers.mask;
  25370. }
  25371. for ( const name in this._previousTextures ) {
  25372. this.toggleTexture( name );
  25373. }
  25374. renderer.setRenderTarget( this.renderTarget );
  25375. renderer.setMRT( this._mrt );
  25376. renderer.render( scene, camera );
  25377. renderer.setRenderTarget( currentRenderTarget );
  25378. renderer.setMRT( currentMRT );
  25379. camera.layers.mask = currentMask;
  25380. }
  25381. /**
  25382. * Sets the size of the pass's render target. Honors the pixel ratio.
  25383. *
  25384. * @param {number} width - The width to set.
  25385. * @param {number} height - The height to set.
  25386. */
  25387. setSize( width, height ) {
  25388. this._width = width;
  25389. this._height = height;
  25390. const effectiveWidth = this._width * this._pixelRatio * this._resolution;
  25391. const effectiveHeight = this._height * this._pixelRatio * this._resolution;
  25392. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25393. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  25394. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  25395. }
  25396. /**
  25397. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  25398. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  25399. * with `null` as the single argument.
  25400. *
  25401. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  25402. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  25403. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  25404. * @param {number} width - The width of the scissor box in logical pixel unit.
  25405. * @param {number} height - The height of the scissor box in logical pixel unit.
  25406. */
  25407. setScissor( x, y, width, height ) {
  25408. if ( x === null ) {
  25409. this._scissor = null;
  25410. } else {
  25411. if ( this._scissor === null ) this._scissor = new Vector4();
  25412. if ( x.isVector4 ) {
  25413. this._scissor.copy( x );
  25414. } else {
  25415. this._scissor.set( x, y, width, height );
  25416. }
  25417. this._scissor.multiplyScalar( this._pixelRatio * this._resolution ).floor();
  25418. }
  25419. }
  25420. /**
  25421. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  25422. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  25423. * with `null` as the single argument.
  25424. *
  25425. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  25426. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  25427. * @param {number} width - The width of the viewport in logical pixel unit.
  25428. * @param {number} height - The height of the viewport in logical pixel unit.
  25429. */
  25430. setViewport( x, y, width, height ) {
  25431. if ( x === null ) {
  25432. this._viewport = null;
  25433. } else {
  25434. if ( this._viewport === null ) this._viewport = new Vector4();
  25435. if ( x.isVector4 ) {
  25436. this._viewport.copy( x );
  25437. } else {
  25438. this._viewport.set( x, y, width, height );
  25439. }
  25440. this._viewport.multiplyScalar( this._pixelRatio * this._resolution ).floor();
  25441. }
  25442. }
  25443. /**
  25444. * Sets the pixel ratio the pass's render target and updates the size.
  25445. *
  25446. * @param {number} pixelRatio - The pixel ratio to set.
  25447. */
  25448. setPixelRatio( pixelRatio ) {
  25449. this._pixelRatio = pixelRatio;
  25450. this.setSize( this._width, this._height );
  25451. }
  25452. /**
  25453. * Frees internal resources. Should be called when the node is no longer in use.
  25454. */
  25455. dispose() {
  25456. this.renderTarget.dispose();
  25457. }
  25458. }
  25459. /**
  25460. * @static
  25461. * @type {'color'}
  25462. * @default 'color'
  25463. */
  25464. PassNode.COLOR = 'color';
  25465. /**
  25466. * @static
  25467. * @type {'depth'}
  25468. * @default 'depth'
  25469. */
  25470. PassNode.DEPTH = 'depth';
  25471. /**
  25472. * TSL function for creating a pass node.
  25473. *
  25474. * @tsl
  25475. * @function
  25476. * @param {Scene} scene - A reference to the scene.
  25477. * @param {Camera} camera - A reference to the camera.
  25478. * @param {Object} options - Options for the internal render target.
  25479. * @returns {PassNode}
  25480. */
  25481. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  25482. /**
  25483. * TSL function for creating a pass texture node.
  25484. *
  25485. * @tsl
  25486. * @function
  25487. * @param {PassNode} pass - The pass node.
  25488. * @param {Texture} texture - The output texture.
  25489. * @returns {PassTextureNode}
  25490. */
  25491. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  25492. /**
  25493. * TSL function for creating a depth pass node.
  25494. *
  25495. * @tsl
  25496. * @function
  25497. * @param {Scene} scene - A reference to the scene.
  25498. * @param {Camera} camera - A reference to the camera.
  25499. * @param {Object} options - Options for the internal render target.
  25500. * @returns {PassNode}
  25501. */
  25502. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  25503. /**
  25504. * Represents a render pass for producing a toon outline effect on compatible objects.
  25505. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  25506. * will receive the outline.
  25507. *
  25508. * ```js
  25509. * const postProcessing = new PostProcessing( renderer );
  25510. *
  25511. * const scenePass = toonOutlinePass( scene, camera );
  25512. *
  25513. * postProcessing.outputNode = scenePass;
  25514. * ```
  25515. * @augments PassNode
  25516. */
  25517. class ToonOutlinePassNode extends PassNode {
  25518. static get type() {
  25519. return 'ToonOutlinePassNode';
  25520. }
  25521. /**
  25522. * Constructs a new outline pass node.
  25523. *
  25524. * @param {Scene} scene - A reference to the scene.
  25525. * @param {Camera} camera - A reference to the camera.
  25526. * @param {Node} colorNode - Defines the outline's color.
  25527. * @param {Node} thicknessNode - Defines the outline's thickness.
  25528. * @param {Node} alphaNode - Defines the outline's alpha.
  25529. */
  25530. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  25531. super( PassNode.COLOR, scene, camera );
  25532. /**
  25533. * Defines the outline's color.
  25534. *
  25535. * @type {Node}
  25536. */
  25537. this.colorNode = colorNode;
  25538. /**
  25539. * Defines the outline's thickness.
  25540. *
  25541. * @type {Node}
  25542. */
  25543. this.thicknessNode = thicknessNode;
  25544. /**
  25545. * Defines the outline's alpha.
  25546. *
  25547. * @type {Node}
  25548. */
  25549. this.alphaNode = alphaNode;
  25550. /**
  25551. * An internal material cache.
  25552. *
  25553. * @private
  25554. * @type {WeakMap<Material, NodeMaterial>}
  25555. */
  25556. this._materialCache = new WeakMap();
  25557. }
  25558. updateBefore( frame ) {
  25559. const { renderer } = frame;
  25560. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  25561. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  25562. // only render outline for supported materials
  25563. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  25564. if ( material.wireframe === false ) {
  25565. const outlineMaterial = this._getOutlineMaterial( material );
  25566. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  25567. }
  25568. }
  25569. // default
  25570. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  25571. } );
  25572. super.updateBefore( frame );
  25573. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  25574. }
  25575. /**
  25576. * Creates the material used for outline rendering.
  25577. *
  25578. * @private
  25579. * @return {NodeMaterial} The outline material.
  25580. */
  25581. _createMaterial() {
  25582. const material = new NodeMaterial();
  25583. material.isMeshToonOutlineMaterial = true;
  25584. material.name = 'Toon_Outline';
  25585. material.side = BackSide;
  25586. // vertex node
  25587. const outlineNormal = normalLocal.negate();
  25588. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  25589. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  25590. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  25591. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  25592. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  25593. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  25594. // color node
  25595. material.colorNode = vec4( this.colorNode, this.alphaNode );
  25596. return material;
  25597. }
  25598. /**
  25599. * For the given toon material, this method returns a corresponding
  25600. * outline material.
  25601. *
  25602. * @private
  25603. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  25604. * @return {NodeMaterial} The outline material.
  25605. */
  25606. _getOutlineMaterial( originalMaterial ) {
  25607. let outlineMaterial = this._materialCache.get( originalMaterial );
  25608. if ( outlineMaterial === undefined ) {
  25609. outlineMaterial = this._createMaterial();
  25610. this._materialCache.set( originalMaterial, outlineMaterial );
  25611. }
  25612. return outlineMaterial;
  25613. }
  25614. }
  25615. /**
  25616. * TSL function for creating a toon outline pass node.
  25617. *
  25618. * @tsl
  25619. * @function
  25620. * @param {Scene} scene - A reference to the scene.
  25621. * @param {Camera} camera - A reference to the camera.
  25622. * @param {Color} color - Defines the outline's color.
  25623. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  25624. * @param {number} [alpha=1] - Defines the outline's alpha.
  25625. * @returns {ToonOutlinePassNode}
  25626. */
  25627. 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 ) ) );
  25628. /**
  25629. * Linear tone mapping, exposure only.
  25630. *
  25631. * @tsl
  25632. * @function
  25633. * @param {Node<vec3>} color - The color that should be tone mapped.
  25634. * @param {Node<float>} exposure - The exposure.
  25635. * @return {Node<vec3>} The tone mapped color.
  25636. */
  25637. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25638. return color.mul( exposure ).clamp();
  25639. } ).setLayout( {
  25640. name: 'linearToneMapping',
  25641. type: 'vec3',
  25642. inputs: [
  25643. { name: 'color', type: 'vec3' },
  25644. { name: 'exposure', type: 'float' }
  25645. ]
  25646. } );
  25647. /**
  25648. * Reinhard tone mapping.
  25649. *
  25650. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  25651. *
  25652. * @tsl
  25653. * @function
  25654. * @param {Node<vec3>} color - The color that should be tone mapped.
  25655. * @param {Node<float>} exposure - The exposure.
  25656. * @return {Node<vec3>} The tone mapped color.
  25657. */
  25658. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25659. color = color.mul( exposure );
  25660. return color.div( color.add( 1.0 ) ).clamp();
  25661. } ).setLayout( {
  25662. name: 'reinhardToneMapping',
  25663. type: 'vec3',
  25664. inputs: [
  25665. { name: 'color', type: 'vec3' },
  25666. { name: 'exposure', type: 'float' }
  25667. ]
  25668. } );
  25669. /**
  25670. * Cineon tone mapping.
  25671. *
  25672. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  25673. *
  25674. * @tsl
  25675. * @function
  25676. * @param {Node<vec3>} color - The color that should be tone mapped.
  25677. * @param {Node<float>} exposure - The exposure.
  25678. * @return {Node<vec3>} The tone mapped color.
  25679. */
  25680. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25681. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  25682. color = color.mul( exposure );
  25683. color = color.sub( 0.004 ).max( 0.0 );
  25684. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  25685. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  25686. return a.div( b ).pow( 2.2 );
  25687. } ).setLayout( {
  25688. name: 'cineonToneMapping',
  25689. type: 'vec3',
  25690. inputs: [
  25691. { name: 'color', type: 'vec3' },
  25692. { name: 'exposure', type: 'float' }
  25693. ]
  25694. } );
  25695. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  25696. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  25697. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  25698. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  25699. return a.div( b );
  25700. } );
  25701. /**
  25702. * ACESFilmic tone mapping.
  25703. *
  25704. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  25705. *
  25706. * @tsl
  25707. * @function
  25708. * @param {Node<vec3>} color - The color that should be tone mapped.
  25709. * @param {Node<float>} exposure - The exposure.
  25710. * @return {Node<vec3>} The tone mapped color.
  25711. */
  25712. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25713. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  25714. const ACESInputMat = mat3(
  25715. 0.59719, 0.35458, 0.04823,
  25716. 0.07600, 0.90834, 0.01566,
  25717. 0.02840, 0.13383, 0.83777
  25718. );
  25719. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  25720. const ACESOutputMat = mat3(
  25721. 1.60475, -0.53108, -0.07367,
  25722. -0.10208, 1.10813, -605e-5,
  25723. -327e-5, -0.07276, 1.07602
  25724. );
  25725. color = color.mul( exposure ).div( 0.6 );
  25726. color = ACESInputMat.mul( color );
  25727. // Apply RRT and ODT
  25728. color = RRTAndODTFit( color );
  25729. color = ACESOutputMat.mul( color );
  25730. // Clamp to [0, 1]
  25731. return color.clamp();
  25732. } ).setLayout( {
  25733. name: 'acesFilmicToneMapping',
  25734. type: 'vec3',
  25735. inputs: [
  25736. { name: 'color', type: 'vec3' },
  25737. { name: 'exposure', type: 'float' }
  25738. ]
  25739. } );
  25740. 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 ) );
  25741. 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 ) );
  25742. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  25743. const x = vec3( x_immutable ).toVar();
  25744. const x2 = vec3( x.mul( x ) ).toVar();
  25745. const x4 = vec3( x2.mul( x2 ) ).toVar();
  25746. 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 ) ) ) );
  25747. } );
  25748. /**
  25749. * AgX tone mapping.
  25750. *
  25751. * @tsl
  25752. * @function
  25753. * @param {Node<vec3>} color - The color that should be tone mapped.
  25754. * @param {Node<float>} exposure - The exposure.
  25755. * @return {Node<vec3>} The tone mapped color.
  25756. */
  25757. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25758. const colortone = vec3( color ).toVar();
  25759. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  25760. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  25761. const AgxMinEv = float( -12.47393 );
  25762. const AgxMaxEv = float( 4.026069 );
  25763. colortone.mulAssign( exposure );
  25764. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  25765. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  25766. colortone.assign( max$1( colortone, 1e-10 ) );
  25767. colortone.assign( log2( colortone ) );
  25768. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  25769. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  25770. colortone.assign( agxDefaultContrastApprox( colortone ) );
  25771. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  25772. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  25773. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  25774. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  25775. return colortone;
  25776. } ).setLayout( {
  25777. name: 'agxToneMapping',
  25778. type: 'vec3',
  25779. inputs: [
  25780. { name: 'color', type: 'vec3' },
  25781. { name: 'exposure', type: 'float' }
  25782. ]
  25783. } );
  25784. /**
  25785. * Neutral tone mapping.
  25786. *
  25787. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  25788. *
  25789. * @tsl
  25790. * @function
  25791. * @param {Node<vec3>} color - The color that should be tone mapped.
  25792. * @param {Node<float>} exposure - The exposure.
  25793. * @return {Node<vec3>} The tone mapped color.
  25794. */
  25795. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25796. const StartCompression = float( 0.8 - 0.04 );
  25797. const Desaturation = float( 0.15 );
  25798. color = color.mul( exposure );
  25799. const x = min$1( color.r, min$1( color.g, color.b ) );
  25800. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  25801. color.subAssign( offset );
  25802. const peak = max$1( color.r, max$1( color.g, color.b ) );
  25803. If( peak.lessThan( StartCompression ), () => {
  25804. return color;
  25805. } );
  25806. const d = sub( 1, StartCompression );
  25807. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  25808. color.mulAssign( newPeak.div( peak ) );
  25809. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  25810. return mix( color, vec3( newPeak ), g );
  25811. } ).setLayout( {
  25812. name: 'neutralToneMapping',
  25813. type: 'vec3',
  25814. inputs: [
  25815. { name: 'color', type: 'vec3' },
  25816. { name: 'exposure', type: 'float' }
  25817. ]
  25818. } );
  25819. /**
  25820. * This class represents native code sections. It is the base
  25821. * class for modules like {@link FunctionNode} which allows to implement
  25822. * functions with native shader languages.
  25823. *
  25824. * @augments Node
  25825. */
  25826. class CodeNode extends Node {
  25827. static get type() {
  25828. return 'CodeNode';
  25829. }
  25830. /**
  25831. * Constructs a new code node.
  25832. *
  25833. * @param {string} [code=''] - The native code.
  25834. * @param {Array<Node>} [includes=[]] - An array of includes.
  25835. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25836. */
  25837. constructor( code = '', includes = [], language = '' ) {
  25838. super( 'code' );
  25839. /**
  25840. * This flag can be used for type testing.
  25841. *
  25842. * @type {boolean}
  25843. * @readonly
  25844. * @default true
  25845. */
  25846. this.isCodeNode = true;
  25847. /**
  25848. * This flag is used for global cache.
  25849. *
  25850. * @type {boolean}
  25851. * @default true
  25852. */
  25853. this.global = true;
  25854. /**
  25855. * The native code.
  25856. *
  25857. * @type {string}
  25858. * @default ''
  25859. */
  25860. this.code = code;
  25861. /**
  25862. * An array of includes
  25863. *
  25864. * @type {Array<Node>}
  25865. * @default []
  25866. */
  25867. this.includes = includes;
  25868. /**
  25869. * The used language.
  25870. *
  25871. * @type {('js'|'wgsl'|'glsl')}
  25872. * @default ''
  25873. */
  25874. this.language = language;
  25875. }
  25876. /**
  25877. * Sets the includes of this code node.
  25878. *
  25879. * @param {Array<Node>} includes - The includes to set.
  25880. * @return {CodeNode} A reference to this node.
  25881. */
  25882. setIncludes( includes ) {
  25883. this.includes = includes;
  25884. return this;
  25885. }
  25886. /**
  25887. * Returns the includes of this code node.
  25888. *
  25889. * @param {NodeBuilder} builder - The current node builder.
  25890. * @return {Array<Node>} The includes.
  25891. */
  25892. getIncludes( /*builder*/ ) {
  25893. return this.includes;
  25894. }
  25895. generate( builder ) {
  25896. const includes = this.getIncludes( builder );
  25897. for ( const include of includes ) {
  25898. include.build( builder );
  25899. }
  25900. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  25901. nodeCode.code = this.code;
  25902. return nodeCode.code;
  25903. }
  25904. serialize( data ) {
  25905. super.serialize( data );
  25906. data.code = this.code;
  25907. data.language = this.language;
  25908. }
  25909. deserialize( data ) {
  25910. super.deserialize( data );
  25911. this.code = data.code;
  25912. this.language = data.language;
  25913. }
  25914. }
  25915. /**
  25916. * TSL function for creating a code node.
  25917. *
  25918. * @tsl
  25919. * @function
  25920. * @param {string} [code] - The native code.
  25921. * @param {?Array<Node>} [includes=[]] - An array of includes.
  25922. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25923. * @returns {CodeNode}
  25924. */
  25925. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  25926. /**
  25927. * TSL function for creating a JS code node.
  25928. *
  25929. * @tsl
  25930. * @function
  25931. * @param {string} src - The native code.
  25932. * @param {Array<Node>} includes - An array of includes.
  25933. * @returns {CodeNode}
  25934. */
  25935. const js = ( src, includes ) => code( src, includes, 'js' );
  25936. /**
  25937. * TSL function for creating a WGSL code node.
  25938. *
  25939. * @tsl
  25940. * @function
  25941. * @param {string} src - The native code.
  25942. * @param {Array<Node>} includes - An array of includes.
  25943. * @returns {CodeNode}
  25944. */
  25945. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  25946. /**
  25947. * TSL function for creating a GLSL code node.
  25948. *
  25949. * @tsl
  25950. * @function
  25951. * @param {string} src - The native code.
  25952. * @param {Array<Node>} includes - An array of includes.
  25953. * @returns {CodeNode}
  25954. */
  25955. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  25956. /**
  25957. * This class represents a native shader function. It can be used to implement
  25958. * certain aspects of a node material with native shader code. There are two predefined
  25959. * TSL functions for easier usage.
  25960. *
  25961. * - `wgslFn`: Creates a WGSL function node.
  25962. * - `glslFn`: Creates a GLSL function node.
  25963. *
  25964. * A basic example with one include looks like so:
  25965. *
  25966. * ```js
  25967. * const desaturateWGSLFn = wgslFn( `
  25968. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  25969. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  25970. * return vec3<f32>( dot( lum, color ) );
  25971. * }`
  25972. *);
  25973. * const someWGSLFn = wgslFn( `
  25974. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  25975. * return desaturate( color );
  25976. * }
  25977. * `, [ desaturateWGSLFn ] );
  25978. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  25979. *```
  25980. * @augments CodeNode
  25981. */
  25982. class FunctionNode extends CodeNode {
  25983. static get type() {
  25984. return 'FunctionNode';
  25985. }
  25986. /**
  25987. * Constructs a new function node.
  25988. *
  25989. * @param {string} [code=''] - The native code.
  25990. * @param {Array<Node>} [includes=[]] - An array of includes.
  25991. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25992. */
  25993. constructor( code = '', includes = [], language = '' ) {
  25994. super( code, includes, language );
  25995. }
  25996. getNodeType( builder ) {
  25997. return this.getNodeFunction( builder ).type;
  25998. }
  25999. /**
  26000. * Returns the inputs of this function node.
  26001. *
  26002. * @param {NodeBuilder} builder - The current node builder.
  26003. * @return {Array<NodeFunctionInput>} The inputs.
  26004. */
  26005. getInputs( builder ) {
  26006. return this.getNodeFunction( builder ).inputs;
  26007. }
  26008. /**
  26009. * Returns the node function for this function node.
  26010. *
  26011. * @param {NodeBuilder} builder - The current node builder.
  26012. * @return {NodeFunction} The node function.
  26013. */
  26014. getNodeFunction( builder ) {
  26015. const nodeData = builder.getDataFromNode( this );
  26016. let nodeFunction = nodeData.nodeFunction;
  26017. if ( nodeFunction === undefined ) {
  26018. nodeFunction = builder.parser.parseFunction( this.code );
  26019. nodeData.nodeFunction = nodeFunction;
  26020. }
  26021. return nodeFunction;
  26022. }
  26023. generate( builder, output ) {
  26024. super.generate( builder );
  26025. const nodeFunction = this.getNodeFunction( builder );
  26026. const name = nodeFunction.name;
  26027. const type = nodeFunction.type;
  26028. const nodeCode = builder.getCodeFromNode( this, type );
  26029. if ( name !== '' ) {
  26030. // use a custom property name
  26031. nodeCode.name = name;
  26032. }
  26033. const propertyName = builder.getPropertyName( nodeCode );
  26034. const code = this.getNodeFunction( builder ).getCode( propertyName );
  26035. nodeCode.code = code + '\n';
  26036. if ( output === 'property' ) {
  26037. return propertyName;
  26038. } else {
  26039. return builder.format( `${ propertyName }()`, type, output );
  26040. }
  26041. }
  26042. }
  26043. const nativeFn = ( code, includes = [], language = '' ) => {
  26044. for ( let i = 0; i < includes.length; i ++ ) {
  26045. const include = includes[ i ];
  26046. // TSL Function: glslFn, wgslFn
  26047. if ( typeof include === 'function' ) {
  26048. includes[ i ] = include.functionNode;
  26049. }
  26050. }
  26051. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  26052. const fn = ( ...params ) => functionNode.call( ...params );
  26053. fn.functionNode = functionNode;
  26054. return fn;
  26055. };
  26056. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  26057. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  26058. /**
  26059. * `ScriptableNode` uses this class to manage script inputs and outputs.
  26060. *
  26061. * @augments Node
  26062. */
  26063. class ScriptableValueNode extends Node {
  26064. static get type() {
  26065. return 'ScriptableValueNode';
  26066. }
  26067. /**
  26068. * Constructs a new scriptable node.
  26069. *
  26070. * @param {any} [value=null] - The value.
  26071. */
  26072. constructor( value = null ) {
  26073. super();
  26074. /**
  26075. * A reference to the value.
  26076. *
  26077. * @private
  26078. * @default null
  26079. */
  26080. this._value = value;
  26081. /**
  26082. * Depending on the type of `_value`, this property might cache parsed data.
  26083. *
  26084. * @private
  26085. * @default null
  26086. */
  26087. this._cache = null;
  26088. /**
  26089. * If this node represents an input, this property represents the input type.
  26090. *
  26091. * @type {?string}
  26092. * @default null
  26093. */
  26094. this.inputType = null;
  26095. /**
  26096. * If this node represents an output, this property represents the output type.
  26097. *
  26098. * @type {?string}
  26099. * @default null
  26100. */
  26101. this.outputType = null;
  26102. /**
  26103. * An event dispatcher for managing events.
  26104. *
  26105. * @type {EventDispatcher}
  26106. */
  26107. this.events = new EventDispatcher();
  26108. /**
  26109. * This flag can be used for type testing.
  26110. *
  26111. * @type {boolean}
  26112. * @readonly
  26113. * @default true
  26114. */
  26115. this.isScriptableValueNode = true;
  26116. }
  26117. /**
  26118. * Whether this node represents an output or not.
  26119. *
  26120. * @type {boolean}
  26121. * @readonly
  26122. * @default true
  26123. */
  26124. get isScriptableOutputNode() {
  26125. return this.outputType !== null;
  26126. }
  26127. set value( val ) {
  26128. if ( this._value === val ) return;
  26129. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  26130. URL.revokeObjectURL( this._cache );
  26131. this._cache = null;
  26132. }
  26133. this._value = val;
  26134. this.events.dispatchEvent( { type: 'change' } );
  26135. this.refresh();
  26136. }
  26137. /**
  26138. * The node's value.
  26139. *
  26140. * @type {any}
  26141. */
  26142. get value() {
  26143. return this._value;
  26144. }
  26145. /**
  26146. * Dispatches the `refresh` event.
  26147. */
  26148. refresh() {
  26149. this.events.dispatchEvent( { type: 'refresh' } );
  26150. }
  26151. /**
  26152. * The `value` property usually represents a node or even binary data in form of array buffers.
  26153. * In this case, this method tries to return the actual value behind the complex type.
  26154. *
  26155. * @return {any} The value.
  26156. */
  26157. getValue() {
  26158. const value = this.value;
  26159. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  26160. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  26161. } else if ( value && value.value !== null && value.value !== undefined && (
  26162. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  26163. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  26164. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  26165. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  26166. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  26167. ( this.inputType === 'Color' && value.value.isColor ) ||
  26168. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  26169. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  26170. ) ) {
  26171. return value.value;
  26172. }
  26173. return this._cache || value;
  26174. }
  26175. /**
  26176. * Overwritten since the node type is inferred from the value.
  26177. *
  26178. * @param {NodeBuilder} builder - The current node builder.
  26179. * @return {string} The node type.
  26180. */
  26181. getNodeType( builder ) {
  26182. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  26183. }
  26184. setup() {
  26185. return this.value && this.value.isNode ? this.value : float();
  26186. }
  26187. serialize( data ) {
  26188. super.serialize( data );
  26189. if ( this.value !== null ) {
  26190. if ( this.inputType === 'ArrayBuffer' ) {
  26191. data.value = arrayBufferToBase64( this.value );
  26192. } else {
  26193. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  26194. }
  26195. } else {
  26196. data.value = null;
  26197. }
  26198. data.inputType = this.inputType;
  26199. data.outputType = this.outputType;
  26200. }
  26201. deserialize( data ) {
  26202. super.deserialize( data );
  26203. let value = null;
  26204. if ( data.value !== null ) {
  26205. if ( data.inputType === 'ArrayBuffer' ) {
  26206. value = base64ToArrayBuffer( data.value );
  26207. } else if ( data.inputType === 'Texture' ) {
  26208. value = data.meta.textures[ data.value ];
  26209. } else {
  26210. value = data.meta.nodes[ data.value ] || null;
  26211. }
  26212. }
  26213. this.value = value;
  26214. this.inputType = data.inputType;
  26215. this.outputType = data.outputType;
  26216. }
  26217. }
  26218. /**
  26219. * TSL function for creating a scriptable value node.
  26220. *
  26221. * @tsl
  26222. * @function
  26223. * @param {any} [value] - The value.
  26224. * @returns {ScriptableValueNode}
  26225. */
  26226. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  26227. /**
  26228. * A Map-like data structure for managing resources of scriptable nodes.
  26229. *
  26230. * @augments Map
  26231. */
  26232. class Resources extends Map {
  26233. get( key, callback = null, ...params ) {
  26234. if ( this.has( key ) ) return super.get( key );
  26235. if ( callback !== null ) {
  26236. const value = callback( ...params );
  26237. this.set( key, value );
  26238. return value;
  26239. }
  26240. }
  26241. }
  26242. class Parameters {
  26243. constructor( scriptableNode ) {
  26244. this.scriptableNode = scriptableNode;
  26245. }
  26246. get parameters() {
  26247. return this.scriptableNode.parameters;
  26248. }
  26249. get layout() {
  26250. return this.scriptableNode.getLayout();
  26251. }
  26252. getInputLayout( id ) {
  26253. return this.scriptableNode.getInputLayout( id );
  26254. }
  26255. get( name ) {
  26256. const param = this.parameters[ name ];
  26257. const value = param ? param.getValue() : null;
  26258. return value;
  26259. }
  26260. }
  26261. /**
  26262. * Defines the resources (e.g. namespaces) of scriptable nodes.
  26263. *
  26264. * @type {Resources}
  26265. */
  26266. const ScriptableNodeResources = new Resources();
  26267. /**
  26268. * This type of node allows to implement nodes with custom scripts. The script
  26269. * section is represented as an instance of `CodeNode` written with JavaScript.
  26270. * The script itself must adhere to a specific structure.
  26271. *
  26272. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  26273. * - layout: The layout object defines the script's interface (inputs and outputs).
  26274. *
  26275. * ```js
  26276. * ScriptableNodeResources.set( 'TSL', TSL );
  26277. *
  26278. * const scriptableNode = scriptable( js( `
  26279. * layout = {
  26280. * outputType: 'node',
  26281. * elements: [
  26282. * { name: 'source', inputType: 'node' },
  26283. * ]
  26284. * };
  26285. *
  26286. * const { mul, oscSine } = TSL;
  26287. *
  26288. * function main() {
  26289. * const source = parameters.get( 'source' ) || float();
  26290. * return mul( source, oscSine() ) );
  26291. * }
  26292. *
  26293. * ` ) );
  26294. *
  26295. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  26296. *
  26297. * const material = new THREE.MeshBasicNodeMaterial();
  26298. * material.colorNode = scriptableNode;
  26299. * ```
  26300. *
  26301. * @augments Node
  26302. */
  26303. class ScriptableNode extends Node {
  26304. static get type() {
  26305. return 'ScriptableNode';
  26306. }
  26307. /**
  26308. * Constructs a new scriptable node.
  26309. *
  26310. * @param {?CodeNode} [codeNode=null] - The code node.
  26311. * @param {Object} [parameters={}] - The parameters definition.
  26312. */
  26313. constructor( codeNode = null, parameters = {} ) {
  26314. super();
  26315. /**
  26316. * The code node.
  26317. *
  26318. * @type {?CodeNode}
  26319. * @default null
  26320. */
  26321. this.codeNode = codeNode;
  26322. /**
  26323. * The parameters definition.
  26324. *
  26325. * @type {Object}
  26326. * @default {}
  26327. */
  26328. this.parameters = parameters;
  26329. this._local = new Resources();
  26330. this._output = scriptableValue( null );
  26331. this._outputs = {};
  26332. this._source = this.source;
  26333. this._method = null;
  26334. this._object = null;
  26335. this._value = null;
  26336. this._needsOutputUpdate = true;
  26337. this.onRefresh = this.onRefresh.bind( this );
  26338. /**
  26339. * This flag can be used for type testing.
  26340. *
  26341. * @type {boolean}
  26342. * @readonly
  26343. * @default true
  26344. */
  26345. this.isScriptableNode = true;
  26346. }
  26347. /**
  26348. * The source code of the scriptable node.
  26349. *
  26350. * @type {string}
  26351. */
  26352. get source() {
  26353. return this.codeNode ? this.codeNode.code : '';
  26354. }
  26355. /**
  26356. * Sets the reference of a local script variable.
  26357. *
  26358. * @param {string} name - The variable name.
  26359. * @param {Object} value - The reference to set.
  26360. * @return {Resources} The resource map
  26361. */
  26362. setLocal( name, value ) {
  26363. return this._local.set( name, value );
  26364. }
  26365. /**
  26366. * Gets the value of a local script variable.
  26367. *
  26368. * @param {string} name - The variable name.
  26369. * @return {Object} The value.
  26370. */
  26371. getLocal( name ) {
  26372. return this._local.get( name );
  26373. }
  26374. /**
  26375. * Event listener for the `refresh` event.
  26376. */
  26377. onRefresh() {
  26378. this._refresh();
  26379. }
  26380. /**
  26381. * Returns an input from the layout with the given id/name.
  26382. *
  26383. * @param {string} id - The id/name of the input.
  26384. * @return {Object} The element entry.
  26385. */
  26386. getInputLayout( id ) {
  26387. for ( const element of this.getLayout() ) {
  26388. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  26389. return element;
  26390. }
  26391. }
  26392. }
  26393. /**
  26394. * Returns an output from the layout with the given id/name.
  26395. *
  26396. * @param {string} id - The id/name of the output.
  26397. * @return {Object} The element entry.
  26398. */
  26399. getOutputLayout( id ) {
  26400. for ( const element of this.getLayout() ) {
  26401. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  26402. return element;
  26403. }
  26404. }
  26405. }
  26406. /**
  26407. * Defines a script output for the given name and value.
  26408. *
  26409. * @param {string} name - The name of the output.
  26410. * @param {Node} value - The node value.
  26411. * @return {ScriptableNode} A reference to this node.
  26412. */
  26413. setOutput( name, value ) {
  26414. const outputs = this._outputs;
  26415. if ( outputs[ name ] === undefined ) {
  26416. outputs[ name ] = scriptableValue( value );
  26417. } else {
  26418. outputs[ name ].value = value;
  26419. }
  26420. return this;
  26421. }
  26422. /**
  26423. * Returns a script output for the given name.
  26424. *
  26425. * @param {string} name - The name of the output.
  26426. * @return {ScriptableValueNode} The node value.
  26427. */
  26428. getOutput( name ) {
  26429. return this._outputs[ name ];
  26430. }
  26431. /**
  26432. * Returns a parameter for the given name
  26433. *
  26434. * @param {string} name - The name of the parameter.
  26435. * @return {ScriptableValueNode} The node value.
  26436. */
  26437. getParameter( name ) {
  26438. return this.parameters[ name ];
  26439. }
  26440. /**
  26441. * Sets a value for the given parameter name.
  26442. *
  26443. * @param {string} name - The parameter name.
  26444. * @param {any} value - The parameter value.
  26445. * @return {ScriptableNode} A reference to this node.
  26446. */
  26447. setParameter( name, value ) {
  26448. const parameters = this.parameters;
  26449. if ( value && value.isScriptableNode ) {
  26450. this.deleteParameter( name );
  26451. parameters[ name ] = value;
  26452. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  26453. } else if ( value && value.isScriptableValueNode ) {
  26454. this.deleteParameter( name );
  26455. parameters[ name ] = value;
  26456. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  26457. } else if ( parameters[ name ] === undefined ) {
  26458. parameters[ name ] = scriptableValue( value );
  26459. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  26460. } else {
  26461. parameters[ name ].value = value;
  26462. }
  26463. return this;
  26464. }
  26465. /**
  26466. * Returns the value of this node which is the value of
  26467. * the default output.
  26468. *
  26469. * @return {Node} The value.
  26470. */
  26471. getValue() {
  26472. return this.getDefaultOutput().getValue();
  26473. }
  26474. /**
  26475. * Deletes a parameter from the script.
  26476. *
  26477. * @param {string} name - The parameter to remove.
  26478. * @return {ScriptableNode} A reference to this node.
  26479. */
  26480. deleteParameter( name ) {
  26481. let valueNode = this.parameters[ name ];
  26482. if ( valueNode ) {
  26483. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  26484. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  26485. }
  26486. return this;
  26487. }
  26488. /**
  26489. * Deletes all parameters from the script.
  26490. *
  26491. * @return {ScriptableNode} A reference to this node.
  26492. */
  26493. clearParameters() {
  26494. for ( const name of Object.keys( this.parameters ) ) {
  26495. this.deleteParameter( name );
  26496. }
  26497. this.needsUpdate = true;
  26498. return this;
  26499. }
  26500. /**
  26501. * Calls a function from the script.
  26502. *
  26503. * @param {string} name - The function name.
  26504. * @param {...any} params - A list of parameters.
  26505. * @return {any} The result of the function call.
  26506. */
  26507. call( name, ...params ) {
  26508. const object = this.getObject();
  26509. const method = object[ name ];
  26510. if ( typeof method === 'function' ) {
  26511. return method( ...params );
  26512. }
  26513. }
  26514. /**
  26515. * Asynchronously calls a function from the script.
  26516. *
  26517. * @param {string} name - The function name.
  26518. * @param {...any} params - A list of parameters.
  26519. * @return {Promise<any>} The result of the function call.
  26520. */
  26521. async callAsync( name, ...params ) {
  26522. const object = this.getObject();
  26523. const method = object[ name ];
  26524. if ( typeof method === 'function' ) {
  26525. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  26526. }
  26527. }
  26528. /**
  26529. * Overwritten since the node types is inferred from the script's output.
  26530. *
  26531. * @param {NodeBuilder} builder - The current node builder
  26532. * @return {string} The node type.
  26533. */
  26534. getNodeType( builder ) {
  26535. return this.getDefaultOutputNode().getNodeType( builder );
  26536. }
  26537. /**
  26538. * Refreshes the script node.
  26539. *
  26540. * @param {?string} [output=null] - An optional output.
  26541. */
  26542. refresh( output = null ) {
  26543. if ( output !== null ) {
  26544. this.getOutput( output ).refresh();
  26545. } else {
  26546. this._refresh();
  26547. }
  26548. }
  26549. /**
  26550. * Returns an object representation of the script.
  26551. *
  26552. * @return {Object} The result object.
  26553. */
  26554. getObject() {
  26555. if ( this.needsUpdate ) this.dispose();
  26556. if ( this._object !== null ) return this._object;
  26557. //
  26558. const refresh = () => this.refresh();
  26559. const setOutput = ( id, value ) => this.setOutput( id, value );
  26560. const parameters = new Parameters( this );
  26561. const THREE = ScriptableNodeResources.get( 'THREE' );
  26562. const TSL = ScriptableNodeResources.get( 'TSL' );
  26563. const method = this.getMethod();
  26564. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  26565. this._object = method( ...params );
  26566. const layout = this._object.layout;
  26567. if ( layout ) {
  26568. if ( layout.cache === false ) {
  26569. this._local.clear();
  26570. }
  26571. // default output
  26572. this._output.outputType = layout.outputType || null;
  26573. if ( Array.isArray( layout.elements ) ) {
  26574. for ( const element of layout.elements ) {
  26575. const id = element.id || element.name;
  26576. if ( element.inputType ) {
  26577. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  26578. this.getParameter( id ).inputType = element.inputType;
  26579. }
  26580. if ( element.outputType ) {
  26581. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  26582. this.getOutput( id ).outputType = element.outputType;
  26583. }
  26584. }
  26585. }
  26586. }
  26587. return this._object;
  26588. }
  26589. deserialize( data ) {
  26590. super.deserialize( data );
  26591. for ( const name in this.parameters ) {
  26592. let valueNode = this.parameters[ name ];
  26593. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  26594. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  26595. }
  26596. }
  26597. /**
  26598. * Returns the layout of the script.
  26599. *
  26600. * @return {Object} The script's layout.
  26601. */
  26602. getLayout() {
  26603. return this.getObject().layout;
  26604. }
  26605. /**
  26606. * Returns default node output of the script.
  26607. *
  26608. * @return {Node} The default node output.
  26609. */
  26610. getDefaultOutputNode() {
  26611. const output = this.getDefaultOutput().value;
  26612. if ( output && output.isNode ) {
  26613. return output;
  26614. }
  26615. return float();
  26616. }
  26617. /**
  26618. * Returns default output of the script.
  26619. *
  26620. * @return {ScriptableValueNode} The default output.
  26621. */
  26622. getDefaultOutput() {
  26623. return this._exec()._output;
  26624. }
  26625. /**
  26626. * Returns a function created from the node's script.
  26627. *
  26628. * @return {Function} The function representing the node's code.
  26629. */
  26630. getMethod() {
  26631. if ( this.needsUpdate ) this.dispose();
  26632. if ( this._method !== null ) return this._method;
  26633. //
  26634. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  26635. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  26636. const properties = interfaceProps.join( ', ' );
  26637. const declarations = 'var ' + properties + '; var output = {};\n';
  26638. const returns = '\nreturn { ...output, ' + properties + ' };';
  26639. const code = declarations + this.codeNode.code + returns;
  26640. //
  26641. this._method = new Function( ...parametersProps, code );
  26642. return this._method;
  26643. }
  26644. /**
  26645. * Frees all internal resources.
  26646. */
  26647. dispose() {
  26648. if ( this._method === null ) return;
  26649. if ( this._object && typeof this._object.dispose === 'function' ) {
  26650. this._object.dispose();
  26651. }
  26652. this._method = null;
  26653. this._object = null;
  26654. this._source = null;
  26655. this._value = null;
  26656. this._needsOutputUpdate = true;
  26657. this._output.value = null;
  26658. this._outputs = {};
  26659. }
  26660. setup() {
  26661. return this.getDefaultOutputNode();
  26662. }
  26663. getCacheKey( force ) {
  26664. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  26665. for ( const param in this.parameters ) {
  26666. values.push( this.parameters[ param ].getCacheKey( force ) );
  26667. }
  26668. return hashArray( values );
  26669. }
  26670. set needsUpdate( value ) {
  26671. if ( value === true ) this.dispose();
  26672. }
  26673. get needsUpdate() {
  26674. return this.source !== this._source;
  26675. }
  26676. /**
  26677. * Executes the `main` function of the script.
  26678. *
  26679. * @private
  26680. * @return {ScriptableNode} A reference to this node.
  26681. */
  26682. _exec() {
  26683. if ( this.codeNode === null ) return this;
  26684. if ( this._needsOutputUpdate === true ) {
  26685. this._value = this.call( 'main' );
  26686. this._needsOutputUpdate = false;
  26687. }
  26688. this._output.value = this._value;
  26689. return this;
  26690. }
  26691. /**
  26692. * Executes the refresh.
  26693. *
  26694. * @private
  26695. */
  26696. _refresh() {
  26697. this.needsUpdate = true;
  26698. this._exec();
  26699. this._output.refresh();
  26700. }
  26701. }
  26702. /**
  26703. * TSL function for creating a scriptable node.
  26704. *
  26705. * @tsl
  26706. * @function
  26707. * @param {CodeNode} [codeNode] - The code node.
  26708. * @param {?Object} [parameters={}] - The parameters definition.
  26709. * @returns {ScriptableNode}
  26710. */
  26711. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  26712. /**
  26713. * Returns a node that represents the `z` coordinate in view space
  26714. * for the current fragment. It's a different representation of the
  26715. * default depth value.
  26716. *
  26717. * This value can be part of a computation that defines how the fog
  26718. * density increases when moving away from the camera.
  26719. *
  26720. * @param {NodeBuilder} builder - The current node builder.
  26721. * @return {Node} The viewZ node.
  26722. */
  26723. function getViewZNode( builder ) {
  26724. let viewZ;
  26725. const getViewZ = builder.context.getViewZ;
  26726. if ( getViewZ !== undefined ) {
  26727. viewZ = getViewZ( this );
  26728. }
  26729. return ( viewZ || positionView.z ).negate();
  26730. }
  26731. /**
  26732. * Constructs a new range factor node.
  26733. *
  26734. * @tsl
  26735. * @function
  26736. * @param {Node} near - Defines the near value.
  26737. * @param {Node} far - Defines the far value.
  26738. */
  26739. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  26740. const viewZ = getViewZNode( builder );
  26741. return smoothstep( near, far, viewZ );
  26742. } );
  26743. /**
  26744. * Represents an exponential squared fog. This type of fog gives
  26745. * a clear view near the camera and a faster than exponentially
  26746. * densening fog farther from the camera.
  26747. *
  26748. * @tsl
  26749. * @function
  26750. * @param {Node} density - Defines the fog density.
  26751. */
  26752. const densityFogFactor = Fn( ( [ density ], builder ) => {
  26753. const viewZ = getViewZNode( builder );
  26754. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  26755. } );
  26756. /**
  26757. * This class can be used to configure a fog for the scene.
  26758. * Nodes of this type are assigned to `Scene.fogNode`.
  26759. *
  26760. * @tsl
  26761. * @function
  26762. * @param {Node} color - Defines the color of the fog.
  26763. * @param {Node} factor - Defines how the fog is factored in the scene.
  26764. */
  26765. const fog = Fn( ( [ color, factor ] ) => {
  26766. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  26767. } );
  26768. // Deprecated
  26769. /**
  26770. * @tsl
  26771. * @function
  26772. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  26773. *
  26774. * @param {Node} color
  26775. * @param {Node} near
  26776. * @param {Node} far
  26777. * @returns {Function}
  26778. */
  26779. function rangeFog( color, near, far ) { // @deprecated, r171
  26780. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  26781. return fog( color, rangeFogFactor( near, far ) );
  26782. }
  26783. /**
  26784. * @tsl
  26785. * @function
  26786. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  26787. *
  26788. * @param {Node} color
  26789. * @param {Node} density
  26790. * @returns {Function}
  26791. */
  26792. function densityFog( color, density ) { // @deprecated, r171
  26793. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  26794. return fog( color, densityFogFactor( density ) );
  26795. }
  26796. let min = null;
  26797. let max = null;
  26798. /**
  26799. * `RangeNode` generates random instanced attribute data in a defined range.
  26800. * An exemplary use case for this utility node is to generate random per-instance
  26801. * colors:
  26802. * ```js
  26803. * const material = new MeshBasicNodeMaterial();
  26804. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  26805. * const mesh = new InstancedMesh( geometry, material, count );
  26806. * ```
  26807. * @augments Node
  26808. */
  26809. class RangeNode extends Node {
  26810. static get type() {
  26811. return 'RangeNode';
  26812. }
  26813. /**
  26814. * Constructs a new range node.
  26815. *
  26816. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  26817. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  26818. */
  26819. constructor( minNode = float(), maxNode = float() ) {
  26820. super();
  26821. /**
  26822. * A node defining the lower bound of the range.
  26823. *
  26824. * @type {Node<any>}
  26825. * @default float()
  26826. */
  26827. this.minNode = minNode;
  26828. /**
  26829. * A node defining the upper bound of the range.
  26830. *
  26831. * @type {Node<any>}
  26832. * @default float()
  26833. */
  26834. this.maxNode = maxNode;
  26835. }
  26836. /**
  26837. * Returns the vector length which is computed based on the range definition.
  26838. *
  26839. * @param {NodeBuilder} builder - The current node builder.
  26840. * @return {number} The vector length.
  26841. */
  26842. getVectorLength( builder ) {
  26843. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  26844. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  26845. return minLength > maxLength ? minLength : maxLength;
  26846. }
  26847. /**
  26848. * This method is overwritten since the node type is inferred from range definition.
  26849. *
  26850. * @param {NodeBuilder} builder - The current node builder.
  26851. * @return {string} The node type.
  26852. */
  26853. getNodeType( builder ) {
  26854. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  26855. }
  26856. setup( builder ) {
  26857. const object = builder.object;
  26858. let output = null;
  26859. if ( object.count > 1 ) {
  26860. const minValue = this.minNode.value;
  26861. const maxValue = this.maxNode.value;
  26862. const minLength = builder.getTypeLength( getValueType( minValue ) );
  26863. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  26864. min = min || new Vector4();
  26865. max = max || new Vector4();
  26866. min.setScalar( 0 );
  26867. max.setScalar( 0 );
  26868. if ( minLength === 1 ) min.setScalar( minValue );
  26869. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  26870. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  26871. if ( maxLength === 1 ) max.setScalar( maxValue );
  26872. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  26873. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  26874. const stride = 4;
  26875. const length = stride * object.count;
  26876. const array = new Float32Array( length );
  26877. for ( let i = 0; i < length; i ++ ) {
  26878. const index = i % stride;
  26879. const minElementValue = min.getComponent( index );
  26880. const maxElementValue = max.getComponent( index );
  26881. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  26882. }
  26883. const nodeType = this.getNodeType( builder );
  26884. if ( object.count <= 4096 ) {
  26885. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  26886. } else {
  26887. // TODO: Improve anonymous buffer attribute creation removing this part
  26888. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  26889. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  26890. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  26891. }
  26892. } else {
  26893. output = float( 0 );
  26894. }
  26895. return output;
  26896. }
  26897. }
  26898. /**
  26899. * TSL function for creating a range node.
  26900. *
  26901. * @tsl
  26902. * @function
  26903. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  26904. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  26905. * @returns {RangeNode}
  26906. */
  26907. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  26908. /**
  26909. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  26910. * about the currently running dispatch and/or the device it is running on.
  26911. *
  26912. * This node can only be used with a WebGPU backend.
  26913. *
  26914. * @augments Node
  26915. */
  26916. class ComputeBuiltinNode extends Node {
  26917. static get type() {
  26918. return 'ComputeBuiltinNode';
  26919. }
  26920. /**
  26921. * Constructs a new compute builtin node.
  26922. *
  26923. * @param {string} builtinName - The built-in name.
  26924. * @param {string} nodeType - The node type.
  26925. */
  26926. constructor( builtinName, nodeType ) {
  26927. super( nodeType );
  26928. /**
  26929. * The built-in name.
  26930. *
  26931. * @private
  26932. * @type {string}
  26933. */
  26934. this._builtinName = builtinName;
  26935. }
  26936. /**
  26937. * This method is overwritten since hash is derived from the built-in name.
  26938. *
  26939. * @param {NodeBuilder} builder - The current node builder.
  26940. * @return {string} The hash.
  26941. */
  26942. getHash( builder ) {
  26943. return this.getBuiltinName( builder );
  26944. }
  26945. /**
  26946. * This method is overwritten since the node type is simply derived from `nodeType`..
  26947. *
  26948. * @param {NodeBuilder} builder - The current node builder.
  26949. * @return {string} The node type.
  26950. */
  26951. getNodeType( /*builder*/ ) {
  26952. return this.nodeType;
  26953. }
  26954. /**
  26955. * Sets the builtin name.
  26956. *
  26957. * @param {string} builtinName - The built-in name.
  26958. * @return {ComputeBuiltinNode} A reference to this node.
  26959. */
  26960. setBuiltinName( builtinName ) {
  26961. this._builtinName = builtinName;
  26962. return this;
  26963. }
  26964. /**
  26965. * Returns the builtin name.
  26966. *
  26967. * @param {NodeBuilder} builder - The current node builder.
  26968. * @return {string} The builtin name.
  26969. */
  26970. getBuiltinName( /*builder*/ ) {
  26971. return this._builtinName;
  26972. }
  26973. /**
  26974. * Whether the current node builder has the builtin or not.
  26975. *
  26976. * @param {NodeBuilder} builder - The current node builder.
  26977. * @return {boolean} Whether the builder has the builtin or not.
  26978. */
  26979. hasBuiltin( builder ) {
  26980. return builder.hasBuiltin( this._builtinName );
  26981. }
  26982. generate( builder, output ) {
  26983. const builtinName = this.getBuiltinName( builder );
  26984. const nodeType = this.getNodeType( builder );
  26985. if ( builder.shaderStage === 'compute' ) {
  26986. return builder.format( builtinName, nodeType, output );
  26987. } else {
  26988. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  26989. return builder.generateConst( nodeType );
  26990. }
  26991. }
  26992. serialize( data ) {
  26993. super.serialize( data );
  26994. data.global = this.global;
  26995. data._builtinName = this._builtinName;
  26996. }
  26997. deserialize( data ) {
  26998. super.deserialize( data );
  26999. this.global = data.global;
  27000. this._builtinName = data._builtinName;
  27001. }
  27002. }
  27003. /**
  27004. * TSL function for creating a compute builtin node.
  27005. *
  27006. * @tsl
  27007. * @function
  27008. * @param {string} name - The built-in name.
  27009. * @param {string} nodeType - The node type.
  27010. * @returns {ComputeBuiltinNode}
  27011. */
  27012. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  27013. /**
  27014. * Represents the number of workgroups dispatched by the compute shader.
  27015. * ```js
  27016. * // Run 512 invocations/threads with a workgroup size of 128.
  27017. * const computeFn = Fn(() => {
  27018. *
  27019. * // numWorkgroups.x = 4
  27020. * storageBuffer.element(0).assign(numWorkgroups.x)
  27021. *
  27022. * })().compute(512, [128]);
  27023. *
  27024. * // Run 512 invocations/threads with the default workgroup size of 64.
  27025. * const computeFn = Fn(() => {
  27026. *
  27027. * // numWorkgroups.x = 8
  27028. * storageBuffer.element(0).assign(numWorkgroups.x)
  27029. *
  27030. * })().compute(512);
  27031. * ```
  27032. *
  27033. * @tsl
  27034. * @type {ComputeBuiltinNode<uvec3>}
  27035. */
  27036. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  27037. /**
  27038. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  27039. * ```js
  27040. * // Execute 12 compute threads with a workgroup size of 3.
  27041. * const computeFn = Fn( () => {
  27042. *
  27043. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  27044. *
  27045. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  27046. *
  27047. * } ).Else( () => {
  27048. *
  27049. * storageBuffer.element( instanceIndex ).assign( 0 );
  27050. *
  27051. * } );
  27052. *
  27053. * } )().compute( 12, [ 3 ] );
  27054. *
  27055. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  27056. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  27057. * ```
  27058. *
  27059. * @tsl
  27060. * @type {ComputeBuiltinNode<uvec3>}
  27061. */
  27062. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  27063. /**
  27064. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  27065. *
  27066. * @tsl
  27067. * @type {ComputeBuiltinNode<uvec3>}
  27068. */
  27069. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  27070. /**
  27071. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  27072. *
  27073. * @tsl
  27074. * @type {ComputeBuiltinNode<uvec3>}
  27075. */
  27076. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  27077. /**
  27078. * A device dependent variable that exposes the size of the current invocation's subgroup.
  27079. *
  27080. * @tsl
  27081. * @type {ComputeBuiltinNode<uint>}
  27082. */
  27083. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  27084. /**
  27085. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  27086. *
  27087. * This node can only be used with a WebGPU backend.
  27088. *
  27089. * @augments Node
  27090. */
  27091. class BarrierNode extends Node {
  27092. /**
  27093. * Constructs a new barrier node.
  27094. *
  27095. * @param {string} scope - The scope defines the behavior of the node.
  27096. */
  27097. constructor( scope ) {
  27098. super();
  27099. this.scope = scope;
  27100. }
  27101. generate( builder ) {
  27102. const { scope } = this;
  27103. const { renderer } = builder;
  27104. if ( renderer.backend.isWebGLBackend === true ) {
  27105. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  27106. } else {
  27107. builder.addLineFlowCode( `${scope}Barrier()`, this );
  27108. }
  27109. }
  27110. }
  27111. /**
  27112. * TSL function for creating a barrier node.
  27113. *
  27114. * @tsl
  27115. * @function
  27116. * @param {string} scope - The scope defines the behavior of the node..
  27117. * @returns {BarrierNode}
  27118. */
  27119. const barrier = nodeProxy( BarrierNode );
  27120. /**
  27121. * TSL function for creating a workgroup barrier. All compute shader
  27122. * invocations must wait for each invocation within a workgroup to
  27123. * complete before the barrier can be surpassed.
  27124. *
  27125. * @tsl
  27126. * @function
  27127. * @returns {BarrierNode}
  27128. */
  27129. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  27130. /**
  27131. * TSL function for creating a storage barrier. All invocations must
  27132. * wait for each access to variables within the 'storage' address space
  27133. * to complete before the barrier can be passed.
  27134. *
  27135. * @tsl
  27136. * @function
  27137. * @returns {BarrierNode}
  27138. */
  27139. const storageBarrier = () => barrier( 'storage' ).toStack();
  27140. /**
  27141. * TSL function for creating a texture barrier. All invocations must
  27142. * wait for each access to variables within the 'texture' address space
  27143. * to complete before the barrier can be passed.
  27144. *
  27145. * @tsl
  27146. * @function
  27147. * @returns {BarrierNode}
  27148. */
  27149. const textureBarrier = () => barrier( 'texture' ).toStack();
  27150. /**
  27151. * Represents an element of a 'workgroup' scoped buffer.
  27152. *
  27153. * @augments ArrayElementNode
  27154. */
  27155. class WorkgroupInfoElementNode extends ArrayElementNode {
  27156. /**
  27157. * Constructs a new workgroup info element node.
  27158. *
  27159. * @param {Node} workgroupInfoNode - The workgroup info node.
  27160. * @param {Node} indexNode - The index node that defines the element access.
  27161. */
  27162. constructor( workgroupInfoNode, indexNode ) {
  27163. super( workgroupInfoNode, indexNode );
  27164. /**
  27165. * This flag can be used for type testing.
  27166. *
  27167. * @type {boolean}
  27168. * @readonly
  27169. * @default true
  27170. */
  27171. this.isWorkgroupInfoElementNode = true;
  27172. }
  27173. generate( builder, output ) {
  27174. let snippet;
  27175. const isAssignContext = builder.context.assign;
  27176. snippet = super.generate( builder );
  27177. if ( isAssignContext !== true ) {
  27178. const type = this.getNodeType( builder );
  27179. snippet = builder.format( snippet, type, output );
  27180. }
  27181. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  27182. return snippet;
  27183. }
  27184. }
  27185. /**
  27186. * A node allowing the user to create a 'workgroup' scoped buffer within the
  27187. * context of a compute shader. Typically, workgroup scoped buffers are
  27188. * created to hold data that is transferred from a global storage scope into
  27189. * a local workgroup scope. For invocations within a workgroup, data
  27190. * access speeds on 'workgroup' scoped buffers can be significantly faster
  27191. * than similar access operations on globally accessible storage buffers.
  27192. *
  27193. * This node can only be used with a WebGPU backend.
  27194. *
  27195. * @augments Node
  27196. */
  27197. class WorkgroupInfoNode extends Node {
  27198. /**
  27199. * Constructs a new buffer scoped to type scope.
  27200. *
  27201. * @param {string} scope - TODO.
  27202. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  27203. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  27204. */
  27205. constructor( scope, bufferType, bufferCount = 0 ) {
  27206. super( bufferType );
  27207. /**
  27208. * The buffer type.
  27209. *
  27210. * @type {string}
  27211. */
  27212. this.bufferType = bufferType;
  27213. /**
  27214. * The buffer count.
  27215. *
  27216. * @type {number}
  27217. * @default 0
  27218. */
  27219. this.bufferCount = bufferCount;
  27220. /**
  27221. * This flag can be used for type testing.
  27222. *
  27223. * @type {boolean}
  27224. * @readonly
  27225. * @default true
  27226. */
  27227. this.isWorkgroupInfoNode = true;
  27228. /**
  27229. * The data type of the array buffer.
  27230. *
  27231. * @type {string}
  27232. */
  27233. this.elementType = bufferType;
  27234. /**
  27235. * TODO.
  27236. *
  27237. * @type {string}
  27238. */
  27239. this.scope = scope;
  27240. /**
  27241. * The name of the workgroup scoped buffer.
  27242. *
  27243. * @type {string}
  27244. * @default ''
  27245. */
  27246. this.name = '';
  27247. }
  27248. /**
  27249. * Sets the name of this node.
  27250. *
  27251. * @param {string} name - The name to set.
  27252. * @return {WorkgroupInfoNode} A reference to this node.
  27253. */
  27254. setName( name ) {
  27255. this.name = name;
  27256. return this;
  27257. }
  27258. /**
  27259. * Sets the name/label of this node.
  27260. *
  27261. * @deprecated
  27262. * @param {string} name - The name to set.
  27263. * @return {WorkgroupInfoNode} A reference to this node.
  27264. */
  27265. label( name ) {
  27266. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  27267. return this.setName( name );
  27268. }
  27269. /**
  27270. * Sets the scope of this node.
  27271. *
  27272. * @param {string} scope - The scope to set.
  27273. * @return {WorkgroupInfoNode} A reference to this node.
  27274. */
  27275. setScope( scope ) {
  27276. this.scope = scope;
  27277. return this;
  27278. }
  27279. /**
  27280. * The data type of the array buffer.
  27281. *
  27282. * @return {string} The element type.
  27283. */
  27284. getElementType() {
  27285. return this.elementType;
  27286. }
  27287. /**
  27288. * Overwrites the default implementation since the input type
  27289. * is inferred from the scope.
  27290. *
  27291. * @param {NodeBuilder} builder - The current node builder.
  27292. * @return {string} The input type.
  27293. */
  27294. getInputType( /*builder*/ ) {
  27295. return `${this.scope}Array`;
  27296. }
  27297. /**
  27298. * This method can be used to access elements via an index node.
  27299. *
  27300. * @param {IndexNode} indexNode - indexNode.
  27301. * @return {WorkgroupInfoElementNode} A reference to an element.
  27302. */
  27303. element( indexNode ) {
  27304. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  27305. }
  27306. generate( builder ) {
  27307. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  27308. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  27309. }
  27310. }
  27311. /**
  27312. * TSL function for creating a workgroup info node.
  27313. * Creates a new 'workgroup' scoped array buffer.
  27314. *
  27315. * @tsl
  27316. * @function
  27317. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  27318. * @param {number} [count=0] - The number of elements in the buffer.
  27319. * @returns {WorkgroupInfoNode}
  27320. */
  27321. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  27322. /**
  27323. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  27324. * within a shader. In an atomic function, any modification to an atomic variable will
  27325. * occur as an indivisible step with a defined order relative to other modifications.
  27326. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  27327. * atomic operations will not interfere with each other.
  27328. *
  27329. * This node can only be used with a WebGPU backend.
  27330. *
  27331. * @augments Node
  27332. */
  27333. class AtomicFunctionNode extends Node {
  27334. static get type() {
  27335. return 'AtomicFunctionNode';
  27336. }
  27337. /**
  27338. * Constructs a new atomic function node.
  27339. *
  27340. * @param {string} method - The signature of the atomic function to construct.
  27341. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27342. * @param {Node} valueNode - The value that mutates the atomic variable.
  27343. */
  27344. constructor( method, pointerNode, valueNode ) {
  27345. super( 'uint' );
  27346. /**
  27347. * The signature of the atomic function to construct.
  27348. *
  27349. * @type {string}
  27350. */
  27351. this.method = method;
  27352. /**
  27353. * An atomic variable or element of an atomic buffer.
  27354. *
  27355. * @type {Node}
  27356. */
  27357. this.pointerNode = pointerNode;
  27358. /**
  27359. * A value that modifies the atomic variable.
  27360. *
  27361. * @type {Node}
  27362. */
  27363. this.valueNode = valueNode;
  27364. /**
  27365. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  27366. *
  27367. * @type {boolean}
  27368. * @default true
  27369. */
  27370. this.parents = true;
  27371. }
  27372. /**
  27373. * Overwrites the default implementation to return the type of
  27374. * the pointer node.
  27375. *
  27376. * @param {NodeBuilder} builder - The current node builder.
  27377. * @return {string} The input type.
  27378. */
  27379. getInputType( builder ) {
  27380. return this.pointerNode.getNodeType( builder );
  27381. }
  27382. /**
  27383. * Overwritten since the node type is inferred from the input type.
  27384. *
  27385. * @param {NodeBuilder} builder - The current node builder.
  27386. * @return {string} The node type.
  27387. */
  27388. getNodeType( builder ) {
  27389. return this.getInputType( builder );
  27390. }
  27391. generate( builder ) {
  27392. const properties = builder.getNodeProperties( this );
  27393. const parents = properties.parents;
  27394. const method = this.method;
  27395. const type = this.getNodeType( builder );
  27396. const inputType = this.getInputType( builder );
  27397. const a = this.pointerNode;
  27398. const b = this.valueNode;
  27399. const params = [];
  27400. params.push( `&${ a.build( builder, inputType ) }` );
  27401. if ( b !== null ) {
  27402. params.push( b.build( builder, inputType ) );
  27403. }
  27404. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  27405. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  27406. if ( isVoid ) {
  27407. builder.addLineFlowCode( methodSnippet, this );
  27408. } else {
  27409. if ( properties.constNode === undefined ) {
  27410. properties.constNode = expression( methodSnippet, type ).toConst();
  27411. }
  27412. return properties.constNode.build( builder );
  27413. }
  27414. }
  27415. }
  27416. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  27417. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  27418. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  27419. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  27420. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  27421. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  27422. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  27423. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  27424. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  27425. /**
  27426. * TSL function for creating an atomic function node.
  27427. *
  27428. * @tsl
  27429. * @function
  27430. * @param {string} method - The signature of the atomic function to construct.
  27431. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27432. * @param {Node} valueNode - The value that mutates the atomic variable.
  27433. * @returns {AtomicFunctionNode}
  27434. */
  27435. const atomicNode = nodeProxy( AtomicFunctionNode );
  27436. /**
  27437. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  27438. *
  27439. * @tsl
  27440. * @function
  27441. * @param {string} method - The signature of the atomic function to construct.
  27442. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27443. * @param {Node} valueNode - The value that mutates the atomic variable.
  27444. * @returns {AtomicFunctionNode}
  27445. */
  27446. const atomicFunc = ( method, pointerNode, valueNode ) => {
  27447. return atomicNode( method, pointerNode, valueNode ).toStack();
  27448. };
  27449. /**
  27450. * Loads the value stored in the atomic variable.
  27451. *
  27452. * @tsl
  27453. * @function
  27454. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27455. * @returns {AtomicFunctionNode}
  27456. */
  27457. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  27458. /**
  27459. * Stores a value in the atomic variable.
  27460. *
  27461. * @tsl
  27462. * @function
  27463. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27464. * @param {Node} valueNode - The value that mutates the atomic variable.
  27465. * @returns {AtomicFunctionNode}
  27466. */
  27467. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  27468. /**
  27469. * Increments the value stored in the atomic variable.
  27470. *
  27471. * @tsl
  27472. * @function
  27473. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27474. * @param {Node} valueNode - The value that mutates the atomic variable.
  27475. * @returns {AtomicFunctionNode}
  27476. */
  27477. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  27478. /**
  27479. * Decrements the value stored in the atomic variable.
  27480. *
  27481. * @tsl
  27482. * @function
  27483. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27484. * @param {Node} valueNode - The value that mutates the atomic variable.
  27485. * @returns {AtomicFunctionNode}
  27486. */
  27487. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  27488. /**
  27489. * Stores in an atomic variable the maximum between its current value and a parameter.
  27490. *
  27491. * @tsl
  27492. * @function
  27493. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27494. * @param {Node} valueNode - The value that mutates the atomic variable.
  27495. * @returns {AtomicFunctionNode}
  27496. */
  27497. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  27498. /**
  27499. * Stores in an atomic variable the minimum between its current value and a parameter.
  27500. *
  27501. * @tsl
  27502. * @function
  27503. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27504. * @param {Node} valueNode - The value that mutates the atomic variable.
  27505. * @returns {AtomicFunctionNode}
  27506. */
  27507. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  27508. /**
  27509. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  27510. *
  27511. * @tsl
  27512. * @function
  27513. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27514. * @param {Node} valueNode - The value that mutates the atomic variable.
  27515. * @returns {AtomicFunctionNode}
  27516. */
  27517. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  27518. /**
  27519. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  27520. *
  27521. * @tsl
  27522. * @function
  27523. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27524. * @param {Node} valueNode - The value that mutates the atomic variable.
  27525. * @returns {AtomicFunctionNode}
  27526. */
  27527. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  27528. /**
  27529. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  27530. *
  27531. * @tsl
  27532. * @function
  27533. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27534. * @param {Node} valueNode - The value that mutates the atomic variable.
  27535. * @returns {AtomicFunctionNode}
  27536. */
  27537. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  27538. let uniformsLib;
  27539. function getLightData( light ) {
  27540. uniformsLib = uniformsLib || new WeakMap();
  27541. let uniforms = uniformsLib.get( light );
  27542. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  27543. return uniforms;
  27544. }
  27545. /**
  27546. * TSL function for getting a shadow matrix uniform node for the given light.
  27547. *
  27548. * @tsl
  27549. * @function
  27550. * @param {Light} light -The light source.
  27551. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  27552. */
  27553. function lightShadowMatrix( light ) {
  27554. const data = getLightData( light );
  27555. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  27556. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  27557. light.shadow.updateMatrices( light );
  27558. }
  27559. return light.shadow.matrix;
  27560. } ) );
  27561. }
  27562. /**
  27563. * TSL function for getting projected uv coordinates for the given light.
  27564. * Relevant when using maps with spot lights.
  27565. *
  27566. * @tsl
  27567. * @function
  27568. * @param {Light} light -The light source.
  27569. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  27570. * @returns {Node<vec3>} The projected uvs.
  27571. */
  27572. function lightProjectionUV( light, position = positionWorld ) {
  27573. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  27574. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  27575. return projectionUV;
  27576. }
  27577. /**
  27578. * TSL function for getting the position in world space for the given light.
  27579. *
  27580. * @tsl
  27581. * @function
  27582. * @param {Light} light -The light source.
  27583. * @returns {UniformNode<vec3>} The light's position in world space.
  27584. */
  27585. function lightPosition( light ) {
  27586. const data = getLightData( light );
  27587. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  27588. }
  27589. /**
  27590. * TSL function for getting the light target position in world space for the given light.
  27591. *
  27592. * @tsl
  27593. * @function
  27594. * @param {Light} light -The light source.
  27595. * @returns {UniformNode<vec3>} The light target position in world space.
  27596. */
  27597. function lightTargetPosition( light ) {
  27598. const data = getLightData( light );
  27599. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  27600. }
  27601. /**
  27602. * TSL function for getting the position in view space for the given light.
  27603. *
  27604. * @tsl
  27605. * @function
  27606. * @param {Light} light - The light source.
  27607. * @returns {UniformNode<vec3>} The light's position in view space.
  27608. */
  27609. function lightViewPosition( light ) {
  27610. const data = getLightData( light );
  27611. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  27612. self.value = self.value || new Vector3();
  27613. self.value.setFromMatrixPosition( light.matrixWorld );
  27614. self.value.applyMatrix4( camera.matrixWorldInverse );
  27615. } ) );
  27616. }
  27617. /**
  27618. * TSL function for getting the light target direction for the given light.
  27619. *
  27620. * @tsl
  27621. * @function
  27622. * @param {Light} light -The light source.
  27623. * @returns {Node<vec3>} The light's target direction.
  27624. */
  27625. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  27626. const sortLights = ( lights ) => {
  27627. return lights.sort( ( a, b ) => a.id - b.id );
  27628. };
  27629. const getLightNodeById = ( id, lightNodes ) => {
  27630. for ( const lightNode of lightNodes ) {
  27631. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  27632. return lightNode;
  27633. }
  27634. }
  27635. return null;
  27636. };
  27637. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  27638. const _hashData = [];
  27639. /**
  27640. * This node represents the scene's lighting and manages the lighting model's life cycle
  27641. * for the current build 3D object. It is responsible for computing the total outgoing
  27642. * light in a given lighting context.
  27643. *
  27644. * @augments Node
  27645. */
  27646. class LightsNode extends Node {
  27647. static get type() {
  27648. return 'LightsNode';
  27649. }
  27650. /**
  27651. * Constructs a new lights node.
  27652. */
  27653. constructor() {
  27654. super( 'vec3' );
  27655. /**
  27656. * A node representing the total diffuse light.
  27657. *
  27658. * @type {Node<vec3>}
  27659. */
  27660. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  27661. /**
  27662. * A node representing the total specular light.
  27663. *
  27664. * @type {Node<vec3>}
  27665. */
  27666. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  27667. /**
  27668. * A node representing the outgoing light.
  27669. *
  27670. * @type {Node<vec3>}
  27671. */
  27672. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  27673. /**
  27674. * An array representing the lights in the scene.
  27675. *
  27676. * @private
  27677. * @type {Array<Light>}
  27678. */
  27679. this._lights = [];
  27680. /**
  27681. * For each light in the scene, this node will create a
  27682. * corresponding light node.
  27683. *
  27684. * @private
  27685. * @type {?Array<LightingNode>}
  27686. * @default null
  27687. */
  27688. this._lightNodes = null;
  27689. /**
  27690. * A hash for identifying the current light nodes setup.
  27691. *
  27692. * @private
  27693. * @type {?string}
  27694. * @default null
  27695. */
  27696. this._lightNodesHash = null;
  27697. /**
  27698. * `LightsNode` sets this property to `true` by default.
  27699. *
  27700. * @type {boolean}
  27701. * @default true
  27702. */
  27703. this.global = true;
  27704. }
  27705. /**
  27706. * Overwrites the default {@link Node#customCacheKey} implementation by including
  27707. * light data into the cache key.
  27708. *
  27709. * @return {number} The custom cache key.
  27710. */
  27711. customCacheKey() {
  27712. const lights = this._lights;
  27713. for ( let i = 0; i < lights.length; i ++ ) {
  27714. const light = lights[ i ];
  27715. _hashData.push( light.id );
  27716. _hashData.push( light.castShadow ? 1 : 0 );
  27717. if ( light.isSpotLight === true ) {
  27718. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  27719. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  27720. _hashData.push( hashMap, hashColorNode );
  27721. }
  27722. }
  27723. const cacheKey = hashArray( _hashData );
  27724. _hashData.length = 0;
  27725. return cacheKey;
  27726. }
  27727. /**
  27728. * Computes a hash value for identifying the current light nodes setup.
  27729. *
  27730. * @param {NodeBuilder} builder - A reference to the current node builder.
  27731. * @return {string} The computed hash.
  27732. */
  27733. getHash( builder ) {
  27734. if ( this._lightNodesHash === null ) {
  27735. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  27736. const hash = [];
  27737. for ( const lightNode of this._lightNodes ) {
  27738. hash.push( lightNode.getSelf().getHash() );
  27739. }
  27740. this._lightNodesHash = 'lights-' + hash.join( ',' );
  27741. }
  27742. return this._lightNodesHash;
  27743. }
  27744. analyze( builder ) {
  27745. const properties = builder.getNodeProperties( this );
  27746. for ( const node of properties.nodes ) {
  27747. node.build( builder );
  27748. }
  27749. properties.outputNode.build( builder );
  27750. }
  27751. /**
  27752. * Creates lighting nodes for each scene light. This makes it possible to further
  27753. * process lights in the node system.
  27754. *
  27755. * @param {NodeBuilder} builder - A reference to the current node builder.
  27756. */
  27757. setupLightsNode( builder ) {
  27758. const lightNodes = [];
  27759. const previousLightNodes = this._lightNodes;
  27760. const lights = sortLights( this._lights );
  27761. const nodeLibrary = builder.renderer.library;
  27762. for ( const light of lights ) {
  27763. if ( light.isNode ) {
  27764. lightNodes.push( nodeObject( light ) );
  27765. } else {
  27766. let lightNode = null;
  27767. if ( previousLightNodes !== null ) {
  27768. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  27769. }
  27770. if ( lightNode === null ) {
  27771. // find the corresponding node type for a given light
  27772. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  27773. if ( lightNodeClass === null ) {
  27774. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  27775. continue;
  27776. }
  27777. let lightNode = null;
  27778. if ( ! _lightsNodeRef.has( light ) ) {
  27779. lightNode = nodeObject( new lightNodeClass( light ) );
  27780. _lightsNodeRef.set( light, lightNode );
  27781. } else {
  27782. lightNode = _lightsNodeRef.get( light );
  27783. }
  27784. lightNodes.push( lightNode );
  27785. }
  27786. }
  27787. }
  27788. this._lightNodes = lightNodes;
  27789. }
  27790. /**
  27791. * Sets up a direct light in the lighting model.
  27792. *
  27793. * @param {Object} builder - The builder object containing the context and stack.
  27794. * @param {Object} lightNode - The light node.
  27795. * @param {Object} lightData - The light object containing color and direction properties.
  27796. */
  27797. setupDirectLight( builder, lightNode, lightData ) {
  27798. const { lightingModel, reflectedLight } = builder.context;
  27799. lightingModel.direct( {
  27800. ...lightData,
  27801. lightNode,
  27802. reflectedLight
  27803. }, builder );
  27804. }
  27805. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  27806. const { lightingModel, reflectedLight } = builder.context;
  27807. lightingModel.directRectArea( {
  27808. ...lightData,
  27809. lightNode,
  27810. reflectedLight
  27811. }, builder );
  27812. }
  27813. /**
  27814. * Setups the internal lights by building all respective
  27815. * light nodes.
  27816. *
  27817. * @param {NodeBuilder} builder - A reference to the current node builder.
  27818. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  27819. */
  27820. setupLights( builder, lightNodes ) {
  27821. for ( const lightNode of lightNodes ) {
  27822. lightNode.build( builder );
  27823. }
  27824. }
  27825. getLightNodes( builder ) {
  27826. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  27827. return this._lightNodes;
  27828. }
  27829. /**
  27830. * The implementation makes sure that for each light in the scene
  27831. * there is a corresponding light node. By building the light nodes
  27832. * and evaluating the lighting model the outgoing light is computed.
  27833. *
  27834. * @param {NodeBuilder} builder - A reference to the current node builder.
  27835. * @return {Node<vec3>} A node representing the outgoing light.
  27836. */
  27837. setup( builder ) {
  27838. const currentLightsNode = builder.lightsNode;
  27839. builder.lightsNode = this;
  27840. //
  27841. let outgoingLightNode = this.outgoingLightNode;
  27842. const context = builder.context;
  27843. const lightingModel = context.lightingModel;
  27844. const properties = builder.getNodeProperties( this );
  27845. if ( lightingModel ) {
  27846. const { totalDiffuseNode, totalSpecularNode } = this;
  27847. context.outgoingLight = outgoingLightNode;
  27848. const stack = builder.addStack();
  27849. //
  27850. properties.nodes = stack.nodes;
  27851. //
  27852. lightingModel.start( builder );
  27853. //
  27854. const { backdrop, backdropAlpha } = context;
  27855. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  27856. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  27857. if ( backdrop !== null ) {
  27858. if ( backdropAlpha !== null ) {
  27859. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  27860. } else {
  27861. totalDiffuse = vec3( backdrop );
  27862. }
  27863. context.material.transparent = true;
  27864. }
  27865. totalDiffuseNode.assign( totalDiffuse );
  27866. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  27867. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  27868. //
  27869. lightingModel.finish( builder );
  27870. //
  27871. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  27872. } else {
  27873. properties.nodes = [];
  27874. }
  27875. //
  27876. builder.lightsNode = currentLightsNode;
  27877. return outgoingLightNode;
  27878. }
  27879. /**
  27880. * Configures this node with an array of lights.
  27881. *
  27882. * @param {Array<Light>} lights - An array of lights.
  27883. * @return {LightsNode} A reference to this node.
  27884. */
  27885. setLights( lights ) {
  27886. this._lights = lights;
  27887. this._lightNodes = null;
  27888. this._lightNodesHash = null;
  27889. return this;
  27890. }
  27891. /**
  27892. * Returns an array of the scene's lights.
  27893. *
  27894. * @return {Array<Light>} The scene's lights.
  27895. */
  27896. getLights() {
  27897. return this._lights;
  27898. }
  27899. /**
  27900. * Whether the scene has lights or not.
  27901. *
  27902. * @type {boolean}
  27903. */
  27904. get hasLights() {
  27905. return this._lights.length > 0;
  27906. }
  27907. }
  27908. /**
  27909. * TSL function for creating an instance of `LightsNode` and configuring
  27910. * it with the given array of lights.
  27911. *
  27912. * @tsl
  27913. * @function
  27914. * @param {Array<Light>} lights - An array of lights.
  27915. * @return {LightsNode} The created lights node.
  27916. */
  27917. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  27918. /**
  27919. * Base class for all shadow nodes.
  27920. *
  27921. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  27922. * Lighting nodes might share the same shadow node type or use specific ones depending on
  27923. * their requirements.
  27924. *
  27925. * @augments Node
  27926. */
  27927. class ShadowBaseNode extends Node {
  27928. static get type() {
  27929. return 'ShadowBaseNode';
  27930. }
  27931. /**
  27932. * Constructs a new shadow base node.
  27933. *
  27934. * @param {Light} light - The shadow casting light.
  27935. */
  27936. constructor( light ) {
  27937. super();
  27938. /**
  27939. * The shadow casting light.
  27940. *
  27941. * @type {Light}
  27942. */
  27943. this.light = light;
  27944. /**
  27945. * Overwritten since shadows are updated by default per render.
  27946. *
  27947. * @type {string}
  27948. * @default 'render'
  27949. */
  27950. this.updateBeforeType = NodeUpdateType.RENDER;
  27951. /**
  27952. * This flag can be used for type testing.
  27953. *
  27954. * @type {boolean}
  27955. * @readonly
  27956. * @default true
  27957. */
  27958. this.isShadowBaseNode = true;
  27959. }
  27960. /**
  27961. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  27962. *
  27963. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  27964. */
  27965. setupShadowPosition( { context, material } ) {
  27966. // Use assign inside an Fn()
  27967. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  27968. }
  27969. }
  27970. /**
  27971. * TSL object that represents the vertex position in world space during the shadow pass.
  27972. *
  27973. * @tsl
  27974. * @type {Node<vec3>}
  27975. */
  27976. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  27977. /**
  27978. * Saves the state of the given renderer and stores it into the given state object.
  27979. *
  27980. * If not state object is provided, the function creates one.
  27981. *
  27982. * @function
  27983. * @param {Renderer} renderer - The renderer.
  27984. * @param {Object} [state={}] - The state.
  27985. * @return {Object} The state.
  27986. */
  27987. function saveRendererState( renderer, state = {} ) {
  27988. state.toneMapping = renderer.toneMapping;
  27989. state.toneMappingExposure = renderer.toneMappingExposure;
  27990. state.outputColorSpace = renderer.outputColorSpace;
  27991. state.renderTarget = renderer.getRenderTarget();
  27992. state.activeCubeFace = renderer.getActiveCubeFace();
  27993. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  27994. state.renderObjectFunction = renderer.getRenderObjectFunction();
  27995. state.pixelRatio = renderer.getPixelRatio();
  27996. state.mrt = renderer.getMRT();
  27997. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  27998. state.clearAlpha = renderer.getClearAlpha();
  27999. state.autoClear = renderer.autoClear;
  28000. state.scissorTest = renderer.getScissorTest();
  28001. return state;
  28002. }
  28003. /**
  28004. * Saves the state of the given renderer and stores it into the given state object.
  28005. * Besides, the function also resets the state of the renderer to its default values.
  28006. *
  28007. * If not state object is provided, the function creates one.
  28008. *
  28009. * @function
  28010. * @param {Renderer} renderer - The renderer.
  28011. * @param {Object} [state={}] - The state.
  28012. * @return {Object} The state.
  28013. */
  28014. function resetRendererState( renderer, state ) {
  28015. state = saveRendererState( renderer, state );
  28016. renderer.setMRT( null );
  28017. renderer.setRenderObjectFunction( null );
  28018. renderer.setClearColor( 0x000000, 1 );
  28019. renderer.autoClear = true;
  28020. return state;
  28021. }
  28022. /**
  28023. * Restores the state of the given renderer from the given state object.
  28024. *
  28025. * @function
  28026. * @param {Renderer} renderer - The renderer.
  28027. * @param {Object} state - The state to restore.
  28028. */
  28029. function restoreRendererState( renderer, state ) {
  28030. renderer.toneMapping = state.toneMapping;
  28031. renderer.toneMappingExposure = state.toneMappingExposure;
  28032. renderer.outputColorSpace = state.outputColorSpace;
  28033. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  28034. renderer.setRenderObjectFunction( state.renderObjectFunction );
  28035. renderer.setPixelRatio( state.pixelRatio );
  28036. renderer.setMRT( state.mrt );
  28037. renderer.setClearColor( state.clearColor, state.clearAlpha );
  28038. renderer.autoClear = state.autoClear;
  28039. renderer.setScissorTest( state.scissorTest );
  28040. }
  28041. /**
  28042. * Saves the state of the given scene and stores it into the given state object.
  28043. *
  28044. * If not state object is provided, the function creates one.
  28045. *
  28046. * @function
  28047. * @param {Scene} scene - The scene.
  28048. * @param {Object} [state={}] - The state.
  28049. * @return {Object} The state.
  28050. */
  28051. function saveSceneState( scene, state = {} ) {
  28052. state.background = scene.background;
  28053. state.backgroundNode = scene.backgroundNode;
  28054. state.overrideMaterial = scene.overrideMaterial;
  28055. return state;
  28056. }
  28057. /**
  28058. * Saves the state of the given scene and stores it into the given state object.
  28059. * Besides, the function also resets the state of the scene to its default values.
  28060. *
  28061. * If not state object is provided, the function creates one.
  28062. *
  28063. * @function
  28064. * @param {Scene} scene - The scene.
  28065. * @param {Object} [state={}] - The state.
  28066. * @return {Object} The state.
  28067. */
  28068. function resetSceneState( scene, state ) {
  28069. state = saveSceneState( scene, state );
  28070. scene.background = null;
  28071. scene.backgroundNode = null;
  28072. scene.overrideMaterial = null;
  28073. return state;
  28074. }
  28075. /**
  28076. * Restores the state of the given scene from the given state object.
  28077. *
  28078. * @function
  28079. * @param {Scene} scene - The scene.
  28080. * @param {Object} state - The state to restore.
  28081. */
  28082. function restoreSceneState( scene, state ) {
  28083. scene.background = state.background;
  28084. scene.backgroundNode = state.backgroundNode;
  28085. scene.overrideMaterial = state.overrideMaterial;
  28086. }
  28087. /**
  28088. * Saves the state of the given renderer and scene and stores it into the given state object.
  28089. *
  28090. * If not state object is provided, the function creates one.
  28091. *
  28092. * @function
  28093. * @param {Renderer} renderer - The renderer.
  28094. * @param {Scene} scene - The scene.
  28095. * @param {Object} [state={}] - The state.
  28096. * @return {Object} The state.
  28097. */
  28098. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  28099. state = saveRendererState( renderer, state );
  28100. state = saveSceneState( scene, state );
  28101. return state;
  28102. }
  28103. /**
  28104. * Saves the state of the given renderer and scene and stores it into the given state object.
  28105. * Besides, the function also resets the state of the renderer and scene to its default values.
  28106. *
  28107. * If not state object is provided, the function creates one.
  28108. *
  28109. * @function
  28110. * @param {Renderer} renderer - The renderer.
  28111. * @param {Scene} scene - The scene.
  28112. * @param {Object} [state={}] - The state.
  28113. * @return {Object} The state.
  28114. */
  28115. function resetRendererAndSceneState( renderer, scene, state ) {
  28116. state = resetRendererState( renderer, state );
  28117. state = resetSceneState( scene, state );
  28118. return state;
  28119. }
  28120. /**
  28121. * Restores the state of the given renderer and scene from the given state object.
  28122. *
  28123. * @function
  28124. * @param {Renderer} renderer - The renderer.
  28125. * @param {Scene} scene - The scene.
  28126. * @param {Object} state - The state to restore.
  28127. */
  28128. function restoreRendererAndSceneState( renderer, scene, state ) {
  28129. restoreRendererState( renderer, state );
  28130. restoreSceneState( scene, state );
  28131. }
  28132. var RendererUtils = /*#__PURE__*/Object.freeze({
  28133. __proto__: null,
  28134. resetRendererAndSceneState: resetRendererAndSceneState,
  28135. resetRendererState: resetRendererState,
  28136. resetSceneState: resetSceneState,
  28137. restoreRendererAndSceneState: restoreRendererAndSceneState,
  28138. restoreRendererState: restoreRendererState,
  28139. restoreSceneState: restoreSceneState,
  28140. saveRendererAndSceneState: saveRendererAndSceneState,
  28141. saveRendererState: saveRendererState,
  28142. saveSceneState: saveSceneState
  28143. });
  28144. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  28145. /**
  28146. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  28147. * with a binary `[0,1]` result.
  28148. *
  28149. * @method
  28150. * @param {Object} inputs - The input parameter object.
  28151. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28152. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  28153. * @return {Node<float>} The filtering result.
  28154. */
  28155. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  28156. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  28157. if ( depthTexture.isArrayTexture ) {
  28158. basic = basic.depth( depthLayer );
  28159. }
  28160. return basic.compare( shadowCoord.z );
  28161. } );
  28162. /**
  28163. * A shadow filtering function performing PCF filtering.
  28164. *
  28165. * @method
  28166. * @param {Object} inputs - The input parameter object.
  28167. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28168. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  28169. * @param {LightShadow} inputs.shadow - The light shadow.
  28170. * @return {Node<float>} The filtering result.
  28171. */
  28172. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  28173. const depthCompare = ( uv, compare ) => {
  28174. let depth = texture( depthTexture, uv );
  28175. if ( depthTexture.isArrayTexture ) {
  28176. depth = depth.depth( depthLayer );
  28177. }
  28178. return depth.compare( compare );
  28179. };
  28180. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  28181. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  28182. const texelSize = vec2( 1 ).div( mapSize );
  28183. const dx0 = texelSize.x.negate().mul( radius );
  28184. const dy0 = texelSize.y.negate().mul( radius );
  28185. const dx1 = texelSize.x.mul( radius );
  28186. const dy1 = texelSize.y.mul( radius );
  28187. const dx2 = dx0.div( 2 );
  28188. const dy2 = dy0.div( 2 );
  28189. const dx3 = dx1.div( 2 );
  28190. const dy3 = dy1.div( 2 );
  28191. return add(
  28192. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  28193. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  28194. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  28195. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  28196. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  28197. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  28198. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  28199. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  28200. depthCompare( shadowCoord.xy, shadowCoord.z ),
  28201. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  28202. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  28203. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  28204. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  28205. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  28206. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  28207. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  28208. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  28209. ).mul( 1 / 17 );
  28210. } );
  28211. /**
  28212. * A shadow filtering function performing PCF soft filtering.
  28213. *
  28214. * @method
  28215. * @param {Object} inputs - The input parameter object.
  28216. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28217. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  28218. * @param {LightShadow} inputs.shadow - The light shadow.
  28219. * @return {Node<float>} The filtering result.
  28220. */
  28221. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  28222. const depthCompare = ( uv, compare ) => {
  28223. let depth = texture( depthTexture, uv );
  28224. if ( depthTexture.isArrayTexture ) {
  28225. depth = depth.depth( depthLayer );
  28226. }
  28227. return depth.compare( compare );
  28228. };
  28229. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  28230. const texelSize = vec2( 1 ).div( mapSize );
  28231. const dx = texelSize.x;
  28232. const dy = texelSize.y;
  28233. const uv = shadowCoord.xy;
  28234. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  28235. uv.subAssign( f.mul( texelSize ) );
  28236. return add(
  28237. depthCompare( uv, shadowCoord.z ),
  28238. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  28239. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  28240. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  28241. mix(
  28242. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  28243. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  28244. f.x
  28245. ),
  28246. mix(
  28247. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  28248. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  28249. f.x
  28250. ),
  28251. mix(
  28252. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  28253. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  28254. f.y
  28255. ),
  28256. mix(
  28257. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  28258. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  28259. f.y
  28260. ),
  28261. mix(
  28262. mix(
  28263. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  28264. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  28265. f.x
  28266. ),
  28267. mix(
  28268. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  28269. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  28270. f.x
  28271. ),
  28272. f.y
  28273. )
  28274. ).mul( 1 / 9 );
  28275. } );
  28276. /**
  28277. * A shadow filtering function performing VSM filtering.
  28278. *
  28279. * @method
  28280. * @param {Object} inputs - The input parameter object.
  28281. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28282. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  28283. * @return {Node<float>} The filtering result.
  28284. */
  28285. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  28286. const occlusion = float( 1 ).toVar();
  28287. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  28288. if ( depthTexture.isArrayTexture ) {
  28289. distribution = distribution.depth( depthLayer );
  28290. }
  28291. distribution = distribution.rg;
  28292. const hardShadow = step( shadowCoord.z, distribution.x );
  28293. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  28294. const distance = shadowCoord.z.sub( distribution.x );
  28295. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  28296. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  28297. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  28298. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  28299. } );
  28300. return occlusion;
  28301. } );
  28302. //
  28303. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  28304. let dist = positionWorld.sub( position ).length();
  28305. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  28306. dist = dist.saturate(); // clamp to [ 0, 1 ]
  28307. return dist;
  28308. } );
  28309. const linearShadowDistance = ( light ) => {
  28310. const camera = light.shadow.camera;
  28311. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  28312. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  28313. const referencePosition = objectPosition( light );
  28314. return linearDistance( referencePosition, nearDistance, farDistance );
  28315. };
  28316. /**
  28317. * Retrieves or creates a shadow material for the given light source.
  28318. *
  28319. * This function checks if a shadow material already exists for the provided light.
  28320. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  28321. * in the `shadowMaterialLib` for future use.
  28322. *
  28323. * @param {Light} light - The light source for which the shadow material is needed.
  28324. * If the light is a point light, a depth node is calculated
  28325. * using the linear shadow distance.
  28326. * @returns {NodeMaterial} The shadow material associated with the given light.
  28327. */
  28328. const getShadowMaterial = ( light ) => {
  28329. let material = shadowMaterialLib.get( light );
  28330. if ( material === undefined ) {
  28331. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  28332. material = new NodeMaterial();
  28333. material.colorNode = vec4( 0, 0, 0, 1 );
  28334. material.depthNode = depthNode;
  28335. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  28336. material.name = 'ShadowMaterial';
  28337. material.fog = false;
  28338. shadowMaterialLib.set( light, material );
  28339. }
  28340. return material;
  28341. };
  28342. //
  28343. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  28344. const _shadowRenderObjectKeys = [];
  28345. /**
  28346. * Creates a function to render shadow objects in a scene.
  28347. *
  28348. * @param {Renderer} renderer - The renderer.
  28349. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  28350. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  28351. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  28352. * @return {Function} A function that renders shadow objects.
  28353. *
  28354. * The returned function has the following parameters:
  28355. * @param {Object3D} object - The 3D object to render.
  28356. * @param {Scene} scene - The scene containing the object.
  28357. * @param {Camera} _camera - The camera used for rendering.
  28358. * @param {BufferGeometry} geometry - The geometry of the object.
  28359. * @param {Material} material - The material of the object.
  28360. * @param {Group} group - The group the object belongs to.
  28361. * @param {...any} params - Additional parameters for rendering.
  28362. */
  28363. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  28364. _shadowRenderObjectKeys[ 0 ] = renderer;
  28365. _shadowRenderObjectKeys[ 1 ] = shadow;
  28366. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  28367. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  28368. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  28369. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  28370. if ( useVelocity ) {
  28371. getDataFromObject( object ).useVelocity = true;
  28372. }
  28373. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  28374. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  28375. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  28376. }
  28377. };
  28378. renderObjectFunction.shadowType = shadowType;
  28379. renderObjectFunction.useVelocity = useVelocity;
  28380. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  28381. }
  28382. _shadowRenderObjectKeys[ 0 ] = null;
  28383. _shadowRenderObjectKeys[ 1 ] = null;
  28384. return renderObjectFunction;
  28385. };
  28386. /**
  28387. * Represents the shader code for the first VSM render pass.
  28388. *
  28389. * @method
  28390. * @param {Object} inputs - The input parameter object.
  28391. * @param {Node<float>} inputs.samples - The number of samples
  28392. * @param {Node<float>} inputs.radius - The radius.
  28393. * @param {Node<float>} inputs.size - The size.
  28394. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  28395. * @return {Node<vec2>} The VSM output.
  28396. */
  28397. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  28398. const mean = float( 0 ).toVar( 'meanVertical' );
  28399. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  28400. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  28401. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  28402. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  28403. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  28404. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  28405. if ( shadowPass.value.isArrayTexture ) {
  28406. depth = depth.depth( depthLayer );
  28407. }
  28408. depth = depth.x;
  28409. mean.addAssign( depth );
  28410. squaredMean.addAssign( depth.mul( depth ) );
  28411. } );
  28412. mean.divAssign( samples );
  28413. squaredMean.divAssign( samples );
  28414. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  28415. return vec2( mean, std_dev );
  28416. } );
  28417. /**
  28418. * Represents the shader code for the second VSM render pass.
  28419. *
  28420. * @method
  28421. * @param {Object} inputs - The input parameter object.
  28422. * @param {Node<float>} inputs.samples - The number of samples
  28423. * @param {Node<float>} inputs.radius - The radius.
  28424. * @param {Node<float>} inputs.size - The size.
  28425. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  28426. * @return {Node<vec2>} The VSM output.
  28427. */
  28428. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  28429. const mean = float( 0 ).toVar( 'meanHorizontal' );
  28430. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  28431. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  28432. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  28433. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  28434. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  28435. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  28436. if ( shadowPass.value.isArrayTexture ) {
  28437. distribution = distribution.depth( depthLayer );
  28438. }
  28439. mean.addAssign( distribution.x );
  28440. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  28441. } );
  28442. mean.divAssign( samples );
  28443. squaredMean.divAssign( samples );
  28444. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  28445. return vec2( mean, std_dev );
  28446. } );
  28447. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  28448. //
  28449. let _rendererState;
  28450. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  28451. /**
  28452. * Represents the default shadow implementation for lighting nodes.
  28453. *
  28454. * @augments ShadowBaseNode
  28455. */
  28456. class ShadowNode extends ShadowBaseNode {
  28457. static get type() {
  28458. return 'ShadowNode';
  28459. }
  28460. /**
  28461. * Constructs a new shadow node.
  28462. *
  28463. * @param {Light} light - The shadow casting light.
  28464. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  28465. */
  28466. constructor( light, shadow = null ) {
  28467. super( light );
  28468. /**
  28469. * The light shadow which defines the properties light's
  28470. * shadow.
  28471. *
  28472. * @type {?LightShadow}
  28473. * @default null
  28474. */
  28475. this.shadow = shadow || light.shadow;
  28476. /**
  28477. * A reference to the shadow map which is a render target.
  28478. *
  28479. * @type {?RenderTarget}
  28480. * @default null
  28481. */
  28482. this.shadowMap = null;
  28483. /**
  28484. * Only relevant for VSM shadows. Render target for the
  28485. * first VSM render pass.
  28486. *
  28487. * @type {?RenderTarget}
  28488. * @default null
  28489. */
  28490. this.vsmShadowMapVertical = null;
  28491. /**
  28492. * Only relevant for VSM shadows. Render target for the
  28493. * second VSM render pass.
  28494. *
  28495. * @type {?RenderTarget}
  28496. * @default null
  28497. */
  28498. this.vsmShadowMapHorizontal = null;
  28499. /**
  28500. * Only relevant for VSM shadows. Node material which
  28501. * is used to render the first VSM pass.
  28502. *
  28503. * @type {?NodeMaterial}
  28504. * @default null
  28505. */
  28506. this.vsmMaterialVertical = null;
  28507. /**
  28508. * Only relevant for VSM shadows. Node material which
  28509. * is used to render the second VSM pass.
  28510. *
  28511. * @type {?NodeMaterial}
  28512. * @default null
  28513. */
  28514. this.vsmMaterialHorizontal = null;
  28515. /**
  28516. * A reference to the output node which defines the
  28517. * final result of this shadow node.
  28518. *
  28519. * @type {?Node}
  28520. * @private
  28521. * @default null
  28522. */
  28523. this._node = null;
  28524. this._cameraFrameId = new WeakMap();
  28525. /**
  28526. * This flag can be used for type testing.
  28527. *
  28528. * @type {boolean}
  28529. * @readonly
  28530. * @default true
  28531. */
  28532. this.isShadowNode = true;
  28533. /**
  28534. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  28535. *
  28536. * @type {number}
  28537. * @readonly
  28538. * @default true
  28539. */
  28540. this.depthLayer = 0;
  28541. }
  28542. /**
  28543. * Setups the shadow filtering.
  28544. *
  28545. * @param {NodeBuilder} builder - A reference to the current node builder.
  28546. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  28547. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  28548. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28549. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  28550. * @param {LightShadow} inputs.shadow - The light shadow.
  28551. * @return {Node<float>} The result node of the shadow filtering.
  28552. */
  28553. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  28554. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  28555. .and( shadowCoord.x.lessThanEqual( 1 ) )
  28556. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  28557. .and( shadowCoord.y.lessThanEqual( 1 ) )
  28558. .and( shadowCoord.z.lessThanEqual( 1 ) );
  28559. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  28560. return frustumTest.select( shadowNode, float( 1 ) );
  28561. }
  28562. /**
  28563. * Setups the shadow coordinates.
  28564. *
  28565. * @param {NodeBuilder} builder - A reference to the current node builder.
  28566. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  28567. * @return {Node<vec3>} The shadow coordinates.
  28568. */
  28569. setupShadowCoord( builder, shadowPosition ) {
  28570. const { shadow } = this;
  28571. const { renderer } = builder;
  28572. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  28573. let shadowCoord = shadowPosition;
  28574. let coordZ;
  28575. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  28576. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  28577. coordZ = shadowCoord.z;
  28578. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  28579. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  28580. }
  28581. } else {
  28582. const w = shadowCoord.w;
  28583. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  28584. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  28585. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  28586. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  28587. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  28588. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  28589. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  28590. }
  28591. shadowCoord = vec3(
  28592. shadowCoord.x,
  28593. shadowCoord.y.oneMinus(), // follow webgpu standards
  28594. coordZ.add( bias )
  28595. );
  28596. return shadowCoord;
  28597. }
  28598. /**
  28599. * Returns the shadow filtering function for the given shadow type.
  28600. *
  28601. * @param {number} type - The shadow type.
  28602. * @return {Function} The filtering function.
  28603. */
  28604. getShadowFilterFn( type ) {
  28605. return _shadowFilterLib[ type ];
  28606. }
  28607. setupRenderTarget( shadow, builder ) {
  28608. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  28609. depthTexture.name = 'ShadowDepthTexture';
  28610. depthTexture.compareFunction = LessCompare;
  28611. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  28612. shadowMap.texture.name = 'ShadowMap';
  28613. shadowMap.texture.type = shadow.mapType;
  28614. shadowMap.depthTexture = depthTexture;
  28615. return { shadowMap, depthTexture };
  28616. }
  28617. /**
  28618. * Setups the shadow output node.
  28619. *
  28620. * @param {NodeBuilder} builder - A reference to the current node builder.
  28621. * @return {Node<vec3>} The shadow output node.
  28622. */
  28623. setupShadow( builder ) {
  28624. const { renderer } = builder;
  28625. const { light, shadow } = this;
  28626. const shadowMapType = renderer.shadowMap.type;
  28627. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  28628. shadow.camera.updateProjectionMatrix();
  28629. // VSM
  28630. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  28631. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  28632. if ( shadowMap.depth > 1 ) {
  28633. if ( ! shadowMap._vsmShadowMapVertical ) {
  28634. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  28635. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  28636. }
  28637. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  28638. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  28639. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  28640. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  28641. }
  28642. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  28643. } else {
  28644. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  28645. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  28646. }
  28647. let shadowPassVertical = texture( depthTexture );
  28648. if ( depthTexture.isArrayTexture ) {
  28649. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  28650. }
  28651. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  28652. if ( depthTexture.isArrayTexture ) {
  28653. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  28654. }
  28655. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  28656. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  28657. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  28658. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  28659. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  28660. material.name = 'VSMVertical';
  28661. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  28662. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  28663. material.name = 'VSMHorizontal';
  28664. }
  28665. //
  28666. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  28667. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  28668. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  28669. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  28670. //
  28671. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  28672. if ( filterFn === null ) {
  28673. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  28674. }
  28675. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  28676. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  28677. let shadowColor = texture( shadowMap.texture, shadowCoord );
  28678. if ( depthTexture.isArrayTexture ) {
  28679. shadowColor = shadowColor.depth( this.depthLayer );
  28680. }
  28681. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  28682. this.shadowMap = shadowMap;
  28683. this.shadow.map = shadowMap;
  28684. return shadowOutput;
  28685. }
  28686. /**
  28687. * The implementation performs the setup of the output node. An output is only
  28688. * produces if shadow mapping is globally enabled in the renderer.
  28689. *
  28690. * @param {NodeBuilder} builder - A reference to the current node builder.
  28691. * @return {ShaderCallNodeInternal} The output node.
  28692. */
  28693. setup( builder ) {
  28694. if ( builder.renderer.shadowMap.enabled === false ) return;
  28695. return Fn( () => {
  28696. let node = this._node;
  28697. this.setupShadowPosition( builder );
  28698. if ( node === null ) {
  28699. this._node = node = this.setupShadow( builder );
  28700. }
  28701. if ( builder.material.shadowNode ) { // @deprecated, r171
  28702. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  28703. }
  28704. if ( builder.material.receivedShadowNode ) {
  28705. node = builder.material.receivedShadowNode( node );
  28706. }
  28707. return node;
  28708. } )();
  28709. }
  28710. /**
  28711. * Renders the shadow. The logic of this function could be included
  28712. * into {@link ShadowNode#updateShadow} however more specialized shadow
  28713. * nodes might require a custom shadow map rendering. By having a
  28714. * dedicated method, it's easier to overwrite the default behavior.
  28715. *
  28716. * @param {NodeFrame} frame - A reference to the current node frame.
  28717. */
  28718. renderShadow( frame ) {
  28719. const { shadow, shadowMap, light } = this;
  28720. const { renderer, scene } = frame;
  28721. shadow.updateMatrices( light );
  28722. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  28723. renderer.render( scene, shadow.camera );
  28724. }
  28725. /**
  28726. * Updates the shadow.
  28727. *
  28728. * @param {NodeFrame} frame - A reference to the current node frame.
  28729. */
  28730. updateShadow( frame ) {
  28731. const { shadowMap, light, shadow } = this;
  28732. const { renderer, scene, camera } = frame;
  28733. const shadowType = renderer.shadowMap.type;
  28734. const depthVersion = shadowMap.depthTexture.version;
  28735. this._depthVersionCached = depthVersion;
  28736. const _shadowCameraLayer = shadow.camera.layers.mask;
  28737. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  28738. shadow.camera.layers.mask = camera.layers.mask;
  28739. }
  28740. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  28741. const currentMRT = renderer.getMRT();
  28742. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  28743. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  28744. scene.overrideMaterial = getShadowMaterial( light );
  28745. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  28746. renderer.setClearColor( 0x000000, 0 );
  28747. renderer.setRenderTarget( shadowMap );
  28748. this.renderShadow( frame );
  28749. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  28750. // vsm blur pass
  28751. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  28752. this.vsmPass( renderer );
  28753. }
  28754. shadow.camera.layers.mask = _shadowCameraLayer;
  28755. restoreRendererAndSceneState( renderer, scene, _rendererState );
  28756. }
  28757. /**
  28758. * For VSM additional render passes are required.
  28759. *
  28760. * @param {Renderer} renderer - A reference to the current renderer.
  28761. */
  28762. vsmPass( renderer ) {
  28763. const { shadow } = this;
  28764. const depth = this.shadowMap.depth;
  28765. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  28766. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  28767. renderer.setRenderTarget( this.vsmShadowMapVertical );
  28768. _quadMesh.material = this.vsmMaterialVertical;
  28769. _quadMesh.render( renderer );
  28770. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  28771. _quadMesh.material = this.vsmMaterialHorizontal;
  28772. _quadMesh.render( renderer );
  28773. }
  28774. /**
  28775. * Frees the internal resources of this shadow node.
  28776. */
  28777. dispose() {
  28778. this.shadowMap.dispose();
  28779. this.shadowMap = null;
  28780. if ( this.vsmShadowMapVertical !== null ) {
  28781. this.vsmShadowMapVertical.dispose();
  28782. this.vsmShadowMapVertical = null;
  28783. this.vsmMaterialVertical.dispose();
  28784. this.vsmMaterialVertical = null;
  28785. }
  28786. if ( this.vsmShadowMapHorizontal !== null ) {
  28787. this.vsmShadowMapHorizontal.dispose();
  28788. this.vsmShadowMapHorizontal = null;
  28789. this.vsmMaterialHorizontal.dispose();
  28790. this.vsmMaterialHorizontal = null;
  28791. }
  28792. super.dispose();
  28793. }
  28794. /**
  28795. * The implementation performs the update of the shadow map if necessary.
  28796. *
  28797. * @param {NodeFrame} frame - A reference to the current node frame.
  28798. */
  28799. updateBefore( frame ) {
  28800. const { shadow } = this;
  28801. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  28802. if ( needsUpdate ) {
  28803. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  28804. needsUpdate = false;
  28805. }
  28806. this._cameraFrameId[ frame.camera ] = frame.frameId;
  28807. }
  28808. if ( needsUpdate ) {
  28809. this.updateShadow( frame );
  28810. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  28811. shadow.needsUpdate = false;
  28812. }
  28813. }
  28814. }
  28815. }
  28816. /**
  28817. * TSL function for creating an instance of `ShadowNode`.
  28818. *
  28819. * @tsl
  28820. * @function
  28821. * @param {Light} light - The shadow casting light.
  28822. * @param {?LightShadow} [shadow] - The light shadow.
  28823. * @return {ShadowNode} The created shadow node.
  28824. */
  28825. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  28826. const _clearColor$1 = /*@__PURE__*/ new Color();
  28827. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  28828. // vector suitable for 2D texture mapping. This code uses the following layout for the
  28829. // 2D texture:
  28830. //
  28831. // xzXZ
  28832. // y Y
  28833. //
  28834. // Y - Positive y direction
  28835. // y - Negative y direction
  28836. // X - Positive x direction
  28837. // x - Negative x direction
  28838. // Z - Positive z direction
  28839. // z - Negative z direction
  28840. //
  28841. // Source and test bed:
  28842. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  28843. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  28844. const v = pos.toVar();
  28845. // Number of texels to avoid at the edge of each square
  28846. const absV = abs( v );
  28847. // Intersect unit cube
  28848. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  28849. absV.mulAssign( scaleToCube );
  28850. // Apply scale to avoid seams
  28851. // two texels less per square (one texel will do for NEAREST)
  28852. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  28853. // Unwrap
  28854. // space: -1 ... 1 range for each square
  28855. //
  28856. // #X## dim := ( 4 , 2 )
  28857. // # # center := ( 1 , 1 )
  28858. const planar = vec2( v.xy ).toVar();
  28859. const almostATexel = texelSizeY.mul( 1.5 );
  28860. const almostOne = almostATexel.oneMinus();
  28861. If( absV.z.greaterThanEqual( almostOne ), () => {
  28862. If( v.z.greaterThan( 0.0 ), () => {
  28863. planar.x.assign( sub( 4.0, v.x ) );
  28864. } );
  28865. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  28866. const signX = sign( v.x );
  28867. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  28868. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  28869. const signY = sign( v.y );
  28870. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  28871. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  28872. } );
  28873. // Transform to UV space
  28874. // scale := 0.5 / dim
  28875. // translate := ( center + 0.5 ) / dim
  28876. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  28877. } ).setLayout( {
  28878. name: 'cubeToUV',
  28879. type: 'vec2',
  28880. inputs: [
  28881. { name: 'pos', type: 'vec3' },
  28882. { name: 'texelSizeY', type: 'float' }
  28883. ]
  28884. } );
  28885. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  28886. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  28887. } );
  28888. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  28889. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  28890. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  28891. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  28892. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  28893. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  28894. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  28895. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  28896. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  28897. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  28898. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  28899. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  28900. .mul( 1.0 / 9.0 );
  28901. } );
  28902. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  28903. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  28904. // the vector from the light to the world-space position of the fragment.
  28905. const lightToPosition = shadowCoord.xyz.toVar();
  28906. const lightToPositionLength = lightToPosition.length();
  28907. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  28908. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  28909. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  28910. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  28911. const result = float( 1.0 ).toVar();
  28912. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  28913. // dp = normalized distance from light to fragment position
  28914. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  28915. dp.addAssign( bias );
  28916. // bd3D = base direction 3D
  28917. const bd3D = lightToPosition.normalize();
  28918. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  28919. // percentage-closer filtering
  28920. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  28921. } );
  28922. return result;
  28923. } );
  28924. const _viewport = /*@__PURE__*/ new Vector4();
  28925. const _viewportSize = /*@__PURE__*/ new Vector2();
  28926. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  28927. /**
  28928. * Represents the shadow implementation for point light nodes.
  28929. *
  28930. * @augments ShadowNode
  28931. */
  28932. class PointShadowNode extends ShadowNode {
  28933. static get type() {
  28934. return 'PointShadowNode';
  28935. }
  28936. /**
  28937. * Constructs a new point shadow node.
  28938. *
  28939. * @param {PointLight} light - The shadow casting point light.
  28940. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  28941. */
  28942. constructor( light, shadow = null ) {
  28943. super( light, shadow );
  28944. }
  28945. /**
  28946. * Overwrites the default implementation to return point light shadow specific
  28947. * filtering functions.
  28948. *
  28949. * @param {number} type - The shadow type.
  28950. * @return {Function} The filtering function.
  28951. */
  28952. getShadowFilterFn( type ) {
  28953. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  28954. }
  28955. /**
  28956. * Overwrites the default implementation so the unaltered shadow position is used.
  28957. *
  28958. * @param {NodeBuilder} builder - A reference to the current node builder.
  28959. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  28960. * @return {Node<vec3>} The shadow coordinates.
  28961. */
  28962. setupShadowCoord( builder, shadowPosition ) {
  28963. return shadowPosition;
  28964. }
  28965. /**
  28966. * Overwrites the default implementation to only use point light specific
  28967. * shadow filter functions.
  28968. *
  28969. * @param {NodeBuilder} builder - A reference to the current node builder.
  28970. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  28971. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  28972. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  28973. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28974. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  28975. * @param {LightShadow} inputs.shadow - The light shadow.
  28976. * @return {Node<float>} The result node of the shadow filtering.
  28977. */
  28978. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  28979. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  28980. }
  28981. /**
  28982. * Overwrites the default implementation with point light specific
  28983. * rendering code.
  28984. *
  28985. * @param {NodeFrame} frame - A reference to the current node frame.
  28986. */
  28987. renderShadow( frame ) {
  28988. const { shadow, shadowMap, light } = this;
  28989. const { renderer, scene } = frame;
  28990. const shadowFrameExtents = shadow.getFrameExtents();
  28991. _shadowMapSize.copy( shadow.mapSize );
  28992. _shadowMapSize.multiply( shadowFrameExtents );
  28993. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  28994. _viewportSize.copy( shadow.mapSize );
  28995. //
  28996. const previousAutoClear = renderer.autoClear;
  28997. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  28998. const previousClearAlpha = renderer.getClearAlpha();
  28999. renderer.autoClear = false;
  29000. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  29001. renderer.clear();
  29002. const viewportCount = shadow.getViewportCount();
  29003. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  29004. const viewport = shadow.getViewport( vp );
  29005. const x = _viewportSize.x * viewport.x;
  29006. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  29007. _viewport.set(
  29008. x,
  29009. y,
  29010. _viewportSize.x * viewport.z,
  29011. _viewportSize.y * viewport.w
  29012. );
  29013. shadowMap.viewport.copy( _viewport );
  29014. shadow.updateMatrices( light, vp );
  29015. renderer.render( scene, shadow.camera );
  29016. }
  29017. //
  29018. renderer.autoClear = previousAutoClear;
  29019. renderer.setClearColor( previousClearColor, previousClearAlpha );
  29020. }
  29021. }
  29022. /**
  29023. * TSL function for creating an instance of `PointShadowNode`.
  29024. *
  29025. * @tsl
  29026. * @function
  29027. * @param {PointLight} light - The shadow casting point light.
  29028. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  29029. * @return {PointShadowNode} The created point shadow node.
  29030. */
  29031. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  29032. /**
  29033. * Base class for analytic light nodes.
  29034. *
  29035. * @augments LightingNode
  29036. */
  29037. class AnalyticLightNode extends LightingNode {
  29038. static get type() {
  29039. return 'AnalyticLightNode';
  29040. }
  29041. /**
  29042. * Constructs a new analytic light node.
  29043. *
  29044. * @param {?Light} [light=null] - The light source.
  29045. */
  29046. constructor( light = null ) {
  29047. super();
  29048. /**
  29049. * The light source.
  29050. *
  29051. * @type {?Light}
  29052. * @default null
  29053. */
  29054. this.light = light;
  29055. /**
  29056. * The light's color value.
  29057. *
  29058. * @type {Color}
  29059. */
  29060. this.color = new Color();
  29061. /**
  29062. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  29063. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  29064. *
  29065. * @type {Node}
  29066. */
  29067. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  29068. /**
  29069. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  29070. * The final color node is represented by a different node when using shadows.
  29071. *
  29072. * @type {?Node}
  29073. * @default null
  29074. */
  29075. this.baseColorNode = null;
  29076. /**
  29077. * Represents the light's shadow.
  29078. *
  29079. * @type {?ShadowNode}
  29080. * @default null
  29081. */
  29082. this.shadowNode = null;
  29083. /**
  29084. * Represents the light's shadow color.
  29085. *
  29086. * @type {?Node}
  29087. * @default null
  29088. */
  29089. this.shadowColorNode = null;
  29090. /**
  29091. * This flag can be used for type testing.
  29092. *
  29093. * @type {boolean}
  29094. * @readonly
  29095. * @default true
  29096. */
  29097. this.isAnalyticLightNode = true;
  29098. /**
  29099. * Overwritten since analytic light nodes are updated
  29100. * once per frame.
  29101. *
  29102. * @type {string}
  29103. * @default 'frame'
  29104. */
  29105. this.updateType = NodeUpdateType.FRAME;
  29106. }
  29107. getHash() {
  29108. return this.light.uuid;
  29109. }
  29110. /**
  29111. * Returns a node representing a direction vector which points from the current
  29112. * position in view space to the light's position in view space.
  29113. *
  29114. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  29115. * @return {Node<vec3>} The light vector node.
  29116. */
  29117. getLightVector( builder ) {
  29118. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  29119. }
  29120. /**
  29121. * Sets up the direct lighting for the analytic light node.
  29122. *
  29123. * @abstract
  29124. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  29125. * @return {Object|undefined} The direct light data (color and direction).
  29126. */
  29127. setupDirect( /*builder*/ ) { }
  29128. /**
  29129. * Sets up the direct rect area lighting for the analytic light node.
  29130. *
  29131. * @abstract
  29132. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  29133. * @return {Object|undefined} The direct rect area light data.
  29134. */
  29135. setupDirectRectArea( /*builder*/ ) { }
  29136. /**
  29137. * Setups the shadow node for this light. The method exists so concrete light classes
  29138. * can setup different types of shadow nodes.
  29139. *
  29140. * @return {ShadowNode} The created shadow node.
  29141. */
  29142. setupShadowNode() {
  29143. return shadow( this.light );
  29144. }
  29145. /**
  29146. * Setups the shadow for this light. This method is only executed if the light
  29147. * cast shadows and the current build object receives shadows. It incorporates
  29148. * shadows into the lighting computation.
  29149. *
  29150. * @param {NodeBuilder} builder - The current node builder.
  29151. */
  29152. setupShadow( builder ) {
  29153. const { renderer } = builder;
  29154. if ( renderer.shadowMap.enabled === false ) return;
  29155. let shadowColorNode = this.shadowColorNode;
  29156. if ( shadowColorNode === null ) {
  29157. const customShadowNode = this.light.shadow.shadowNode;
  29158. let shadowNode;
  29159. if ( customShadowNode !== undefined ) {
  29160. shadowNode = nodeObject( customShadowNode );
  29161. } else {
  29162. shadowNode = this.setupShadowNode();
  29163. }
  29164. this.shadowNode = shadowNode;
  29165. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  29166. this.baseColorNode = this.colorNode;
  29167. }
  29168. //
  29169. this.colorNode = shadowColorNode;
  29170. }
  29171. /**
  29172. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  29173. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  29174. * invocate the respective interface methods.
  29175. *
  29176. * @param {NodeBuilder} builder - The current node builder.
  29177. */
  29178. setup( builder ) {
  29179. this.colorNode = this.baseColorNode || this.colorNode;
  29180. if ( this.light.castShadow ) {
  29181. if ( builder.object.receiveShadow ) {
  29182. this.setupShadow( builder );
  29183. }
  29184. } else if ( this.shadowNode !== null ) {
  29185. this.shadowNode.dispose();
  29186. this.shadowNode = null;
  29187. this.shadowColorNode = null;
  29188. }
  29189. const directLightData = this.setupDirect( builder );
  29190. const directRectAreaLightData = this.setupDirectRectArea( builder );
  29191. if ( directLightData ) {
  29192. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  29193. }
  29194. if ( directRectAreaLightData ) {
  29195. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  29196. }
  29197. }
  29198. /**
  29199. * The update method is used to update light uniforms per frame.
  29200. * Potentially overwritten in concrete light nodes to update light
  29201. * specific uniforms.
  29202. *
  29203. * @param {NodeFrame} frame - A reference to the current node frame.
  29204. */
  29205. update( /*frame*/ ) {
  29206. const { light } = this;
  29207. this.color.copy( light.color ).multiplyScalar( light.intensity );
  29208. }
  29209. }
  29210. /**
  29211. * Represents a `discard` shader operation in TSL.
  29212. *
  29213. * @method
  29214. * @param {Object} inputs - The input parameter object.
  29215. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  29216. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  29217. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  29218. * @return {Node<float>} The distance falloff.
  29219. */
  29220. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  29221. // based upon Frostbite 3 Moving to Physically-based Rendering
  29222. // page 32, equation 26: E[window1]
  29223. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  29224. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  29225. return cutoffDistance.greaterThan( 0 ).select(
  29226. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  29227. distanceFalloff
  29228. );
  29229. } ); // validated
  29230. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  29231. const lightDirection = lightVector.normalize();
  29232. const lightDistance = lightVector.length();
  29233. const attenuation = getDistanceAttenuation( {
  29234. lightDistance,
  29235. cutoffDistance,
  29236. decayExponent
  29237. } );
  29238. const lightColor = color.mul( attenuation );
  29239. return { lightDirection, lightColor };
  29240. };
  29241. /**
  29242. * Module for representing point lights as nodes.
  29243. *
  29244. * @augments AnalyticLightNode
  29245. */
  29246. class PointLightNode extends AnalyticLightNode {
  29247. static get type() {
  29248. return 'PointLightNode';
  29249. }
  29250. /**
  29251. * Constructs a new point light node.
  29252. *
  29253. * @param {?PointLight} [light=null] - The point light source.
  29254. */
  29255. constructor( light = null ) {
  29256. super( light );
  29257. /**
  29258. * Uniform node representing the cutoff distance.
  29259. *
  29260. * @type {UniformNode<float>}
  29261. */
  29262. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  29263. /**
  29264. * Uniform node representing the decay exponent.
  29265. *
  29266. * @type {UniformNode<float>}
  29267. */
  29268. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  29269. }
  29270. /**
  29271. * Overwritten to updated point light specific uniforms.
  29272. *
  29273. * @param {NodeFrame} frame - A reference to the current node frame.
  29274. */
  29275. update( frame ) {
  29276. const { light } = this;
  29277. super.update( frame );
  29278. this.cutoffDistanceNode.value = light.distance;
  29279. this.decayExponentNode.value = light.decay;
  29280. }
  29281. /**
  29282. * Overwritten to setup point light specific shadow.
  29283. *
  29284. * @return {PointShadowNode}
  29285. */
  29286. setupShadowNode() {
  29287. return pointShadow( this.light );
  29288. }
  29289. setupDirect( builder ) {
  29290. return directPointLight( {
  29291. color: this.colorNode,
  29292. lightVector: this.getLightVector( builder ),
  29293. cutoffDistance: this.cutoffDistanceNode,
  29294. decayExponent: this.decayExponentNode
  29295. } );
  29296. }
  29297. }
  29298. /**
  29299. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  29300. *
  29301. * @tsl
  29302. * @function
  29303. * @param {Node<vec2>} coord - The uv coordinates.
  29304. * @return {Node<float>} The result data.
  29305. */
  29306. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  29307. const uv = coord.mul( 2.0 );
  29308. const cx = uv.x.floor();
  29309. const cy = uv.y.floor();
  29310. const result = cx.add( cy ).mod( 2.0 );
  29311. return result.sign();
  29312. } );
  29313. /**
  29314. * Generates a circle based on the uv coordinates.
  29315. *
  29316. * @tsl
  29317. * @function
  29318. * @param {Node<vec2>} coord - The uv to generate the circle.
  29319. * @return {Node<float>} The circle shape.
  29320. */
  29321. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  29322. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  29323. let alpha;
  29324. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  29325. const dlen = float( len2.fwidth() ).toVar();
  29326. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  29327. } else {
  29328. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  29329. }
  29330. return alpha;
  29331. } );
  29332. // Three.js Transpiler
  29333. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  29334. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  29335. const f = float( f_immutable ).toVar();
  29336. const t = float( t_immutable ).toVar();
  29337. const b = bool( b_immutable ).toVar();
  29338. return select( b, t, f );
  29339. } ).setLayout( {
  29340. name: 'mx_select',
  29341. type: 'float',
  29342. inputs: [
  29343. { name: 'b', type: 'bool' },
  29344. { name: 't', type: 'float' },
  29345. { name: 'f', type: 'float' }
  29346. ]
  29347. } );
  29348. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  29349. const b = bool( b_immutable ).toVar();
  29350. const val = float( val_immutable ).toVar();
  29351. return select( b, val.negate(), val );
  29352. } ).setLayout( {
  29353. name: 'mx_negate_if',
  29354. type: 'float',
  29355. inputs: [
  29356. { name: 'val', type: 'float' },
  29357. { name: 'b', type: 'bool' }
  29358. ]
  29359. } );
  29360. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  29361. const x = float( x_immutable ).toVar();
  29362. return int( floor( x ) );
  29363. } ).setLayout( {
  29364. name: 'mx_floor',
  29365. type: 'int',
  29366. inputs: [
  29367. { name: 'x', type: 'float' }
  29368. ]
  29369. } );
  29370. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  29371. const x = float( x_immutable ).toVar();
  29372. i.assign( mx_floor( x ) );
  29373. return x.sub( float( i ) );
  29374. } );
  29375. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  29376. const t = float( t_immutable ).toVar();
  29377. const s = float( s_immutable ).toVar();
  29378. const v3 = float( v3_immutable ).toVar();
  29379. const v2 = float( v2_immutable ).toVar();
  29380. const v1 = float( v1_immutable ).toVar();
  29381. const v0 = float( v0_immutable ).toVar();
  29382. const s1 = float( sub( 1.0, s ) ).toVar();
  29383. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  29384. } ).setLayout( {
  29385. name: 'mx_bilerp_0',
  29386. type: 'float',
  29387. inputs: [
  29388. { name: 'v0', type: 'float' },
  29389. { name: 'v1', type: 'float' },
  29390. { name: 'v2', type: 'float' },
  29391. { name: 'v3', type: 'float' },
  29392. { name: 's', type: 'float' },
  29393. { name: 't', type: 'float' }
  29394. ]
  29395. } );
  29396. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  29397. const t = float( t_immutable ).toVar();
  29398. const s = float( s_immutable ).toVar();
  29399. const v3 = vec3( v3_immutable ).toVar();
  29400. const v2 = vec3( v2_immutable ).toVar();
  29401. const v1 = vec3( v1_immutable ).toVar();
  29402. const v0 = vec3( v0_immutable ).toVar();
  29403. const s1 = float( sub( 1.0, s ) ).toVar();
  29404. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  29405. } ).setLayout( {
  29406. name: 'mx_bilerp_1',
  29407. type: 'vec3',
  29408. inputs: [
  29409. { name: 'v0', type: 'vec3' },
  29410. { name: 'v1', type: 'vec3' },
  29411. { name: 'v2', type: 'vec3' },
  29412. { name: 'v3', type: 'vec3' },
  29413. { name: 's', type: 'float' },
  29414. { name: 't', type: 'float' }
  29415. ]
  29416. } );
  29417. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  29418. 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 ] ) => {
  29419. const r = float( r_immutable ).toVar();
  29420. const t = float( t_immutable ).toVar();
  29421. const s = float( s_immutable ).toVar();
  29422. const v7 = float( v7_immutable ).toVar();
  29423. const v6 = float( v6_immutable ).toVar();
  29424. const v5 = float( v5_immutable ).toVar();
  29425. const v4 = float( v4_immutable ).toVar();
  29426. const v3 = float( v3_immutable ).toVar();
  29427. const v2 = float( v2_immutable ).toVar();
  29428. const v1 = float( v1_immutable ).toVar();
  29429. const v0 = float( v0_immutable ).toVar();
  29430. const s1 = float( sub( 1.0, s ) ).toVar();
  29431. const t1 = float( sub( 1.0, t ) ).toVar();
  29432. const r1 = float( sub( 1.0, r ) ).toVar();
  29433. 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 ) ) ) ) ) );
  29434. } ).setLayout( {
  29435. name: 'mx_trilerp_0',
  29436. type: 'float',
  29437. inputs: [
  29438. { name: 'v0', type: 'float' },
  29439. { name: 'v1', type: 'float' },
  29440. { name: 'v2', type: 'float' },
  29441. { name: 'v3', type: 'float' },
  29442. { name: 'v4', type: 'float' },
  29443. { name: 'v5', type: 'float' },
  29444. { name: 'v6', type: 'float' },
  29445. { name: 'v7', type: 'float' },
  29446. { name: 's', type: 'float' },
  29447. { name: 't', type: 'float' },
  29448. { name: 'r', type: 'float' }
  29449. ]
  29450. } );
  29451. 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 ] ) => {
  29452. const r = float( r_immutable ).toVar();
  29453. const t = float( t_immutable ).toVar();
  29454. const s = float( s_immutable ).toVar();
  29455. const v7 = vec3( v7_immutable ).toVar();
  29456. const v6 = vec3( v6_immutable ).toVar();
  29457. const v5 = vec3( v5_immutable ).toVar();
  29458. const v4 = vec3( v4_immutable ).toVar();
  29459. const v3 = vec3( v3_immutable ).toVar();
  29460. const v2 = vec3( v2_immutable ).toVar();
  29461. const v1 = vec3( v1_immutable ).toVar();
  29462. const v0 = vec3( v0_immutable ).toVar();
  29463. const s1 = float( sub( 1.0, s ) ).toVar();
  29464. const t1 = float( sub( 1.0, t ) ).toVar();
  29465. const r1 = float( sub( 1.0, r ) ).toVar();
  29466. 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 ) ) ) ) ) );
  29467. } ).setLayout( {
  29468. name: 'mx_trilerp_1',
  29469. type: 'vec3',
  29470. inputs: [
  29471. { name: 'v0', type: 'vec3' },
  29472. { name: 'v1', type: 'vec3' },
  29473. { name: 'v2', type: 'vec3' },
  29474. { name: 'v3', type: 'vec3' },
  29475. { name: 'v4', type: 'vec3' },
  29476. { name: 'v5', type: 'vec3' },
  29477. { name: 'v6', type: 'vec3' },
  29478. { name: 'v7', type: 'vec3' },
  29479. { name: 's', type: 'float' },
  29480. { name: 't', type: 'float' },
  29481. { name: 'r', type: 'float' }
  29482. ]
  29483. } );
  29484. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  29485. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  29486. const y = float( y_immutable ).toVar();
  29487. const x = float( x_immutable ).toVar();
  29488. const hash = uint( hash_immutable ).toVar();
  29489. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  29490. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  29491. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  29492. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  29493. } ).setLayout( {
  29494. name: 'mx_gradient_float_0',
  29495. type: 'float',
  29496. inputs: [
  29497. { name: 'hash', type: 'uint' },
  29498. { name: 'x', type: 'float' },
  29499. { name: 'y', type: 'float' }
  29500. ]
  29501. } );
  29502. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  29503. const z = float( z_immutable ).toVar();
  29504. const y = float( y_immutable ).toVar();
  29505. const x = float( x_immutable ).toVar();
  29506. const hash = uint( hash_immutable ).toVar();
  29507. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  29508. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  29509. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  29510. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  29511. } ).setLayout( {
  29512. name: 'mx_gradient_float_1',
  29513. type: 'float',
  29514. inputs: [
  29515. { name: 'hash', type: 'uint' },
  29516. { name: 'x', type: 'float' },
  29517. { name: 'y', type: 'float' },
  29518. { name: 'z', type: 'float' }
  29519. ]
  29520. } );
  29521. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  29522. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  29523. const y = float( y_immutable ).toVar();
  29524. const x = float( x_immutable ).toVar();
  29525. const hash = uvec3( hash_immutable ).toVar();
  29526. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  29527. } ).setLayout( {
  29528. name: 'mx_gradient_vec3_0',
  29529. type: 'vec3',
  29530. inputs: [
  29531. { name: 'hash', type: 'uvec3' },
  29532. { name: 'x', type: 'float' },
  29533. { name: 'y', type: 'float' }
  29534. ]
  29535. } );
  29536. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  29537. const z = float( z_immutable ).toVar();
  29538. const y = float( y_immutable ).toVar();
  29539. const x = float( x_immutable ).toVar();
  29540. const hash = uvec3( hash_immutable ).toVar();
  29541. 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 ) );
  29542. } ).setLayout( {
  29543. name: 'mx_gradient_vec3_1',
  29544. type: 'vec3',
  29545. inputs: [
  29546. { name: 'hash', type: 'uvec3' },
  29547. { name: 'x', type: 'float' },
  29548. { name: 'y', type: 'float' },
  29549. { name: 'z', type: 'float' }
  29550. ]
  29551. } );
  29552. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  29553. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  29554. const v = float( v_immutable ).toVar();
  29555. return mul( 0.6616, v );
  29556. } ).setLayout( {
  29557. name: 'mx_gradient_scale2d_0',
  29558. type: 'float',
  29559. inputs: [
  29560. { name: 'v', type: 'float' }
  29561. ]
  29562. } );
  29563. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  29564. const v = float( v_immutable ).toVar();
  29565. return mul( 0.9820, v );
  29566. } ).setLayout( {
  29567. name: 'mx_gradient_scale3d_0',
  29568. type: 'float',
  29569. inputs: [
  29570. { name: 'v', type: 'float' }
  29571. ]
  29572. } );
  29573. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  29574. const v = vec3( v_immutable ).toVar();
  29575. return mul( 0.6616, v );
  29576. } ).setLayout( {
  29577. name: 'mx_gradient_scale2d_1',
  29578. type: 'vec3',
  29579. inputs: [
  29580. { name: 'v', type: 'vec3' }
  29581. ]
  29582. } );
  29583. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  29584. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  29585. const v = vec3( v_immutable ).toVar();
  29586. return mul( 0.9820, v );
  29587. } ).setLayout( {
  29588. name: 'mx_gradient_scale3d_1',
  29589. type: 'vec3',
  29590. inputs: [
  29591. { name: 'v', type: 'vec3' }
  29592. ]
  29593. } );
  29594. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  29595. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  29596. const k = int( k_immutable ).toVar();
  29597. const x = uint( x_immutable ).toVar();
  29598. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  29599. } ).setLayout( {
  29600. name: 'mx_rotl32',
  29601. type: 'uint',
  29602. inputs: [
  29603. { name: 'x', type: 'uint' },
  29604. { name: 'k', type: 'int' }
  29605. ]
  29606. } );
  29607. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  29608. a.subAssign( c );
  29609. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  29610. c.addAssign( b );
  29611. b.subAssign( a );
  29612. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  29613. a.addAssign( c );
  29614. c.subAssign( b );
  29615. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  29616. b.addAssign( a );
  29617. a.subAssign( c );
  29618. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  29619. c.addAssign( b );
  29620. b.subAssign( a );
  29621. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  29622. a.addAssign( c );
  29623. c.subAssign( b );
  29624. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  29625. b.addAssign( a );
  29626. } );
  29627. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  29628. const c = uint( c_immutable ).toVar();
  29629. const b = uint( b_immutable ).toVar();
  29630. const a = uint( a_immutable ).toVar();
  29631. c.bitXorAssign( b );
  29632. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  29633. a.bitXorAssign( c );
  29634. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  29635. b.bitXorAssign( a );
  29636. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  29637. c.bitXorAssign( b );
  29638. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  29639. a.bitXorAssign( c );
  29640. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  29641. b.bitXorAssign( a );
  29642. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  29643. c.bitXorAssign( b );
  29644. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  29645. return c;
  29646. } ).setLayout( {
  29647. name: 'mx_bjfinal',
  29648. type: 'uint',
  29649. inputs: [
  29650. { name: 'a', type: 'uint' },
  29651. { name: 'b', type: 'uint' },
  29652. { name: 'c', type: 'uint' }
  29653. ]
  29654. } );
  29655. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  29656. const bits = uint( bits_immutable ).toVar();
  29657. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  29658. } ).setLayout( {
  29659. name: 'mx_bits_to_01',
  29660. type: 'float',
  29661. inputs: [
  29662. { name: 'bits', type: 'uint' }
  29663. ]
  29664. } );
  29665. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  29666. const t = float( t_immutable ).toVar();
  29667. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  29668. } ).setLayout( {
  29669. name: 'mx_fade',
  29670. type: 'float',
  29671. inputs: [
  29672. { name: 't', type: 'float' }
  29673. ]
  29674. } );
  29675. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  29676. const x = int( x_immutable ).toVar();
  29677. const len = uint( uint( 1 ) ).toVar();
  29678. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  29679. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  29680. } ).setLayout( {
  29681. name: 'mx_hash_int_0',
  29682. type: 'uint',
  29683. inputs: [
  29684. { name: 'x', type: 'int' }
  29685. ]
  29686. } );
  29687. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  29688. const y = int( y_immutable ).toVar();
  29689. const x = int( x_immutable ).toVar();
  29690. const len = uint( uint( 2 ) ).toVar();
  29691. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29692. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29693. a.addAssign( uint( x ) );
  29694. b.addAssign( uint( y ) );
  29695. return mx_bjfinal( a, b, c );
  29696. } ).setLayout( {
  29697. name: 'mx_hash_int_1',
  29698. type: 'uint',
  29699. inputs: [
  29700. { name: 'x', type: 'int' },
  29701. { name: 'y', type: 'int' }
  29702. ]
  29703. } );
  29704. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  29705. const z = int( z_immutable ).toVar();
  29706. const y = int( y_immutable ).toVar();
  29707. const x = int( x_immutable ).toVar();
  29708. const len = uint( uint( 3 ) ).toVar();
  29709. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29710. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29711. a.addAssign( uint( x ) );
  29712. b.addAssign( uint( y ) );
  29713. c.addAssign( uint( z ) );
  29714. return mx_bjfinal( a, b, c );
  29715. } ).setLayout( {
  29716. name: 'mx_hash_int_2',
  29717. type: 'uint',
  29718. inputs: [
  29719. { name: 'x', type: 'int' },
  29720. { name: 'y', type: 'int' },
  29721. { name: 'z', type: 'int' }
  29722. ]
  29723. } );
  29724. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  29725. const xx = int( xx_immutable ).toVar();
  29726. const z = int( z_immutable ).toVar();
  29727. const y = int( y_immutable ).toVar();
  29728. const x = int( x_immutable ).toVar();
  29729. const len = uint( uint( 4 ) ).toVar();
  29730. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29731. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29732. a.addAssign( uint( x ) );
  29733. b.addAssign( uint( y ) );
  29734. c.addAssign( uint( z ) );
  29735. mx_bjmix( a, b, c );
  29736. a.addAssign( uint( xx ) );
  29737. return mx_bjfinal( a, b, c );
  29738. } ).setLayout( {
  29739. name: 'mx_hash_int_3',
  29740. type: 'uint',
  29741. inputs: [
  29742. { name: 'x', type: 'int' },
  29743. { name: 'y', type: 'int' },
  29744. { name: 'z', type: 'int' },
  29745. { name: 'xx', type: 'int' }
  29746. ]
  29747. } );
  29748. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  29749. const yy = int( yy_immutable ).toVar();
  29750. const xx = int( xx_immutable ).toVar();
  29751. const z = int( z_immutable ).toVar();
  29752. const y = int( y_immutable ).toVar();
  29753. const x = int( x_immutable ).toVar();
  29754. const len = uint( uint( 5 ) ).toVar();
  29755. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29756. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29757. a.addAssign( uint( x ) );
  29758. b.addAssign( uint( y ) );
  29759. c.addAssign( uint( z ) );
  29760. mx_bjmix( a, b, c );
  29761. a.addAssign( uint( xx ) );
  29762. b.addAssign( uint( yy ) );
  29763. return mx_bjfinal( a, b, c );
  29764. } ).setLayout( {
  29765. name: 'mx_hash_int_4',
  29766. type: 'uint',
  29767. inputs: [
  29768. { name: 'x', type: 'int' },
  29769. { name: 'y', type: 'int' },
  29770. { name: 'z', type: 'int' },
  29771. { name: 'xx', type: 'int' },
  29772. { name: 'yy', type: 'int' }
  29773. ]
  29774. } );
  29775. 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 ] );
  29776. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  29777. const y = int( y_immutable ).toVar();
  29778. const x = int( x_immutable ).toVar();
  29779. const h = uint( mx_hash_int( x, y ) ).toVar();
  29780. const result = uvec3().toVar();
  29781. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  29782. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  29783. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  29784. return result;
  29785. } ).setLayout( {
  29786. name: 'mx_hash_vec3_0',
  29787. type: 'uvec3',
  29788. inputs: [
  29789. { name: 'x', type: 'int' },
  29790. { name: 'y', type: 'int' }
  29791. ]
  29792. } );
  29793. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  29794. const z = int( z_immutable ).toVar();
  29795. const y = int( y_immutable ).toVar();
  29796. const x = int( x_immutable ).toVar();
  29797. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  29798. const result = uvec3().toVar();
  29799. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  29800. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  29801. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  29802. return result;
  29803. } ).setLayout( {
  29804. name: 'mx_hash_vec3_1',
  29805. type: 'uvec3',
  29806. inputs: [
  29807. { name: 'x', type: 'int' },
  29808. { name: 'y', type: 'int' },
  29809. { name: 'z', type: 'int' }
  29810. ]
  29811. } );
  29812. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  29813. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29814. const p = vec2( p_immutable ).toVar();
  29815. const X = int().toVar(), Y = int().toVar();
  29816. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29817. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29818. const u = float( mx_fade( fx ) ).toVar();
  29819. const v = float( mx_fade( fy ) ).toVar();
  29820. 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();
  29821. return mx_gradient_scale2d( result );
  29822. } ).setLayout( {
  29823. name: 'mx_perlin_noise_float_0',
  29824. type: 'float',
  29825. inputs: [
  29826. { name: 'p', type: 'vec2' }
  29827. ]
  29828. } );
  29829. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29830. const p = vec3( p_immutable ).toVar();
  29831. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29832. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29833. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29834. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  29835. const u = float( mx_fade( fx ) ).toVar();
  29836. const v = float( mx_fade( fy ) ).toVar();
  29837. const w = float( mx_fade( fz ) ).toVar();
  29838. 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();
  29839. return mx_gradient_scale3d( result );
  29840. } ).setLayout( {
  29841. name: 'mx_perlin_noise_float_1',
  29842. type: 'float',
  29843. inputs: [
  29844. { name: 'p', type: 'vec3' }
  29845. ]
  29846. } );
  29847. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  29848. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29849. const p = vec2( p_immutable ).toVar();
  29850. const X = int().toVar(), Y = int().toVar();
  29851. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29852. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29853. const u = float( mx_fade( fx ) ).toVar();
  29854. const v = float( mx_fade( fy ) ).toVar();
  29855. 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();
  29856. return mx_gradient_scale2d( result );
  29857. } ).setLayout( {
  29858. name: 'mx_perlin_noise_vec3_0',
  29859. type: 'vec3',
  29860. inputs: [
  29861. { name: 'p', type: 'vec2' }
  29862. ]
  29863. } );
  29864. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29865. const p = vec3( p_immutable ).toVar();
  29866. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29867. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29868. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29869. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  29870. const u = float( mx_fade( fx ) ).toVar();
  29871. const v = float( mx_fade( fy ) ).toVar();
  29872. const w = float( mx_fade( fz ) ).toVar();
  29873. 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();
  29874. return mx_gradient_scale3d( result );
  29875. } ).setLayout( {
  29876. name: 'mx_perlin_noise_vec3_1',
  29877. type: 'vec3',
  29878. inputs: [
  29879. { name: 'p', type: 'vec3' }
  29880. ]
  29881. } );
  29882. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  29883. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29884. const p = float( p_immutable ).toVar();
  29885. const ix = int( mx_floor( p ) ).toVar();
  29886. return mx_bits_to_01( mx_hash_int( ix ) );
  29887. } ).setLayout( {
  29888. name: 'mx_cell_noise_float_0',
  29889. type: 'float',
  29890. inputs: [
  29891. { name: 'p', type: 'float' }
  29892. ]
  29893. } );
  29894. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29895. const p = vec2( p_immutable ).toVar();
  29896. const ix = int( mx_floor( p.x ) ).toVar();
  29897. const iy = int( mx_floor( p.y ) ).toVar();
  29898. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  29899. } ).setLayout( {
  29900. name: 'mx_cell_noise_float_1',
  29901. type: 'float',
  29902. inputs: [
  29903. { name: 'p', type: 'vec2' }
  29904. ]
  29905. } );
  29906. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29907. const p = vec3( p_immutable ).toVar();
  29908. const ix = int( mx_floor( p.x ) ).toVar();
  29909. const iy = int( mx_floor( p.y ) ).toVar();
  29910. const iz = int( mx_floor( p.z ) ).toVar();
  29911. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  29912. } ).setLayout( {
  29913. name: 'mx_cell_noise_float_2',
  29914. type: 'float',
  29915. inputs: [
  29916. { name: 'p', type: 'vec3' }
  29917. ]
  29918. } );
  29919. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29920. const p = vec4( p_immutable ).toVar();
  29921. const ix = int( mx_floor( p.x ) ).toVar();
  29922. const iy = int( mx_floor( p.y ) ).toVar();
  29923. const iz = int( mx_floor( p.z ) ).toVar();
  29924. const iw = int( mx_floor( p.w ) ).toVar();
  29925. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  29926. } ).setLayout( {
  29927. name: 'mx_cell_noise_float_3',
  29928. type: 'float',
  29929. inputs: [
  29930. { name: 'p', type: 'vec4' }
  29931. ]
  29932. } );
  29933. 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 ] );
  29934. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29935. const p = float( p_immutable ).toVar();
  29936. const ix = int( mx_floor( p ) ).toVar();
  29937. 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 ) ) ) );
  29938. } ).setLayout( {
  29939. name: 'mx_cell_noise_vec3_0',
  29940. type: 'vec3',
  29941. inputs: [
  29942. { name: 'p', type: 'float' }
  29943. ]
  29944. } );
  29945. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29946. const p = vec2( p_immutable ).toVar();
  29947. const ix = int( mx_floor( p.x ) ).toVar();
  29948. const iy = int( mx_floor( p.y ) ).toVar();
  29949. 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 ) ) ) );
  29950. } ).setLayout( {
  29951. name: 'mx_cell_noise_vec3_1',
  29952. type: 'vec3',
  29953. inputs: [
  29954. { name: 'p', type: 'vec2' }
  29955. ]
  29956. } );
  29957. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29958. const p = vec3( p_immutable ).toVar();
  29959. const ix = int( mx_floor( p.x ) ).toVar();
  29960. const iy = int( mx_floor( p.y ) ).toVar();
  29961. const iz = int( mx_floor( p.z ) ).toVar();
  29962. 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 ) ) ) );
  29963. } ).setLayout( {
  29964. name: 'mx_cell_noise_vec3_2',
  29965. type: 'vec3',
  29966. inputs: [
  29967. { name: 'p', type: 'vec3' }
  29968. ]
  29969. } );
  29970. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29971. const p = vec4( p_immutable ).toVar();
  29972. const ix = int( mx_floor( p.x ) ).toVar();
  29973. const iy = int( mx_floor( p.y ) ).toVar();
  29974. const iz = int( mx_floor( p.z ) ).toVar();
  29975. const iw = int( mx_floor( p.w ) ).toVar();
  29976. 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 ) ) ) );
  29977. } ).setLayout( {
  29978. name: 'mx_cell_noise_vec3_3',
  29979. type: 'vec3',
  29980. inputs: [
  29981. { name: 'p', type: 'vec4' }
  29982. ]
  29983. } );
  29984. 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 ] );
  29985. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29986. const diminish = float( diminish_immutable ).toVar();
  29987. const lacunarity = float( lacunarity_immutable ).toVar();
  29988. const octaves = int( octaves_immutable ).toVar();
  29989. const p = vec3( p_immutable ).toVar();
  29990. const result = float( 0.0 ).toVar();
  29991. const amplitude = float( 1.0 ).toVar();
  29992. Loop( octaves, () => {
  29993. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  29994. amplitude.mulAssign( diminish );
  29995. p.mulAssign( lacunarity );
  29996. } );
  29997. return result;
  29998. } ).setLayout( {
  29999. name: 'mx_fractal_noise_float',
  30000. type: 'float',
  30001. inputs: [
  30002. { name: 'p', type: 'vec3' },
  30003. { name: 'octaves', type: 'int' },
  30004. { name: 'lacunarity', type: 'float' },
  30005. { name: 'diminish', type: 'float' }
  30006. ]
  30007. } );
  30008. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30009. const diminish = float( diminish_immutable ).toVar();
  30010. const lacunarity = float( lacunarity_immutable ).toVar();
  30011. const octaves = int( octaves_immutable ).toVar();
  30012. const p = vec3( p_immutable ).toVar();
  30013. const result = vec3( 0.0 ).toVar();
  30014. const amplitude = float( 1.0 ).toVar();
  30015. Loop( octaves, () => {
  30016. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  30017. amplitude.mulAssign( diminish );
  30018. p.mulAssign( lacunarity );
  30019. } );
  30020. return result;
  30021. } ).setLayout( {
  30022. name: 'mx_fractal_noise_vec3',
  30023. type: 'vec3',
  30024. inputs: [
  30025. { name: 'p', type: 'vec3' },
  30026. { name: 'octaves', type: 'int' },
  30027. { name: 'lacunarity', type: 'float' },
  30028. { name: 'diminish', type: 'float' }
  30029. ]
  30030. } );
  30031. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30032. const diminish = float( diminish_immutable ).toVar();
  30033. const lacunarity = float( lacunarity_immutable ).toVar();
  30034. const octaves = int( octaves_immutable ).toVar();
  30035. const p = vec3( p_immutable ).toVar();
  30036. 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 ) );
  30037. } ).setLayout( {
  30038. name: 'mx_fractal_noise_vec2',
  30039. type: 'vec2',
  30040. inputs: [
  30041. { name: 'p', type: 'vec3' },
  30042. { name: 'octaves', type: 'int' },
  30043. { name: 'lacunarity', type: 'float' },
  30044. { name: 'diminish', type: 'float' }
  30045. ]
  30046. } );
  30047. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30048. const diminish = float( diminish_immutable ).toVar();
  30049. const lacunarity = float( lacunarity_immutable ).toVar();
  30050. const octaves = int( octaves_immutable ).toVar();
  30051. const p = vec3( p_immutable ).toVar();
  30052. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  30053. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  30054. return vec4( c, f );
  30055. } ).setLayout( {
  30056. name: 'mx_fractal_noise_vec4',
  30057. type: 'vec4',
  30058. inputs: [
  30059. { name: 'p', type: 'vec3' },
  30060. { name: 'octaves', type: 'int' },
  30061. { name: 'lacunarity', type: 'float' },
  30062. { name: 'diminish', type: 'float' }
  30063. ]
  30064. } );
  30065. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  30066. const metric = int( metric_immutable ).toVar();
  30067. const jitter = float( jitter_immutable ).toVar();
  30068. const yoff = int( yoff_immutable ).toVar();
  30069. const xoff = int( xoff_immutable ).toVar();
  30070. const y = int( y_immutable ).toVar();
  30071. const x = int( x_immutable ).toVar();
  30072. const p = vec2( p_immutable ).toVar();
  30073. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  30074. const off = vec2( tmp.x, tmp.y ).toVar();
  30075. off.subAssign( 0.5 );
  30076. off.mulAssign( jitter );
  30077. off.addAssign( 0.5 );
  30078. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  30079. const diff = vec2( cellpos.sub( p ) ).toVar();
  30080. If( metric.equal( int( 2 ) ), () => {
  30081. return abs( diff.x ).add( abs( diff.y ) );
  30082. } );
  30083. If( metric.equal( int( 3 ) ), () => {
  30084. return max$1( abs( diff.x ), abs( diff.y ) );
  30085. } );
  30086. return dot( diff, diff );
  30087. } ).setLayout( {
  30088. name: 'mx_worley_distance_0',
  30089. type: 'float',
  30090. inputs: [
  30091. { name: 'p', type: 'vec2' },
  30092. { name: 'x', type: 'int' },
  30093. { name: 'y', type: 'int' },
  30094. { name: 'xoff', type: 'int' },
  30095. { name: 'yoff', type: 'int' },
  30096. { name: 'jitter', type: 'float' },
  30097. { name: 'metric', type: 'int' }
  30098. ]
  30099. } );
  30100. 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 ] ) => {
  30101. const metric = int( metric_immutable ).toVar();
  30102. const jitter = float( jitter_immutable ).toVar();
  30103. const zoff = int( zoff_immutable ).toVar();
  30104. const yoff = int( yoff_immutable ).toVar();
  30105. const xoff = int( xoff_immutable ).toVar();
  30106. const z = int( z_immutable ).toVar();
  30107. const y = int( y_immutable ).toVar();
  30108. const x = int( x_immutable ).toVar();
  30109. const p = vec3( p_immutable ).toVar();
  30110. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  30111. off.subAssign( 0.5 );
  30112. off.mulAssign( jitter );
  30113. off.addAssign( 0.5 );
  30114. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  30115. const diff = vec3( cellpos.sub( p ) ).toVar();
  30116. If( metric.equal( int( 2 ) ), () => {
  30117. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  30118. } );
  30119. If( metric.equal( int( 3 ) ), () => {
  30120. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  30121. } );
  30122. return dot( diff, diff );
  30123. } ).setLayout( {
  30124. name: 'mx_worley_distance_1',
  30125. type: 'float',
  30126. inputs: [
  30127. { name: 'p', type: 'vec3' },
  30128. { name: 'x', type: 'int' },
  30129. { name: 'y', type: 'int' },
  30130. { name: 'z', type: 'int' },
  30131. { name: 'xoff', type: 'int' },
  30132. { name: 'yoff', type: 'int' },
  30133. { name: 'zoff', type: 'int' },
  30134. { name: 'jitter', type: 'float' },
  30135. { name: 'metric', type: 'int' }
  30136. ]
  30137. } );
  30138. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  30139. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30140. const metric = int( metric_immutable ).toVar();
  30141. const jitter = float( jitter_immutable ).toVar();
  30142. const p = vec2( p_immutable ).toVar();
  30143. const X = int().toVar(), Y = int().toVar();
  30144. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  30145. const sqdist = float( 1e6 ).toVar();
  30146. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30147. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30148. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  30149. sqdist.assign( min$1( sqdist, dist ) );
  30150. } );
  30151. } );
  30152. If( metric.equal( int( 0 ) ), () => {
  30153. sqdist.assign( sqrt( sqdist ) );
  30154. } );
  30155. return sqdist;
  30156. } ).setLayout( {
  30157. name: 'mx_worley_noise_float_0',
  30158. type: 'float',
  30159. inputs: [
  30160. { name: 'p', type: 'vec2' },
  30161. { name: 'jitter', type: 'float' },
  30162. { name: 'metric', type: 'int' }
  30163. ]
  30164. } );
  30165. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30166. const metric = int( metric_immutable ).toVar();
  30167. const jitter = float( jitter_immutable ).toVar();
  30168. const p = vec2( p_immutable ).toVar();
  30169. const X = int().toVar(), Y = int().toVar();
  30170. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  30171. const sqdist = vec2( 1e6, 1e6 ).toVar();
  30172. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30173. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30174. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  30175. If( dist.lessThan( sqdist.x ), () => {
  30176. sqdist.y.assign( sqdist.x );
  30177. sqdist.x.assign( dist );
  30178. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  30179. sqdist.y.assign( dist );
  30180. } );
  30181. } );
  30182. } );
  30183. If( metric.equal( int( 0 ) ), () => {
  30184. sqdist.assign( sqrt( sqdist ) );
  30185. } );
  30186. return sqdist;
  30187. } ).setLayout( {
  30188. name: 'mx_worley_noise_vec2_0',
  30189. type: 'vec2',
  30190. inputs: [
  30191. { name: 'p', type: 'vec2' },
  30192. { name: 'jitter', type: 'float' },
  30193. { name: 'metric', type: 'int' }
  30194. ]
  30195. } );
  30196. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30197. const metric = int( metric_immutable ).toVar();
  30198. const jitter = float( jitter_immutable ).toVar();
  30199. const p = vec2( p_immutable ).toVar();
  30200. const X = int().toVar(), Y = int().toVar();
  30201. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  30202. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  30203. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30204. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30205. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  30206. If( dist.lessThan( sqdist.x ), () => {
  30207. sqdist.z.assign( sqdist.y );
  30208. sqdist.y.assign( sqdist.x );
  30209. sqdist.x.assign( dist );
  30210. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  30211. sqdist.z.assign( sqdist.y );
  30212. sqdist.y.assign( dist );
  30213. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  30214. sqdist.z.assign( dist );
  30215. } );
  30216. } );
  30217. } );
  30218. If( metric.equal( int( 0 ) ), () => {
  30219. sqdist.assign( sqrt( sqdist ) );
  30220. } );
  30221. return sqdist;
  30222. } ).setLayout( {
  30223. name: 'mx_worley_noise_vec3_0',
  30224. type: 'vec3',
  30225. inputs: [
  30226. { name: 'p', type: 'vec2' },
  30227. { name: 'jitter', type: 'float' },
  30228. { name: 'metric', type: 'int' }
  30229. ]
  30230. } );
  30231. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30232. const metric = int( metric_immutable ).toVar();
  30233. const jitter = float( jitter_immutable ).toVar();
  30234. const p = vec3( p_immutable ).toVar();
  30235. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30236. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  30237. const sqdist = float( 1e6 ).toVar();
  30238. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30239. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30240. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  30241. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  30242. sqdist.assign( min$1( sqdist, dist ) );
  30243. } );
  30244. } );
  30245. } );
  30246. If( metric.equal( int( 0 ) ), () => {
  30247. sqdist.assign( sqrt( sqdist ) );
  30248. } );
  30249. return sqdist;
  30250. } ).setLayout( {
  30251. name: 'mx_worley_noise_float_1',
  30252. type: 'float',
  30253. inputs: [
  30254. { name: 'p', type: 'vec3' },
  30255. { name: 'jitter', type: 'float' },
  30256. { name: 'metric', type: 'int' }
  30257. ]
  30258. } );
  30259. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  30260. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30261. const metric = int( metric_immutable ).toVar();
  30262. const jitter = float( jitter_immutable ).toVar();
  30263. const p = vec3( p_immutable ).toVar();
  30264. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30265. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  30266. const sqdist = vec2( 1e6, 1e6 ).toVar();
  30267. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30268. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30269. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  30270. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  30271. If( dist.lessThan( sqdist.x ), () => {
  30272. sqdist.y.assign( sqdist.x );
  30273. sqdist.x.assign( dist );
  30274. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  30275. sqdist.y.assign( dist );
  30276. } );
  30277. } );
  30278. } );
  30279. } );
  30280. If( metric.equal( int( 0 ) ), () => {
  30281. sqdist.assign( sqrt( sqdist ) );
  30282. } );
  30283. return sqdist;
  30284. } ).setLayout( {
  30285. name: 'mx_worley_noise_vec2_1',
  30286. type: 'vec2',
  30287. inputs: [
  30288. { name: 'p', type: 'vec3' },
  30289. { name: 'jitter', type: 'float' },
  30290. { name: 'metric', type: 'int' }
  30291. ]
  30292. } );
  30293. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  30294. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  30295. const metric = int( metric_immutable ).toVar();
  30296. const jitter = float( jitter_immutable ).toVar();
  30297. const p = vec3( p_immutable ).toVar();
  30298. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30299. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  30300. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  30301. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  30302. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  30303. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  30304. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  30305. If( dist.lessThan( sqdist.x ), () => {
  30306. sqdist.z.assign( sqdist.y );
  30307. sqdist.y.assign( sqdist.x );
  30308. sqdist.x.assign( dist );
  30309. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  30310. sqdist.z.assign( sqdist.y );
  30311. sqdist.y.assign( dist );
  30312. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  30313. sqdist.z.assign( dist );
  30314. } );
  30315. } );
  30316. } );
  30317. } );
  30318. If( metric.equal( int( 0 ) ), () => {
  30319. sqdist.assign( sqrt( sqdist ) );
  30320. } );
  30321. return sqdist;
  30322. } ).setLayout( {
  30323. name: 'mx_worley_noise_vec3_1',
  30324. type: 'vec3',
  30325. inputs: [
  30326. { name: 'p', type: 'vec3' },
  30327. { name: 'jitter', type: 'float' },
  30328. { name: 'metric', type: 'int' }
  30329. ]
  30330. } );
  30331. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  30332. // Unified Noise 2D
  30333. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  30334. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  30335. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  30336. octaves_immutable, lacunarity_immutable, diminish_immutable
  30337. ] ) => {
  30338. const noiseType = int( noiseType_immutable ).toVar();
  30339. const texcoord = vec2( texcoord_immutable ).toVar();
  30340. const freq = vec2( freq_immutable ).toVar();
  30341. const offset = vec2( offset_immutable ).toVar();
  30342. const jitter = float( jitter_immutable ).toVar();
  30343. const outmin = float( outmin_immutable ).toVar();
  30344. const outmax = float( outmax_immutable ).toVar();
  30345. const clampoutput = bool( clampoutput_immutable ).toVar();
  30346. const octaves = int( octaves_immutable ).toVar();
  30347. const lacunarity = float( lacunarity_immutable ).toVar();
  30348. const diminish = float( diminish_immutable ).toVar();
  30349. // Compute input position
  30350. const p = texcoord.mul( freq ).add( offset );
  30351. const result = float( 0.0 ).toVar();
  30352. // Perlin
  30353. If( noiseType.equal( int( 0 ) ), () => {
  30354. result.assign( mx_perlin_noise_vec3( p ) );
  30355. } );
  30356. // Cell
  30357. If( noiseType.equal( int( 1 ) ), () => {
  30358. result.assign( mx_cell_noise_vec3( p ) );
  30359. } );
  30360. // Worley (metric=0 = euclidean)
  30361. If( noiseType.equal( int( 2 ) ), () => {
  30362. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  30363. } );
  30364. // Fractal (use vec3(p, 0.0) for 2D input)
  30365. If( noiseType.equal( int( 3 ) ), () => {
  30366. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  30367. } );
  30368. // Remap output to [outmin, outmax]
  30369. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  30370. // Clamp if requested
  30371. If( clampoutput, () => {
  30372. result.assign( clamp( result, outmin, outmax ) );
  30373. } );
  30374. return result;
  30375. } ).setLayout( {
  30376. name: 'mx_unifiednoise2d',
  30377. type: 'float',
  30378. inputs: [
  30379. { name: 'noiseType', type: 'int' },
  30380. { name: 'texcoord', type: 'vec2' },
  30381. { name: 'freq', type: 'vec2' },
  30382. { name: 'offset', type: 'vec2' },
  30383. { name: 'jitter', type: 'float' },
  30384. { name: 'outmin', type: 'float' },
  30385. { name: 'outmax', type: 'float' },
  30386. { name: 'clampoutput', type: 'bool' },
  30387. { name: 'octaves', type: 'int' },
  30388. { name: 'lacunarity', type: 'float' },
  30389. { name: 'diminish', type: 'float' }
  30390. ]
  30391. } );
  30392. // Unified Noise 3D
  30393. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  30394. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  30395. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  30396. octaves_immutable, lacunarity_immutable, diminish_immutable
  30397. ] ) => {
  30398. const noiseType = int( noiseType_immutable ).toVar();
  30399. const position = vec3( position_immutable ).toVar();
  30400. const freq = vec3( freq_immutable ).toVar();
  30401. const offset = vec3( offset_immutable ).toVar();
  30402. const jitter = float( jitter_immutable ).toVar();
  30403. const outmin = float( outmin_immutable ).toVar();
  30404. const outmax = float( outmax_immutable ).toVar();
  30405. const clampoutput = bool( clampoutput_immutable ).toVar();
  30406. const octaves = int( octaves_immutable ).toVar();
  30407. const lacunarity = float( lacunarity_immutable ).toVar();
  30408. const diminish = float( diminish_immutable ).toVar();
  30409. // Compute input position
  30410. const p = position.mul( freq ).add( offset );
  30411. const result = float( 0.0 ).toVar();
  30412. // Perlin
  30413. If( noiseType.equal( int( 0 ) ), () => {
  30414. result.assign( mx_perlin_noise_vec3( p ) );
  30415. } );
  30416. // Cell
  30417. If( noiseType.equal( int( 1 ) ), () => {
  30418. result.assign( mx_cell_noise_vec3( p ) );
  30419. } );
  30420. // Worley (metric=0 = euclidean)
  30421. If( noiseType.equal( int( 2 ) ), () => {
  30422. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  30423. } );
  30424. // Fractal
  30425. If( noiseType.equal( int( 3 ) ), () => {
  30426. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  30427. } );
  30428. // Remap output to [outmin, outmax]
  30429. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  30430. // Clamp if requested
  30431. If( clampoutput, () => {
  30432. result.assign( clamp( result, outmin, outmax ) );
  30433. } );
  30434. return result;
  30435. } ).setLayout( {
  30436. name: 'mx_unifiednoise3d',
  30437. type: 'float',
  30438. inputs: [
  30439. { name: 'noiseType', type: 'int' },
  30440. { name: 'position', type: 'vec3' },
  30441. { name: 'freq', type: 'vec3' },
  30442. { name: 'offset', type: 'vec3' },
  30443. { name: 'jitter', type: 'float' },
  30444. { name: 'outmin', type: 'float' },
  30445. { name: 'outmax', type: 'float' },
  30446. { name: 'clampoutput', type: 'bool' },
  30447. { name: 'octaves', type: 'int' },
  30448. { name: 'lacunarity', type: 'float' },
  30449. { name: 'diminish', type: 'float' }
  30450. ]
  30451. } );
  30452. // Three.js Transpiler
  30453. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  30454. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  30455. const s = hsv.y;
  30456. const v = hsv.z;
  30457. const result = vec3().toVar();
  30458. If( s.lessThan( 0.0001 ), () => {
  30459. result.assign( vec3( v, v, v ) );
  30460. } ).Else( () => {
  30461. let h = hsv.x;
  30462. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  30463. const hi = int( trunc( h ) );
  30464. const f = h.sub( float( hi ) );
  30465. const p = v.mul( s.oneMinus() );
  30466. const q = v.mul( s.mul( f ).oneMinus() );
  30467. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  30468. If( hi.equal( int( 0 ) ), () => {
  30469. result.assign( vec3( v, t, p ) );
  30470. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  30471. result.assign( vec3( q, v, p ) );
  30472. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  30473. result.assign( vec3( p, v, t ) );
  30474. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  30475. result.assign( vec3( p, q, v ) );
  30476. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  30477. result.assign( vec3( t, p, v ) );
  30478. } ).Else( () => {
  30479. result.assign( vec3( v, p, q ) );
  30480. } );
  30481. } );
  30482. return result;
  30483. } ).setLayout( {
  30484. name: 'mx_hsvtorgb',
  30485. type: 'vec3',
  30486. inputs: [
  30487. { name: 'hsv', type: 'vec3' }
  30488. ]
  30489. } );
  30490. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  30491. const c = vec3( c_immutable ).toVar();
  30492. const r = float( c.x ).toVar();
  30493. const g = float( c.y ).toVar();
  30494. const b = float( c.z ).toVar();
  30495. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  30496. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  30497. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  30498. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  30499. v.assign( maxcomp );
  30500. If( maxcomp.greaterThan( 0.0 ), () => {
  30501. s.assign( delta.div( maxcomp ) );
  30502. } ).Else( () => {
  30503. s.assign( 0.0 );
  30504. } );
  30505. If( s.lessThanEqual( 0.0 ), () => {
  30506. h.assign( 0.0 );
  30507. } ).Else( () => {
  30508. If( r.greaterThanEqual( maxcomp ), () => {
  30509. h.assign( g.sub( b ).div( delta ) );
  30510. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  30511. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  30512. } ).Else( () => {
  30513. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  30514. } );
  30515. h.mulAssign( 1.0 / 6.0 );
  30516. If( h.lessThan( 0.0 ), () => {
  30517. h.addAssign( 1.0 );
  30518. } );
  30519. } );
  30520. return vec3( h, s, v );
  30521. } ).setLayout( {
  30522. name: 'mx_rgbtohsv',
  30523. type: 'vec3',
  30524. inputs: [
  30525. { name: 'c', type: 'vec3' }
  30526. ]
  30527. } );
  30528. // Three.js Transpiler
  30529. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  30530. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  30531. const color = vec3( color_immutable ).toVar();
  30532. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  30533. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  30534. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  30535. return mix( linSeg, powSeg, isAbove );
  30536. } ).setLayout( {
  30537. name: 'mx_srgb_texture_to_lin_rec709',
  30538. type: 'vec3',
  30539. inputs: [
  30540. { name: 'color', type: 'vec3' }
  30541. ]
  30542. } );
  30543. const mx_aastep = ( threshold, value ) => {
  30544. threshold = float( threshold );
  30545. value = float( value );
  30546. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  30547. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  30548. };
  30549. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  30550. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  30551. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  30552. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  30553. const mx_ramp4 = (
  30554. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  30555. ) => {
  30556. const u = texcoord.x.clamp();
  30557. const v = texcoord.y.clamp();
  30558. const top = mix( valuetl, valuetr, u );
  30559. const bottom = mix( valuebl, valuebr, u );
  30560. return mix( top, bottom, v );
  30561. };
  30562. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  30563. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  30564. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  30565. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  30566. const mx_safepower = ( in1, in2 = 1 ) => {
  30567. in1 = float( in1 );
  30568. return in1.abs().pow( in2 ).mul( in1.sign() );
  30569. };
  30570. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  30571. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  30572. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  30573. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  30574. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  30575. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  30576. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  30577. return noise_vec4.mul( amplitude ).add( pivot );
  30578. };
  30579. 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 );
  30580. 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 );
  30581. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  30582. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  30583. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  30584. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  30585. 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 );
  30586. 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 );
  30587. 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 );
  30588. 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 );
  30589. // === Moved from MaterialXLoader.js ===
  30590. // Math ops
  30591. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  30592. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  30593. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  30594. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  30595. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  30596. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  30597. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  30598. const mx_timer = () => time;
  30599. const mx_frame = () => frameId;
  30600. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  30601. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  30602. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  30603. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  30604. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  30605. const mx_separate = ( in1, channelOrOut = null ) => {
  30606. if ( typeof channelOrOut === 'string' ) {
  30607. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  30608. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  30609. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  30610. }
  30611. if ( typeof channelOrOut === 'number' ) {
  30612. return in1.element( channelOrOut );
  30613. }
  30614. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  30615. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  30616. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  30617. }
  30618. return in1;
  30619. };
  30620. const mx_place2d = (
  30621. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  30622. ) => {
  30623. let uv = texcoord;
  30624. if ( pivot ) uv = uv.sub( pivot );
  30625. if ( scale ) uv = uv.mul( scale );
  30626. if ( rotate ) {
  30627. const rad = rotate.mul( Math.PI / 180.0 );
  30628. const cosR = rad.cos();
  30629. const sinR = rad.sin();
  30630. uv = vec2(
  30631. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  30632. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  30633. );
  30634. }
  30635. if ( pivot ) uv = uv.add( pivot );
  30636. if ( offset ) uv = uv.add( offset );
  30637. return uv;
  30638. };
  30639. const mx_rotate2d = ( input, amount ) => {
  30640. input = vec2( input );
  30641. amount = float( amount );
  30642. const radians = amount.mul( Math.PI / 180.0 );
  30643. return rotate( input, radians );
  30644. };
  30645. const mx_rotate3d = ( input, amount, axis ) => {
  30646. input = vec3( input );
  30647. amount = float( amount );
  30648. axis = vec3( axis );
  30649. const radians = amount.mul( Math.PI / 180.0 );
  30650. const nAxis = axis.normalize();
  30651. const cosA = radians.cos();
  30652. const sinA = radians.sin();
  30653. const oneMinusCosA = float( 1 ).sub( cosA );
  30654. const rot =
  30655. input.mul( cosA )
  30656. .add( nAxis.cross( input ).mul( sinA ) )
  30657. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  30658. return rot;
  30659. };
  30660. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  30661. input = vec3( input );
  30662. scale = float( scale );
  30663. return bumpMap( input, scale );
  30664. };
  30665. /**
  30666. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  30667. *
  30668. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  30669. *
  30670. * ```js
  30671. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  30672. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  30673. * ```
  30674. *
  30675. * @tsl
  30676. * @function
  30677. * @param {Node<vec3>} normal - The normal to correct.
  30678. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  30679. * @param {Node<vec3>} cubePos - The cube position.
  30680. * @return {Node<vec3>} The parallax corrected normal.
  30681. */
  30682. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  30683. const nDir = normalize( normal ).toVar();
  30684. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  30685. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  30686. const rbminmax = vec3().toVar();
  30687. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  30688. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  30689. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  30690. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  30691. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  30692. return boxIntersection.sub( cubePos );
  30693. } );
  30694. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  30695. // normal is assumed to have unit length
  30696. const x = normal.x, y = normal.y, z = normal.z;
  30697. // band 0
  30698. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  30699. // band 1
  30700. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  30701. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  30702. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  30703. // band 2
  30704. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  30705. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  30706. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  30707. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  30708. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  30709. return result;
  30710. } );
  30711. // constants
  30712. var TSL = /*#__PURE__*/Object.freeze({
  30713. __proto__: null,
  30714. BRDF_GGX: BRDF_GGX,
  30715. BRDF_Lambert: BRDF_Lambert,
  30716. BasicPointShadowFilter: BasicPointShadowFilter,
  30717. BasicShadowFilter: BasicShadowFilter,
  30718. Break: Break,
  30719. Const: Const,
  30720. Continue: Continue,
  30721. DFGApprox: DFGApprox,
  30722. D_GGX: D_GGX,
  30723. Discard: Discard,
  30724. EPSILON: EPSILON,
  30725. F_Schlick: F_Schlick,
  30726. Fn: Fn,
  30727. INFINITY: INFINITY,
  30728. If: If,
  30729. Loop: Loop,
  30730. NodeAccess: NodeAccess,
  30731. NodeShaderStage: NodeShaderStage,
  30732. NodeType: NodeType,
  30733. NodeUpdateType: NodeUpdateType,
  30734. OnMaterialUpdate: OnMaterialUpdate,
  30735. OnObjectUpdate: OnObjectUpdate,
  30736. PCFShadowFilter: PCFShadowFilter,
  30737. PCFSoftShadowFilter: PCFSoftShadowFilter,
  30738. PI: PI,
  30739. PI2: PI2,
  30740. PointShadowFilter: PointShadowFilter,
  30741. Return: Return,
  30742. Schlick_to_F0: Schlick_to_F0,
  30743. ScriptableNodeResources: ScriptableNodeResources,
  30744. ShaderNode: ShaderNode,
  30745. Stack: Stack,
  30746. Switch: Switch,
  30747. TBNViewMatrix: TBNViewMatrix,
  30748. VSMShadowFilter: VSMShadowFilter,
  30749. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  30750. Var: Var,
  30751. VarIntent: VarIntent,
  30752. abs: abs,
  30753. acesFilmicToneMapping: acesFilmicToneMapping,
  30754. acos: acos,
  30755. add: add,
  30756. addMethodChaining: addMethodChaining,
  30757. addNodeElement: addNodeElement,
  30758. agxToneMapping: agxToneMapping,
  30759. all: all,
  30760. alphaT: alphaT,
  30761. and: and,
  30762. anisotropy: anisotropy,
  30763. anisotropyB: anisotropyB,
  30764. anisotropyT: anisotropyT,
  30765. any: any,
  30766. append: append,
  30767. array: array,
  30768. arrayBuffer: arrayBuffer,
  30769. asin: asin,
  30770. assign: assign,
  30771. atan: atan,
  30772. atan2: atan2,
  30773. atomicAdd: atomicAdd,
  30774. atomicAnd: atomicAnd,
  30775. atomicFunc: atomicFunc,
  30776. atomicLoad: atomicLoad,
  30777. atomicMax: atomicMax,
  30778. atomicMin: atomicMin,
  30779. atomicOr: atomicOr,
  30780. atomicStore: atomicStore,
  30781. atomicSub: atomicSub,
  30782. atomicXor: atomicXor,
  30783. attenuationColor: attenuationColor,
  30784. attenuationDistance: attenuationDistance,
  30785. attribute: attribute,
  30786. attributeArray: attributeArray,
  30787. backgroundBlurriness: backgroundBlurriness,
  30788. backgroundIntensity: backgroundIntensity,
  30789. backgroundRotation: backgroundRotation,
  30790. batch: batch,
  30791. bentNormalView: bentNormalView,
  30792. billboarding: billboarding,
  30793. bitAnd: bitAnd,
  30794. bitNot: bitNot,
  30795. bitOr: bitOr,
  30796. bitXor: bitXor,
  30797. bitangentGeometry: bitangentGeometry,
  30798. bitangentLocal: bitangentLocal,
  30799. bitangentView: bitangentView,
  30800. bitangentWorld: bitangentWorld,
  30801. bitcast: bitcast,
  30802. blendBurn: blendBurn,
  30803. blendColor: blendColor,
  30804. blendDodge: blendDodge,
  30805. blendOverlay: blendOverlay,
  30806. blendScreen: blendScreen,
  30807. blur: blur,
  30808. bool: bool,
  30809. buffer: buffer,
  30810. bufferAttribute: bufferAttribute,
  30811. bumpMap: bumpMap,
  30812. burn: burn,
  30813. bvec2: bvec2,
  30814. bvec3: bvec3,
  30815. bvec4: bvec4,
  30816. bypass: bypass,
  30817. cache: cache,
  30818. call: call,
  30819. cameraFar: cameraFar,
  30820. cameraIndex: cameraIndex,
  30821. cameraNear: cameraNear,
  30822. cameraNormalMatrix: cameraNormalMatrix,
  30823. cameraPosition: cameraPosition,
  30824. cameraProjectionMatrix: cameraProjectionMatrix,
  30825. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  30826. cameraViewMatrix: cameraViewMatrix,
  30827. cameraWorldMatrix: cameraWorldMatrix,
  30828. cbrt: cbrt,
  30829. cdl: cdl,
  30830. ceil: ceil,
  30831. checker: checker,
  30832. cineonToneMapping: cineonToneMapping,
  30833. clamp: clamp,
  30834. clearcoat: clearcoat,
  30835. clearcoatNormalView: clearcoatNormalView,
  30836. clearcoatRoughness: clearcoatRoughness,
  30837. code: code,
  30838. color: color,
  30839. colorSpaceToWorking: colorSpaceToWorking,
  30840. colorToDirection: colorToDirection,
  30841. compute: compute,
  30842. computeKernel: computeKernel,
  30843. computeSkinning: computeSkinning,
  30844. context: context,
  30845. convert: convert,
  30846. convertColorSpace: convertColorSpace,
  30847. convertToTexture: convertToTexture,
  30848. cos: cos,
  30849. cross: cross,
  30850. cubeTexture: cubeTexture,
  30851. cubeTextureBase: cubeTextureBase,
  30852. cubeToUV: cubeToUV,
  30853. dFdx: dFdx,
  30854. dFdy: dFdy,
  30855. dashSize: dashSize,
  30856. debug: debug,
  30857. decrement: decrement,
  30858. decrementBefore: decrementBefore,
  30859. defaultBuildStages: defaultBuildStages,
  30860. defaultShaderStages: defaultShaderStages,
  30861. defined: defined,
  30862. degrees: degrees,
  30863. deltaTime: deltaTime,
  30864. densityFog: densityFog,
  30865. densityFogFactor: densityFogFactor,
  30866. depth: depth,
  30867. depthPass: depthPass,
  30868. determinant: determinant,
  30869. difference: difference,
  30870. diffuseColor: diffuseColor,
  30871. directPointLight: directPointLight,
  30872. directionToColor: directionToColor,
  30873. directionToFaceDirection: directionToFaceDirection,
  30874. dispersion: dispersion,
  30875. distance: distance,
  30876. div: div,
  30877. dodge: dodge,
  30878. dot: dot,
  30879. drawIndex: drawIndex,
  30880. dynamicBufferAttribute: dynamicBufferAttribute,
  30881. element: element,
  30882. emissive: emissive,
  30883. equal: equal,
  30884. equals: equals,
  30885. equirectUV: equirectUV,
  30886. exp: exp,
  30887. exp2: exp2,
  30888. expression: expression,
  30889. faceDirection: faceDirection,
  30890. faceForward: faceForward,
  30891. faceforward: faceforward,
  30892. float: float,
  30893. floor: floor,
  30894. fog: fog,
  30895. fract: fract,
  30896. frameGroup: frameGroup,
  30897. frameId: frameId,
  30898. frontFacing: frontFacing,
  30899. fwidth: fwidth,
  30900. gain: gain,
  30901. gapSize: gapSize,
  30902. getConstNodeType: getConstNodeType,
  30903. getCurrentStack: getCurrentStack,
  30904. getDirection: getDirection,
  30905. getDistanceAttenuation: getDistanceAttenuation,
  30906. getGeometryRoughness: getGeometryRoughness,
  30907. getNormalFromDepth: getNormalFromDepth,
  30908. getParallaxCorrectNormal: getParallaxCorrectNormal,
  30909. getRoughness: getRoughness,
  30910. getScreenPosition: getScreenPosition,
  30911. getShIrradianceAt: getShIrradianceAt,
  30912. getShadowMaterial: getShadowMaterial,
  30913. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  30914. getTextureIndex: getTextureIndex,
  30915. getViewPosition: getViewPosition,
  30916. globalId: globalId,
  30917. glsl: glsl,
  30918. glslFn: glslFn,
  30919. grayscale: grayscale,
  30920. greaterThan: greaterThan,
  30921. greaterThanEqual: greaterThanEqual,
  30922. hash: hash,
  30923. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  30924. highpModelViewMatrix: highpModelViewMatrix,
  30925. hue: hue,
  30926. increment: increment,
  30927. incrementBefore: incrementBefore,
  30928. instance: instance,
  30929. instanceIndex: instanceIndex,
  30930. instancedArray: instancedArray,
  30931. instancedBufferAttribute: instancedBufferAttribute,
  30932. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  30933. instancedMesh: instancedMesh,
  30934. int: int,
  30935. inverse: inverse,
  30936. inverseSqrt: inverseSqrt,
  30937. inversesqrt: inversesqrt,
  30938. invocationLocalIndex: invocationLocalIndex,
  30939. invocationSubgroupIndex: invocationSubgroupIndex,
  30940. ior: ior,
  30941. iridescence: iridescence,
  30942. iridescenceIOR: iridescenceIOR,
  30943. iridescenceThickness: iridescenceThickness,
  30944. ivec2: ivec2,
  30945. ivec3: ivec3,
  30946. ivec4: ivec4,
  30947. js: js,
  30948. label: label,
  30949. length: length,
  30950. lengthSq: lengthSq,
  30951. lessThan: lessThan,
  30952. lessThanEqual: lessThanEqual,
  30953. lightPosition: lightPosition,
  30954. lightProjectionUV: lightProjectionUV,
  30955. lightShadowMatrix: lightShadowMatrix,
  30956. lightTargetDirection: lightTargetDirection,
  30957. lightTargetPosition: lightTargetPosition,
  30958. lightViewPosition: lightViewPosition,
  30959. lightingContext: lightingContext,
  30960. lights: lights,
  30961. linearDepth: linearDepth,
  30962. linearToneMapping: linearToneMapping,
  30963. localId: localId,
  30964. log: log,
  30965. log2: log2,
  30966. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  30967. luminance: luminance,
  30968. mat2: mat2,
  30969. mat3: mat3,
  30970. mat4: mat4,
  30971. matcapUV: matcapUV,
  30972. materialAO: materialAO,
  30973. materialAlphaTest: materialAlphaTest,
  30974. materialAnisotropy: materialAnisotropy,
  30975. materialAnisotropyVector: materialAnisotropyVector,
  30976. materialAttenuationColor: materialAttenuationColor,
  30977. materialAttenuationDistance: materialAttenuationDistance,
  30978. materialClearcoat: materialClearcoat,
  30979. materialClearcoatNormal: materialClearcoatNormal,
  30980. materialClearcoatRoughness: materialClearcoatRoughness,
  30981. materialColor: materialColor,
  30982. materialDispersion: materialDispersion,
  30983. materialEmissive: materialEmissive,
  30984. materialEnvIntensity: materialEnvIntensity,
  30985. materialEnvRotation: materialEnvRotation,
  30986. materialIOR: materialIOR,
  30987. materialIridescence: materialIridescence,
  30988. materialIridescenceIOR: materialIridescenceIOR,
  30989. materialIridescenceThickness: materialIridescenceThickness,
  30990. materialLightMap: materialLightMap,
  30991. materialLineDashOffset: materialLineDashOffset,
  30992. materialLineDashSize: materialLineDashSize,
  30993. materialLineGapSize: materialLineGapSize,
  30994. materialLineScale: materialLineScale,
  30995. materialLineWidth: materialLineWidth,
  30996. materialMetalness: materialMetalness,
  30997. materialNormal: materialNormal,
  30998. materialOpacity: materialOpacity,
  30999. materialPointSize: materialPointSize,
  31000. materialReference: materialReference,
  31001. materialReflectivity: materialReflectivity,
  31002. materialRefractionRatio: materialRefractionRatio,
  31003. materialRotation: materialRotation,
  31004. materialRoughness: materialRoughness,
  31005. materialSheen: materialSheen,
  31006. materialSheenRoughness: materialSheenRoughness,
  31007. materialShininess: materialShininess,
  31008. materialSpecular: materialSpecular,
  31009. materialSpecularColor: materialSpecularColor,
  31010. materialSpecularIntensity: materialSpecularIntensity,
  31011. materialSpecularStrength: materialSpecularStrength,
  31012. materialThickness: materialThickness,
  31013. materialTransmission: materialTransmission,
  31014. max: max$1,
  31015. maxMipLevel: maxMipLevel,
  31016. mediumpModelViewMatrix: mediumpModelViewMatrix,
  31017. metalness: metalness,
  31018. min: min$1,
  31019. mix: mix,
  31020. mixElement: mixElement,
  31021. mod: mod,
  31022. modInt: modInt,
  31023. modelDirection: modelDirection,
  31024. modelNormalMatrix: modelNormalMatrix,
  31025. modelPosition: modelPosition,
  31026. modelRadius: modelRadius,
  31027. modelScale: modelScale,
  31028. modelViewMatrix: modelViewMatrix,
  31029. modelViewPosition: modelViewPosition,
  31030. modelViewProjection: modelViewProjection,
  31031. modelWorldMatrix: modelWorldMatrix,
  31032. modelWorldMatrixInverse: modelWorldMatrixInverse,
  31033. morphReference: morphReference,
  31034. mrt: mrt,
  31035. mul: mul,
  31036. mx_aastep: mx_aastep,
  31037. mx_add: mx_add,
  31038. mx_atan2: mx_atan2,
  31039. mx_cell_noise_float: mx_cell_noise_float,
  31040. mx_contrast: mx_contrast,
  31041. mx_divide: mx_divide,
  31042. mx_fractal_noise_float: mx_fractal_noise_float,
  31043. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  31044. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  31045. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  31046. mx_frame: mx_frame,
  31047. mx_heighttonormal: mx_heighttonormal,
  31048. mx_hsvtorgb: mx_hsvtorgb,
  31049. mx_ifequal: mx_ifequal,
  31050. mx_ifgreater: mx_ifgreater,
  31051. mx_ifgreatereq: mx_ifgreatereq,
  31052. mx_invert: mx_invert,
  31053. mx_modulo: mx_modulo,
  31054. mx_multiply: mx_multiply,
  31055. mx_noise_float: mx_noise_float,
  31056. mx_noise_vec3: mx_noise_vec3,
  31057. mx_noise_vec4: mx_noise_vec4,
  31058. mx_place2d: mx_place2d,
  31059. mx_power: mx_power,
  31060. mx_ramp4: mx_ramp4,
  31061. mx_ramplr: mx_ramplr,
  31062. mx_ramptb: mx_ramptb,
  31063. mx_rgbtohsv: mx_rgbtohsv,
  31064. mx_rotate2d: mx_rotate2d,
  31065. mx_rotate3d: mx_rotate3d,
  31066. mx_safepower: mx_safepower,
  31067. mx_separate: mx_separate,
  31068. mx_splitlr: mx_splitlr,
  31069. mx_splittb: mx_splittb,
  31070. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  31071. mx_subtract: mx_subtract,
  31072. mx_timer: mx_timer,
  31073. mx_transform_uv: mx_transform_uv,
  31074. mx_unifiednoise2d: mx_unifiednoise2d,
  31075. mx_unifiednoise3d: mx_unifiednoise3d,
  31076. mx_worley_noise_float: mx_worley_noise_float,
  31077. mx_worley_noise_vec2: mx_worley_noise_vec2,
  31078. mx_worley_noise_vec3: mx_worley_noise_vec3,
  31079. negate: negate,
  31080. neutralToneMapping: neutralToneMapping,
  31081. nodeArray: nodeArray,
  31082. nodeImmutable: nodeImmutable,
  31083. nodeObject: nodeObject,
  31084. nodeObjectIntent: nodeObjectIntent,
  31085. nodeObjects: nodeObjects,
  31086. nodeProxy: nodeProxy,
  31087. nodeProxyIntent: nodeProxyIntent,
  31088. normalFlat: normalFlat,
  31089. normalGeometry: normalGeometry,
  31090. normalLocal: normalLocal,
  31091. normalMap: normalMap,
  31092. normalView: normalView,
  31093. normalViewGeometry: normalViewGeometry,
  31094. normalWorld: normalWorld,
  31095. normalWorldGeometry: normalWorldGeometry,
  31096. normalize: normalize,
  31097. not: not,
  31098. notEqual: notEqual,
  31099. numWorkgroups: numWorkgroups,
  31100. objectDirection: objectDirection,
  31101. objectGroup: objectGroup,
  31102. objectPosition: objectPosition,
  31103. objectRadius: objectRadius,
  31104. objectScale: objectScale,
  31105. objectViewPosition: objectViewPosition,
  31106. objectWorldMatrix: objectWorldMatrix,
  31107. oneMinus: oneMinus,
  31108. or: or,
  31109. orthographicDepthToViewZ: orthographicDepthToViewZ,
  31110. oscSawtooth: oscSawtooth,
  31111. oscSine: oscSine,
  31112. oscSquare: oscSquare,
  31113. oscTriangle: oscTriangle,
  31114. output: output,
  31115. outputStruct: outputStruct,
  31116. overlay: overlay,
  31117. overloadingFn: overloadingFn,
  31118. parabola: parabola,
  31119. parallaxDirection: parallaxDirection,
  31120. parallaxUV: parallaxUV,
  31121. parameter: parameter,
  31122. pass: pass,
  31123. passTexture: passTexture,
  31124. pcurve: pcurve,
  31125. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  31126. pmremTexture: pmremTexture,
  31127. pointShadow: pointShadow,
  31128. pointUV: pointUV,
  31129. pointWidth: pointWidth,
  31130. positionGeometry: positionGeometry,
  31131. positionLocal: positionLocal,
  31132. positionPrevious: positionPrevious,
  31133. positionView: positionView,
  31134. positionViewDirection: positionViewDirection,
  31135. positionWorld: positionWorld,
  31136. positionWorldDirection: positionWorldDirection,
  31137. posterize: posterize,
  31138. pow: pow,
  31139. pow2: pow2,
  31140. pow3: pow3,
  31141. pow4: pow4,
  31142. premultiplyAlpha: premultiplyAlpha,
  31143. property: property,
  31144. radians: radians,
  31145. rand: rand,
  31146. range: range,
  31147. rangeFog: rangeFog,
  31148. rangeFogFactor: rangeFogFactor,
  31149. reciprocal: reciprocal,
  31150. reference: reference,
  31151. referenceBuffer: referenceBuffer,
  31152. reflect: reflect,
  31153. reflectVector: reflectVector,
  31154. reflectView: reflectView,
  31155. reflector: reflector,
  31156. refract: refract,
  31157. refractVector: refractVector,
  31158. refractView: refractView,
  31159. reinhardToneMapping: reinhardToneMapping,
  31160. remap: remap,
  31161. remapClamp: remapClamp,
  31162. renderGroup: renderGroup,
  31163. renderOutput: renderOutput,
  31164. rendererReference: rendererReference,
  31165. rotate: rotate,
  31166. rotateUV: rotateUV,
  31167. roughness: roughness,
  31168. round: round,
  31169. rtt: rtt,
  31170. sRGBTransferEOTF: sRGBTransferEOTF,
  31171. sRGBTransferOETF: sRGBTransferOETF,
  31172. sample: sample,
  31173. sampler: sampler,
  31174. samplerComparison: samplerComparison,
  31175. saturate: saturate,
  31176. saturation: saturation,
  31177. screen: screen,
  31178. screenCoordinate: screenCoordinate,
  31179. screenSize: screenSize,
  31180. screenUV: screenUV,
  31181. scriptable: scriptable,
  31182. scriptableValue: scriptableValue,
  31183. select: select,
  31184. setCurrentStack: setCurrentStack,
  31185. setName: setName,
  31186. shaderStages: shaderStages,
  31187. shadow: shadow,
  31188. shadowPositionWorld: shadowPositionWorld,
  31189. shapeCircle: shapeCircle,
  31190. sharedUniformGroup: sharedUniformGroup,
  31191. sheen: sheen,
  31192. sheenRoughness: sheenRoughness,
  31193. shiftLeft: shiftLeft,
  31194. shiftRight: shiftRight,
  31195. shininess: shininess,
  31196. sign: sign,
  31197. sin: sin,
  31198. sinc: sinc,
  31199. skinning: skinning,
  31200. smoothstep: smoothstep,
  31201. smoothstepElement: smoothstepElement,
  31202. specularColor: specularColor,
  31203. specularF90: specularF90,
  31204. spherizeUV: spherizeUV,
  31205. split: split,
  31206. spritesheetUV: spritesheetUV,
  31207. sqrt: sqrt,
  31208. stack: stack,
  31209. step: step,
  31210. stepElement: stepElement,
  31211. storage: storage,
  31212. storageBarrier: storageBarrier,
  31213. storageObject: storageObject,
  31214. storageTexture: storageTexture,
  31215. string: string,
  31216. struct: struct,
  31217. sub: sub,
  31218. subBuild: subBuild,
  31219. subgroupIndex: subgroupIndex,
  31220. subgroupSize: subgroupSize,
  31221. tan: tan,
  31222. tangentGeometry: tangentGeometry,
  31223. tangentLocal: tangentLocal,
  31224. tangentView: tangentView,
  31225. tangentWorld: tangentWorld,
  31226. texture: texture,
  31227. texture3D: texture3D,
  31228. textureBarrier: textureBarrier,
  31229. textureBicubic: textureBicubic,
  31230. textureBicubicLevel: textureBicubicLevel,
  31231. textureCubeUV: textureCubeUV,
  31232. textureLoad: textureLoad,
  31233. textureSize: textureSize,
  31234. textureStore: textureStore,
  31235. thickness: thickness,
  31236. time: time,
  31237. toneMapping: toneMapping,
  31238. toneMappingExposure: toneMappingExposure,
  31239. toonOutlinePass: toonOutlinePass,
  31240. transformDirection: transformDirection,
  31241. transformNormal: transformNormal,
  31242. transformNormalToView: transformNormalToView,
  31243. transformedClearcoatNormalView: transformedClearcoatNormalView,
  31244. transformedNormalView: transformedNormalView,
  31245. transformedNormalWorld: transformedNormalWorld,
  31246. transmission: transmission,
  31247. transpose: transpose,
  31248. triNoise3D: triNoise3D,
  31249. triplanarTexture: triplanarTexture,
  31250. triplanarTextures: triplanarTextures,
  31251. trunc: trunc,
  31252. uint: uint,
  31253. uniform: uniform,
  31254. uniformArray: uniformArray,
  31255. uniformCubeTexture: uniformCubeTexture,
  31256. uniformFlow: uniformFlow,
  31257. uniformGroup: uniformGroup,
  31258. uniformTexture: uniformTexture,
  31259. unpremultiplyAlpha: unpremultiplyAlpha,
  31260. userData: userData,
  31261. uv: uv$1,
  31262. uvec2: uvec2,
  31263. uvec3: uvec3,
  31264. uvec4: uvec4,
  31265. varying: varying,
  31266. varyingProperty: varyingProperty,
  31267. vec2: vec2,
  31268. vec3: vec3,
  31269. vec4: vec4,
  31270. vectorComponents: vectorComponents,
  31271. velocity: velocity,
  31272. vertexColor: vertexColor,
  31273. vertexIndex: vertexIndex,
  31274. vertexStage: vertexStage,
  31275. vibrance: vibrance,
  31276. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  31277. viewZToOrthographicDepth: viewZToOrthographicDepth,
  31278. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  31279. viewport: viewport,
  31280. viewportCoordinate: viewportCoordinate,
  31281. viewportDepthTexture: viewportDepthTexture,
  31282. viewportLinearDepth: viewportLinearDepth,
  31283. viewportMipTexture: viewportMipTexture,
  31284. viewportResolution: viewportResolution,
  31285. viewportSafeUV: viewportSafeUV,
  31286. viewportSharedTexture: viewportSharedTexture,
  31287. viewportSize: viewportSize,
  31288. viewportTexture: viewportTexture,
  31289. viewportUV: viewportUV,
  31290. wgsl: wgsl,
  31291. wgslFn: wgslFn,
  31292. workgroupArray: workgroupArray,
  31293. workgroupBarrier: workgroupBarrier,
  31294. workgroupId: workgroupId,
  31295. workingToColorSpace: workingToColorSpace,
  31296. xor: xor
  31297. });
  31298. const _clearColor = /*@__PURE__*/ new Color4();
  31299. /**
  31300. * This renderer module manages the background.
  31301. *
  31302. * @private
  31303. * @augments DataMap
  31304. */
  31305. class Background extends DataMap {
  31306. /**
  31307. * Constructs a new background management component.
  31308. *
  31309. * @param {Renderer} renderer - The renderer.
  31310. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  31311. */
  31312. constructor( renderer, nodes ) {
  31313. super();
  31314. /**
  31315. * The renderer.
  31316. *
  31317. * @type {Renderer}
  31318. */
  31319. this.renderer = renderer;
  31320. /**
  31321. * Renderer component for managing nodes related logic.
  31322. *
  31323. * @type {Nodes}
  31324. */
  31325. this.nodes = nodes;
  31326. }
  31327. /**
  31328. * Updates the background for the given scene. Depending on how `Scene.background`
  31329. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  31330. * or add a mesh to the render list for rendering the background as a textured plane
  31331. * or skybox.
  31332. *
  31333. * @param {Scene} scene - The scene.
  31334. * @param {RenderList} renderList - The current render list.
  31335. * @param {RenderContext} renderContext - The current render context.
  31336. */
  31337. update( scene, renderList, renderContext ) {
  31338. const renderer = this.renderer;
  31339. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  31340. let forceClear = false;
  31341. if ( background === null ) {
  31342. // no background settings, use clear color configuration from the renderer
  31343. renderer._clearColor.getRGB( _clearColor );
  31344. _clearColor.a = renderer._clearColor.a;
  31345. } else if ( background.isColor === true ) {
  31346. // background is an opaque color
  31347. background.getRGB( _clearColor );
  31348. _clearColor.a = 1;
  31349. forceClear = true;
  31350. } else if ( background.isNode === true ) {
  31351. const sceneData = this.get( scene );
  31352. const backgroundNode = background;
  31353. _clearColor.copy( renderer._clearColor );
  31354. let backgroundMesh = sceneData.backgroundMesh;
  31355. if ( backgroundMesh === undefined ) {
  31356. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  31357. // @TODO: Add Texture2D support using node context
  31358. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  31359. getTextureLevel: () => backgroundBlurriness
  31360. } );
  31361. let viewProj = modelViewProjection;
  31362. viewProj = viewProj.setZ( viewProj.w );
  31363. const nodeMaterial = new NodeMaterial();
  31364. nodeMaterial.name = 'Background.material';
  31365. nodeMaterial.side = BackSide;
  31366. nodeMaterial.depthTest = false;
  31367. nodeMaterial.depthWrite = false;
  31368. nodeMaterial.allowOverride = false;
  31369. nodeMaterial.fog = false;
  31370. nodeMaterial.lights = false;
  31371. nodeMaterial.vertexNode = viewProj;
  31372. nodeMaterial.colorNode = backgroundMeshNode;
  31373. sceneData.backgroundMeshNode = backgroundMeshNode;
  31374. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  31375. backgroundMesh.frustumCulled = false;
  31376. backgroundMesh.name = 'Background.mesh';
  31377. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  31378. this.matrixWorld.copyPosition( camera.matrixWorld );
  31379. };
  31380. function onBackgroundDispose() {
  31381. background.removeEventListener( 'dispose', onBackgroundDispose );
  31382. backgroundMesh.material.dispose();
  31383. backgroundMesh.geometry.dispose();
  31384. }
  31385. background.addEventListener( 'dispose', onBackgroundDispose );
  31386. }
  31387. const backgroundCacheKey = backgroundNode.getCacheKey();
  31388. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  31389. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  31390. sceneData.backgroundMeshNode.needsUpdate = true;
  31391. backgroundMesh.material.needsUpdate = true;
  31392. sceneData.backgroundCacheKey = backgroundCacheKey;
  31393. }
  31394. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  31395. } else {
  31396. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  31397. }
  31398. //
  31399. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  31400. if ( environmentBlendMode === 'additive' ) {
  31401. _clearColor.set( 0, 0, 0, 1 );
  31402. } else if ( environmentBlendMode === 'alpha-blend' ) {
  31403. _clearColor.set( 0, 0, 0, 0 );
  31404. }
  31405. //
  31406. if ( renderer.autoClear === true || forceClear === true ) {
  31407. const clearColorValue = renderContext.clearColorValue;
  31408. clearColorValue.r = _clearColor.r;
  31409. clearColorValue.g = _clearColor.g;
  31410. clearColorValue.b = _clearColor.b;
  31411. clearColorValue.a = _clearColor.a;
  31412. // premultiply alpha
  31413. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  31414. clearColorValue.r *= clearColorValue.a;
  31415. clearColorValue.g *= clearColorValue.a;
  31416. clearColorValue.b *= clearColorValue.a;
  31417. }
  31418. //
  31419. renderContext.depthClearValue = renderer._clearDepth;
  31420. renderContext.stencilClearValue = renderer._clearStencil;
  31421. renderContext.clearColor = renderer.autoClearColor === true;
  31422. renderContext.clearDepth = renderer.autoClearDepth === true;
  31423. renderContext.clearStencil = renderer.autoClearStencil === true;
  31424. } else {
  31425. renderContext.clearColor = false;
  31426. renderContext.clearDepth = false;
  31427. renderContext.clearStencil = false;
  31428. }
  31429. }
  31430. }
  31431. let _id$6 = 0;
  31432. /**
  31433. * A bind group represents a collection of bindings and thus a collection
  31434. * or resources. Bind groups are assigned to pipelines to provide them
  31435. * with the required resources (like uniform buffers or textures).
  31436. *
  31437. * @private
  31438. */
  31439. class BindGroup {
  31440. /**
  31441. * Constructs a new bind group.
  31442. *
  31443. * @param {string} name - The bind group's name.
  31444. * @param {Array<Binding>} bindings - An array of bindings.
  31445. * @param {number} index - The group index.
  31446. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  31447. */
  31448. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  31449. /**
  31450. * The bind group's name.
  31451. *
  31452. * @type {string}
  31453. */
  31454. this.name = name;
  31455. /**
  31456. * An array of bindings.
  31457. *
  31458. * @type {Array<Binding>}
  31459. */
  31460. this.bindings = bindings;
  31461. /**
  31462. * The group index.
  31463. *
  31464. * @type {number}
  31465. */
  31466. this.index = index;
  31467. /**
  31468. * An array of reference bindings.
  31469. *
  31470. * @type {Array<Binding>}
  31471. */
  31472. this.bindingsReference = bindingsReference;
  31473. /**
  31474. * The group's ID.
  31475. *
  31476. * @type {number}
  31477. */
  31478. this.id = _id$6 ++;
  31479. }
  31480. }
  31481. /**
  31482. * This module represents the state of a node builder after it was
  31483. * used to build the nodes for a render object. The state holds the
  31484. * results of the build for further processing in the renderer.
  31485. *
  31486. * Render objects with identical cache keys share the same node builder state.
  31487. *
  31488. * @private
  31489. */
  31490. class NodeBuilderState {
  31491. /**
  31492. * Constructs a new node builder state.
  31493. *
  31494. * @param {string} vertexShader - The native vertex shader code.
  31495. * @param {string} fragmentShader - The native fragment shader code.
  31496. * @param {string} computeShader - The native compute shader code.
  31497. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  31498. * @param {Array<BindGroup>} bindings - An array of bind groups.
  31499. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  31500. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  31501. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  31502. * @param {NodeMaterialObserver} observer - A node material observer.
  31503. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  31504. */
  31505. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  31506. /**
  31507. * The native vertex shader code.
  31508. *
  31509. * @type {string}
  31510. */
  31511. this.vertexShader = vertexShader;
  31512. /**
  31513. * The native fragment shader code.
  31514. *
  31515. * @type {string}
  31516. */
  31517. this.fragmentShader = fragmentShader;
  31518. /**
  31519. * The native compute shader code.
  31520. *
  31521. * @type {string}
  31522. */
  31523. this.computeShader = computeShader;
  31524. /**
  31525. * An array with transform attribute objects.
  31526. * Only relevant when using compute shaders with WebGL 2.
  31527. *
  31528. * @type {Array<Object>}
  31529. */
  31530. this.transforms = transforms;
  31531. /**
  31532. * An array of node attributes representing
  31533. * the attributes of the shaders.
  31534. *
  31535. * @type {Array<NodeAttribute>}
  31536. */
  31537. this.nodeAttributes = nodeAttributes;
  31538. /**
  31539. * An array of bind groups representing the uniform or storage
  31540. * buffers, texture or samplers of the shader.
  31541. *
  31542. * @type {Array<BindGroup>}
  31543. */
  31544. this.bindings = bindings;
  31545. /**
  31546. * An array of nodes that implement their `update()` method.
  31547. *
  31548. * @type {Array<Node>}
  31549. */
  31550. this.updateNodes = updateNodes;
  31551. /**
  31552. * An array of nodes that implement their `updateBefore()` method.
  31553. *
  31554. * @type {Array<Node>}
  31555. */
  31556. this.updateBeforeNodes = updateBeforeNodes;
  31557. /**
  31558. * An array of nodes that implement their `updateAfter()` method.
  31559. *
  31560. * @type {Array<Node>}
  31561. */
  31562. this.updateAfterNodes = updateAfterNodes;
  31563. /**
  31564. * A node material observer.
  31565. *
  31566. * @type {NodeMaterialObserver}
  31567. */
  31568. this.observer = observer;
  31569. /**
  31570. * How often this state is used by render objects.
  31571. *
  31572. * @type {number}
  31573. */
  31574. this.usedTimes = 0;
  31575. }
  31576. /**
  31577. * This method is used to create a array of bind groups based
  31578. * on the existing bind groups of this state. Shared groups are
  31579. * not cloned.
  31580. *
  31581. * @return {Array<BindGroup>} A array of bind groups.
  31582. */
  31583. createBindings() {
  31584. const bindings = [];
  31585. for ( const instanceGroup of this.bindings ) {
  31586. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  31587. if ( shared !== true ) {
  31588. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  31589. bindings.push( bindingsGroup );
  31590. for ( const instanceBinding of instanceGroup.bindings ) {
  31591. bindingsGroup.bindings.push( instanceBinding.clone() );
  31592. }
  31593. } else {
  31594. bindings.push( instanceGroup );
  31595. }
  31596. }
  31597. return bindings;
  31598. }
  31599. }
  31600. /**
  31601. * {@link NodeBuilder} is going to create instances of this class during the build process
  31602. * of nodes. They represent the final shader attributes that are going to be generated
  31603. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  31604. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  31605. */
  31606. class NodeAttribute {
  31607. /**
  31608. * Constructs a new node attribute.
  31609. *
  31610. * @param {string} name - The name of the attribute.
  31611. * @param {string} type - The type of the attribute.
  31612. * @param {?Node} node - An optional reference to the node.
  31613. */
  31614. constructor( name, type, node = null ) {
  31615. /**
  31616. * This flag can be used for type testing.
  31617. *
  31618. * @type {boolean}
  31619. * @readonly
  31620. * @default true
  31621. */
  31622. this.isNodeAttribute = true;
  31623. /**
  31624. * The name of the attribute.
  31625. *
  31626. * @type {string}
  31627. */
  31628. this.name = name;
  31629. /**
  31630. * The type of the attribute.
  31631. *
  31632. * @type {string}
  31633. */
  31634. this.type = type;
  31635. /**
  31636. * An optional reference to the node.
  31637. *
  31638. * @type {?Node}
  31639. * @default null
  31640. */
  31641. this.node = node;
  31642. }
  31643. }
  31644. /**
  31645. * {@link NodeBuilder} is going to create instances of this class during the build process
  31646. * of nodes. They represent the final shader uniforms that are going to be generated
  31647. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  31648. * for this purpose.
  31649. */
  31650. class NodeUniform {
  31651. /**
  31652. * Constructs a new node uniform.
  31653. *
  31654. * @param {string} name - The name of the uniform.
  31655. * @param {string} type - The type of the uniform.
  31656. * @param {UniformNode} node - An reference to the node.
  31657. */
  31658. constructor( name, type, node ) {
  31659. /**
  31660. * This flag can be used for type testing.
  31661. *
  31662. * @type {boolean}
  31663. * @readonly
  31664. * @default true
  31665. */
  31666. this.isNodeUniform = true;
  31667. /**
  31668. * The name of the uniform.
  31669. *
  31670. * @type {string}
  31671. */
  31672. this.name = name;
  31673. /**
  31674. * The type of the uniform.
  31675. *
  31676. * @type {string}
  31677. */
  31678. this.type = type;
  31679. /**
  31680. * An reference to the node.
  31681. *
  31682. * @type {UniformNode}
  31683. */
  31684. this.node = node.getSelf();
  31685. }
  31686. /**
  31687. * The value of the uniform node.
  31688. *
  31689. * @type {any}
  31690. */
  31691. get value() {
  31692. return this.node.value;
  31693. }
  31694. set value( val ) {
  31695. this.node.value = val;
  31696. }
  31697. /**
  31698. * The id of the uniform node.
  31699. *
  31700. * @type {number}
  31701. */
  31702. get id() {
  31703. return this.node.id;
  31704. }
  31705. /**
  31706. * The uniform node's group.
  31707. *
  31708. * @type {UniformGroupNode}
  31709. */
  31710. get groupNode() {
  31711. return this.node.groupNode;
  31712. }
  31713. }
  31714. /**
  31715. * {@link NodeBuilder} is going to create instances of this class during the build process
  31716. * of nodes. They represent the final shader variables that are going to be generated
  31717. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  31718. * this purpose.
  31719. */
  31720. class NodeVar {
  31721. /**
  31722. * Constructs a new node variable.
  31723. *
  31724. * @param {string} name - The name of the variable.
  31725. * @param {string} type - The type of the variable.
  31726. * @param {boolean} [readOnly=false] - The read-only flag.
  31727. * @param {?number} [count=null] - The size.
  31728. */
  31729. constructor( name, type, readOnly = false, count = null ) {
  31730. /**
  31731. * This flag can be used for type testing.
  31732. *
  31733. * @type {boolean}
  31734. * @readonly
  31735. * @default true
  31736. */
  31737. this.isNodeVar = true;
  31738. /**
  31739. * The name of the variable.
  31740. *
  31741. * @type {string}
  31742. */
  31743. this.name = name;
  31744. /**
  31745. * The type of the variable.
  31746. *
  31747. * @type {string}
  31748. */
  31749. this.type = type;
  31750. /**
  31751. * The read-only flag.
  31752. *
  31753. * @type {boolean}
  31754. */
  31755. this.readOnly = readOnly;
  31756. /**
  31757. * The size.
  31758. *
  31759. * @type {?number}
  31760. */
  31761. this.count = count;
  31762. }
  31763. }
  31764. /**
  31765. * {@link NodeBuilder} is going to create instances of this class during the build process
  31766. * of nodes. They represent the final shader varyings that are going to be generated
  31767. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  31768. * this purpose.
  31769. *
  31770. * @augments NodeVar
  31771. */
  31772. class NodeVarying extends NodeVar {
  31773. /**
  31774. * Constructs a new node varying.
  31775. *
  31776. * @param {string} name - The name of the varying.
  31777. * @param {string} type - The type of the varying.
  31778. * @param {?string} interpolationType - The interpolation type of the varying.
  31779. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  31780. */
  31781. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  31782. super( name, type );
  31783. /**
  31784. * Whether this varying requires interpolation or not. This property can be used
  31785. * to check if the varying can be optimized for a variable.
  31786. *
  31787. * @type {boolean}
  31788. * @default false
  31789. */
  31790. this.needsInterpolation = false;
  31791. /**
  31792. * This flag can be used for type testing.
  31793. *
  31794. * @type {boolean}
  31795. * @readonly
  31796. * @default true
  31797. */
  31798. this.isNodeVarying = true;
  31799. /**
  31800. * The interpolation type of the varying data.
  31801. *
  31802. * @type {?string}
  31803. * @default null
  31804. */
  31805. this.interpolationType = interpolationType;
  31806. /**
  31807. * The interpolation sampling type of varying data.
  31808. *
  31809. * @type {?string}
  31810. * @default null
  31811. */
  31812. this.interpolationSampling = interpolationSampling;
  31813. }
  31814. }
  31815. /**
  31816. * {@link NodeBuilder} is going to create instances of this class during the build process
  31817. * of nodes. They represent user-defined, native shader code portions that are going to be
  31818. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  31819. * for this purpose.
  31820. */
  31821. class NodeCode {
  31822. /**
  31823. * Constructs a new code node.
  31824. *
  31825. * @param {string} name - The name of the code.
  31826. * @param {string} type - The node type.
  31827. * @param {string} [code=''] - The native shader code.
  31828. */
  31829. constructor( name, type, code = '' ) {
  31830. /**
  31831. * The name of the code.
  31832. *
  31833. * @type {string}
  31834. */
  31835. this.name = name;
  31836. /**
  31837. * The node type.
  31838. *
  31839. * @type {string}
  31840. */
  31841. this.type = type;
  31842. /**
  31843. * The native shader code.
  31844. *
  31845. * @type {string}
  31846. * @default ''
  31847. */
  31848. this.code = code;
  31849. Object.defineProperty( this, 'isNodeCode', { value: true } );
  31850. }
  31851. }
  31852. let _id$5 = 0;
  31853. /**
  31854. * This utility class is used in {@link NodeBuilder} as an internal
  31855. * cache data structure for node data.
  31856. */
  31857. class NodeCache {
  31858. /**
  31859. * Constructs a new node cache.
  31860. *
  31861. * @param {?NodeCache} parent - A reference to a parent cache.
  31862. */
  31863. constructor( parent = null ) {
  31864. /**
  31865. * The id of the cache.
  31866. *
  31867. * @type {number}
  31868. * @readonly
  31869. */
  31870. this.id = _id$5 ++;
  31871. /**
  31872. * A weak map for managing node data.
  31873. *
  31874. * @type {WeakMap<Node, Object>}
  31875. */
  31876. this.nodesData = new WeakMap();
  31877. /**
  31878. * Reference to a parent node cache.
  31879. *
  31880. * @type {?NodeCache}
  31881. * @default null
  31882. */
  31883. this.parent = parent;
  31884. }
  31885. /**
  31886. * Returns the data for the given node.
  31887. *
  31888. * @param {Node} node - The node.
  31889. * @return {?Object} The data for the node.
  31890. */
  31891. getData( node ) {
  31892. let data = this.nodesData.get( node );
  31893. if ( data === undefined && this.parent !== null ) {
  31894. data = this.parent.getData( node );
  31895. }
  31896. return data;
  31897. }
  31898. /**
  31899. * Sets the data for a given node.
  31900. *
  31901. * @param {Node} node - The node.
  31902. * @param {Object} data - The data that should be cached.
  31903. */
  31904. setData( node, data ) {
  31905. this.nodesData.set( node, data );
  31906. }
  31907. }
  31908. class StructType {
  31909. constructor( name, members ) {
  31910. this.name = name;
  31911. this.members = members;
  31912. this.output = false;
  31913. }
  31914. }
  31915. /**
  31916. * Abstract base class for uniforms.
  31917. *
  31918. * @abstract
  31919. * @private
  31920. */
  31921. class Uniform {
  31922. /**
  31923. * Constructs a new uniform.
  31924. *
  31925. * @param {string} name - The uniform's name.
  31926. * @param {any} value - The uniform's value.
  31927. */
  31928. constructor( name, value ) {
  31929. /**
  31930. * The uniform's name.
  31931. *
  31932. * @type {string}
  31933. */
  31934. this.name = name;
  31935. /**
  31936. * The uniform's value.
  31937. *
  31938. * @type {any}
  31939. */
  31940. this.value = value;
  31941. /**
  31942. * Used to build the uniform buffer according to the STD140 layout.
  31943. * Derived uniforms will set this property to a data type specific
  31944. * value.
  31945. *
  31946. * @type {number}
  31947. */
  31948. this.boundary = 0;
  31949. /**
  31950. * The item size. Derived uniforms will set this property to a data
  31951. * type specific value.
  31952. *
  31953. * @type {number}
  31954. */
  31955. this.itemSize = 0;
  31956. /**
  31957. * This property is set by {@link UniformsGroup} and marks
  31958. * the start position in the uniform buffer.
  31959. *
  31960. * @type {number}
  31961. */
  31962. this.offset = 0;
  31963. }
  31964. /**
  31965. * Sets the uniform's value.
  31966. *
  31967. * @param {any} value - The value to set.
  31968. */
  31969. setValue( value ) {
  31970. this.value = value;
  31971. }
  31972. /**
  31973. * Returns the uniform's value.
  31974. *
  31975. * @return {any} The value.
  31976. */
  31977. getValue() {
  31978. return this.value;
  31979. }
  31980. }
  31981. /**
  31982. * Represents a Number uniform.
  31983. *
  31984. * @private
  31985. * @augments Uniform
  31986. */
  31987. class NumberUniform extends Uniform {
  31988. /**
  31989. * Constructs a new Number uniform.
  31990. *
  31991. * @param {string} name - The uniform's name.
  31992. * @param {number} value - The uniform's value.
  31993. */
  31994. constructor( name, value = 0 ) {
  31995. super( name, value );
  31996. /**
  31997. * This flag can be used for type testing.
  31998. *
  31999. * @type {boolean}
  32000. * @readonly
  32001. * @default true
  32002. */
  32003. this.isNumberUniform = true;
  32004. this.boundary = 4;
  32005. this.itemSize = 1;
  32006. }
  32007. }
  32008. /**
  32009. * Represents a Vector2 uniform.
  32010. *
  32011. * @private
  32012. * @augments Uniform
  32013. */
  32014. class Vector2Uniform extends Uniform {
  32015. /**
  32016. * Constructs a new Number uniform.
  32017. *
  32018. * @param {string} name - The uniform's name.
  32019. * @param {Vector2} value - The uniform's value.
  32020. */
  32021. constructor( name, value = new Vector2() ) {
  32022. super( name, value );
  32023. /**
  32024. * This flag can be used for type testing.
  32025. *
  32026. * @type {boolean}
  32027. * @readonly
  32028. * @default true
  32029. */
  32030. this.isVector2Uniform = true;
  32031. this.boundary = 8;
  32032. this.itemSize = 2;
  32033. }
  32034. }
  32035. /**
  32036. * Represents a Vector3 uniform.
  32037. *
  32038. * @private
  32039. * @augments Uniform
  32040. */
  32041. class Vector3Uniform extends Uniform {
  32042. /**
  32043. * Constructs a new Number uniform.
  32044. *
  32045. * @param {string} name - The uniform's name.
  32046. * @param {Vector3} value - The uniform's value.
  32047. */
  32048. constructor( name, value = new Vector3() ) {
  32049. super( name, value );
  32050. /**
  32051. * This flag can be used for type testing.
  32052. *
  32053. * @type {boolean}
  32054. * @readonly
  32055. * @default true
  32056. */
  32057. this.isVector3Uniform = true;
  32058. this.boundary = 16;
  32059. this.itemSize = 3;
  32060. }
  32061. }
  32062. /**
  32063. * Represents a Vector4 uniform.
  32064. *
  32065. * @private
  32066. * @augments Uniform
  32067. */
  32068. class Vector4Uniform extends Uniform {
  32069. /**
  32070. * Constructs a new Number uniform.
  32071. *
  32072. * @param {string} name - The uniform's name.
  32073. * @param {Vector4} value - The uniform's value.
  32074. */
  32075. constructor( name, value = new Vector4() ) {
  32076. super( name, value );
  32077. /**
  32078. * This flag can be used for type testing.
  32079. *
  32080. * @type {boolean}
  32081. * @readonly
  32082. * @default true
  32083. */
  32084. this.isVector4Uniform = true;
  32085. this.boundary = 16;
  32086. this.itemSize = 4;
  32087. }
  32088. }
  32089. /**
  32090. * Represents a Color uniform.
  32091. *
  32092. * @private
  32093. * @augments Uniform
  32094. */
  32095. class ColorUniform extends Uniform {
  32096. /**
  32097. * Constructs a new Number uniform.
  32098. *
  32099. * @param {string} name - The uniform's name.
  32100. * @param {Color} value - The uniform's value.
  32101. */
  32102. constructor( name, value = new Color() ) {
  32103. super( name, value );
  32104. /**
  32105. * This flag can be used for type testing.
  32106. *
  32107. * @type {boolean}
  32108. * @readonly
  32109. * @default true
  32110. */
  32111. this.isColorUniform = true;
  32112. this.boundary = 16;
  32113. this.itemSize = 3;
  32114. }
  32115. }
  32116. /**
  32117. * Represents a Matrix2 uniform.
  32118. *
  32119. * @private
  32120. * @augments Uniform
  32121. */
  32122. class Matrix2Uniform extends Uniform {
  32123. /**
  32124. * Constructs a new Number uniform.
  32125. *
  32126. * @param {string} name - The uniform's name.
  32127. * @param {Matrix2} value - The uniform's value.
  32128. */
  32129. constructor( name, value = new Matrix2() ) {
  32130. super( name, value );
  32131. /**
  32132. * This flag can be used for type testing.
  32133. *
  32134. * @type {boolean}
  32135. * @readonly
  32136. * @default true
  32137. */
  32138. this.isMatrix2Uniform = true;
  32139. this.boundary = 8;
  32140. this.itemSize = 4;
  32141. }
  32142. }
  32143. /**
  32144. * Represents a Matrix3 uniform.
  32145. *
  32146. * @private
  32147. * @augments Uniform
  32148. */
  32149. class Matrix3Uniform extends Uniform {
  32150. /**
  32151. * Constructs a new Number uniform.
  32152. *
  32153. * @param {string} name - The uniform's name.
  32154. * @param {Matrix3} value - The uniform's value.
  32155. */
  32156. constructor( name, value = new Matrix3() ) {
  32157. super( name, value );
  32158. /**
  32159. * This flag can be used for type testing.
  32160. *
  32161. * @type {boolean}
  32162. * @readonly
  32163. * @default true
  32164. */
  32165. this.isMatrix3Uniform = true;
  32166. this.boundary = 48;
  32167. this.itemSize = 12;
  32168. }
  32169. }
  32170. /**
  32171. * Represents a Matrix4 uniform.
  32172. *
  32173. * @private
  32174. * @augments Uniform
  32175. */
  32176. class Matrix4Uniform extends Uniform {
  32177. /**
  32178. * Constructs a new Number uniform.
  32179. *
  32180. * @param {string} name - The uniform's name.
  32181. * @param {Matrix4} value - The uniform's value.
  32182. */
  32183. constructor( name, value = new Matrix4() ) {
  32184. super( name, value );
  32185. /**
  32186. * This flag can be used for type testing.
  32187. *
  32188. * @type {boolean}
  32189. * @readonly
  32190. * @default true
  32191. */
  32192. this.isMatrix4Uniform = true;
  32193. this.boundary = 64;
  32194. this.itemSize = 16;
  32195. }
  32196. }
  32197. /**
  32198. * A special form of Number uniform binding type.
  32199. * It's value is managed by a node object.
  32200. *
  32201. * @private
  32202. * @augments NumberUniform
  32203. */
  32204. class NumberNodeUniform extends NumberUniform {
  32205. /**
  32206. * Constructs a new node-based Number uniform.
  32207. *
  32208. * @param {NodeUniform} nodeUniform - The node uniform.
  32209. */
  32210. constructor( nodeUniform ) {
  32211. super( nodeUniform.name, nodeUniform.value );
  32212. /**
  32213. * The node uniform.
  32214. *
  32215. * @type {NodeUniform}
  32216. */
  32217. this.nodeUniform = nodeUniform;
  32218. }
  32219. /**
  32220. * Overwritten to return the value of the node uniform.
  32221. *
  32222. * @return {number} The value.
  32223. */
  32224. getValue() {
  32225. return this.nodeUniform.value;
  32226. }
  32227. /**
  32228. * Returns the node uniform data type.
  32229. *
  32230. * @return {string} The data type.
  32231. */
  32232. getType() {
  32233. return this.nodeUniform.type;
  32234. }
  32235. }
  32236. /**
  32237. * A special form of Vector2 uniform binding type.
  32238. * It's value is managed by a node object.
  32239. *
  32240. * @private
  32241. * @augments Vector2Uniform
  32242. */
  32243. class Vector2NodeUniform extends Vector2Uniform {
  32244. /**
  32245. * Constructs a new node-based Vector2 uniform.
  32246. *
  32247. * @param {NodeUniform} nodeUniform - The node uniform.
  32248. */
  32249. constructor( nodeUniform ) {
  32250. super( nodeUniform.name, nodeUniform.value );
  32251. /**
  32252. * The node uniform.
  32253. *
  32254. * @type {NodeUniform}
  32255. */
  32256. this.nodeUniform = nodeUniform;
  32257. }
  32258. /**
  32259. * Overwritten to return the value of the node uniform.
  32260. *
  32261. * @return {Vector2} The value.
  32262. */
  32263. getValue() {
  32264. return this.nodeUniform.value;
  32265. }
  32266. /**
  32267. * Returns the node uniform data type.
  32268. *
  32269. * @return {string} The data type.
  32270. */
  32271. getType() {
  32272. return this.nodeUniform.type;
  32273. }
  32274. }
  32275. /**
  32276. * A special form of Vector3 uniform binding type.
  32277. * It's value is managed by a node object.
  32278. *
  32279. * @private
  32280. * @augments Vector3Uniform
  32281. */
  32282. class Vector3NodeUniform extends Vector3Uniform {
  32283. /**
  32284. * Constructs a new node-based Vector3 uniform.
  32285. *
  32286. * @param {NodeUniform} nodeUniform - The node uniform.
  32287. */
  32288. constructor( nodeUniform ) {
  32289. super( nodeUniform.name, nodeUniform.value );
  32290. /**
  32291. * The node uniform.
  32292. *
  32293. * @type {NodeUniform}
  32294. */
  32295. this.nodeUniform = nodeUniform;
  32296. }
  32297. /**
  32298. * Overwritten to return the value of the node uniform.
  32299. *
  32300. * @return {Vector3} The value.
  32301. */
  32302. getValue() {
  32303. return this.nodeUniform.value;
  32304. }
  32305. /**
  32306. * Returns the node uniform data type.
  32307. *
  32308. * @return {string} The data type.
  32309. */
  32310. getType() {
  32311. return this.nodeUniform.type;
  32312. }
  32313. }
  32314. /**
  32315. * A special form of Vector4 uniform binding type.
  32316. * It's value is managed by a node object.
  32317. *
  32318. * @private
  32319. * @augments Vector4Uniform
  32320. */
  32321. class Vector4NodeUniform extends Vector4Uniform {
  32322. /**
  32323. * Constructs a new node-based Vector4 uniform.
  32324. *
  32325. * @param {NodeUniform} nodeUniform - The node uniform.
  32326. */
  32327. constructor( nodeUniform ) {
  32328. super( nodeUniform.name, nodeUniform.value );
  32329. /**
  32330. * The node uniform.
  32331. *
  32332. * @type {NodeUniform}
  32333. */
  32334. this.nodeUniform = nodeUniform;
  32335. }
  32336. /**
  32337. * Overwritten to return the value of the node uniform.
  32338. *
  32339. * @return {Vector4} The value.
  32340. */
  32341. getValue() {
  32342. return this.nodeUniform.value;
  32343. }
  32344. /**
  32345. * Returns the node uniform data type.
  32346. *
  32347. * @return {string} The data type.
  32348. */
  32349. getType() {
  32350. return this.nodeUniform.type;
  32351. }
  32352. }
  32353. /**
  32354. * A special form of Color uniform binding type.
  32355. * It's value is managed by a node object.
  32356. *
  32357. * @private
  32358. * @augments ColorUniform
  32359. */
  32360. class ColorNodeUniform extends ColorUniform {
  32361. /**
  32362. * Constructs a new node-based Color uniform.
  32363. *
  32364. * @param {NodeUniform} nodeUniform - The node uniform.
  32365. */
  32366. constructor( nodeUniform ) {
  32367. super( nodeUniform.name, nodeUniform.value );
  32368. /**
  32369. * The node uniform.
  32370. *
  32371. * @type {NodeUniform}
  32372. */
  32373. this.nodeUniform = nodeUniform;
  32374. }
  32375. /**
  32376. * Overwritten to return the value of the node uniform.
  32377. *
  32378. * @return {Color} The value.
  32379. */
  32380. getValue() {
  32381. return this.nodeUniform.value;
  32382. }
  32383. /**
  32384. * Returns the node uniform data type.
  32385. *
  32386. * @return {string} The data type.
  32387. */
  32388. getType() {
  32389. return this.nodeUniform.type;
  32390. }
  32391. }
  32392. /**
  32393. * A special form of Matrix2 uniform binding type.
  32394. * It's value is managed by a node object.
  32395. *
  32396. * @private
  32397. * @augments Matrix2Uniform
  32398. */
  32399. class Matrix2NodeUniform extends Matrix2Uniform {
  32400. /**
  32401. * Constructs a new node-based Matrix2 uniform.
  32402. *
  32403. * @param {NodeUniform} nodeUniform - The node uniform.
  32404. */
  32405. constructor( nodeUniform ) {
  32406. super( nodeUniform.name, nodeUniform.value );
  32407. /**
  32408. * The node uniform.
  32409. *
  32410. * @type {NodeUniform}
  32411. */
  32412. this.nodeUniform = nodeUniform;
  32413. }
  32414. /**
  32415. * Overwritten to return the value of the node uniform.
  32416. *
  32417. * @return {Matrix2} The value.
  32418. */
  32419. getValue() {
  32420. return this.nodeUniform.value;
  32421. }
  32422. /**
  32423. * Returns the node uniform data type.
  32424. *
  32425. * @return {string} The data type.
  32426. */
  32427. getType() {
  32428. return this.nodeUniform.type;
  32429. }
  32430. }
  32431. /**
  32432. * A special form of Matrix3 uniform binding type.
  32433. * It's value is managed by a node object.
  32434. *
  32435. * @private
  32436. * @augments Matrix3Uniform
  32437. */
  32438. class Matrix3NodeUniform extends Matrix3Uniform {
  32439. /**
  32440. * Constructs a new node-based Matrix3 uniform.
  32441. *
  32442. * @param {NodeUniform} nodeUniform - The node uniform.
  32443. */
  32444. constructor( nodeUniform ) {
  32445. super( nodeUniform.name, nodeUniform.value );
  32446. /**
  32447. * The node uniform.
  32448. *
  32449. * @type {NodeUniform}
  32450. */
  32451. this.nodeUniform = nodeUniform;
  32452. }
  32453. /**
  32454. * Overwritten to return the value of the node uniform.
  32455. *
  32456. * @return {Matrix3} The value.
  32457. */
  32458. getValue() {
  32459. return this.nodeUniform.value;
  32460. }
  32461. /**
  32462. * Returns the node uniform data type.
  32463. *
  32464. * @return {string} The data type.
  32465. */
  32466. getType() {
  32467. return this.nodeUniform.type;
  32468. }
  32469. }
  32470. /**
  32471. * A special form of Matrix4 uniform binding type.
  32472. * It's value is managed by a node object.
  32473. *
  32474. * @private
  32475. * @augments Matrix4Uniform
  32476. */
  32477. class Matrix4NodeUniform extends Matrix4Uniform {
  32478. /**
  32479. * Constructs a new node-based Matrix4 uniform.
  32480. *
  32481. * @param {NodeUniform} nodeUniform - The node uniform.
  32482. */
  32483. constructor( nodeUniform ) {
  32484. super( nodeUniform.name, nodeUniform.value );
  32485. /**
  32486. * The node uniform.
  32487. *
  32488. * @type {NodeUniform}
  32489. */
  32490. this.nodeUniform = nodeUniform;
  32491. }
  32492. /**
  32493. * Overwritten to return the value of the node uniform.
  32494. *
  32495. * @return {Matrix4} The value.
  32496. */
  32497. getValue() {
  32498. return this.nodeUniform.value;
  32499. }
  32500. /**
  32501. * Returns the node uniform data type.
  32502. *
  32503. * @return {string} The data type.
  32504. */
  32505. getType() {
  32506. return this.nodeUniform.type;
  32507. }
  32508. }
  32509. const rendererCache = new WeakMap();
  32510. const typeFromArray = new Map( [
  32511. [ Int8Array, 'int' ],
  32512. [ Int16Array, 'int' ],
  32513. [ Int32Array, 'int' ],
  32514. [ Uint8Array, 'uint' ],
  32515. [ Uint16Array, 'uint' ],
  32516. [ Uint32Array, 'uint' ],
  32517. [ Float32Array, 'float' ]
  32518. ] );
  32519. const toFloat = ( value ) => {
  32520. if ( /e/g.test( value ) ) {
  32521. return String( value ).replace( /\+/g, '' );
  32522. } else {
  32523. value = Number( value );
  32524. return value + ( value % 1 ? '' : '.0' );
  32525. }
  32526. };
  32527. /**
  32528. * Base class for builders which generate a shader program based
  32529. * on a 3D object and its node material definition.
  32530. */
  32531. class NodeBuilder {
  32532. /**
  32533. * Constructs a new node builder.
  32534. *
  32535. * @param {Object3D} object - The 3D object.
  32536. * @param {Renderer} renderer - The current renderer.
  32537. * @param {NodeParser} parser - A reference to a node parser.
  32538. */
  32539. constructor( object, renderer, parser ) {
  32540. /**
  32541. * The 3D object.
  32542. *
  32543. * @type {Object3D}
  32544. */
  32545. this.object = object;
  32546. /**
  32547. * The material of the 3D object.
  32548. *
  32549. * @type {?Material}
  32550. */
  32551. this.material = ( object && object.material ) || null;
  32552. /**
  32553. * The geometry of the 3D object.
  32554. *
  32555. * @type {?BufferGeometry}
  32556. */
  32557. this.geometry = ( object && object.geometry ) || null;
  32558. /**
  32559. * The current renderer.
  32560. *
  32561. * @type {Renderer}
  32562. */
  32563. this.renderer = renderer;
  32564. /**
  32565. * A reference to a node parser.
  32566. *
  32567. * @type {NodeParser}
  32568. */
  32569. this.parser = parser;
  32570. /**
  32571. * The scene the 3D object belongs to.
  32572. *
  32573. * @type {?Scene}
  32574. * @default null
  32575. */
  32576. this.scene = null;
  32577. /**
  32578. * The camera the 3D object is rendered with.
  32579. *
  32580. * @type {?Camera}
  32581. * @default null
  32582. */
  32583. this.camera = null;
  32584. /**
  32585. * A list of all nodes the builder is processing
  32586. * for this 3D object.
  32587. *
  32588. * @type {Array<Node>}
  32589. */
  32590. this.nodes = [];
  32591. /**
  32592. * A list of all sequential nodes.
  32593. *
  32594. * @type {Array<Node>}
  32595. */
  32596. this.sequentialNodes = [];
  32597. /**
  32598. * A list of all nodes which {@link Node#update} method should be executed.
  32599. *
  32600. * @type {Array<Node>}
  32601. */
  32602. this.updateNodes = [];
  32603. /**
  32604. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  32605. *
  32606. * @type {Array<Node>}
  32607. */
  32608. this.updateBeforeNodes = [];
  32609. /**
  32610. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  32611. *
  32612. * @type {Array<Node>}
  32613. */
  32614. this.updateAfterNodes = [];
  32615. /**
  32616. * A dictionary that assigns each node to a unique hash.
  32617. *
  32618. * @type {Object<number,Node>}
  32619. */
  32620. this.hashNodes = {};
  32621. /**
  32622. * A reference to a node material observer.
  32623. *
  32624. * @type {?NodeMaterialObserver}
  32625. * @default null
  32626. */
  32627. this.observer = null;
  32628. /**
  32629. * A reference to the current lights node.
  32630. *
  32631. * @type {?LightsNode}
  32632. * @default null
  32633. */
  32634. this.lightsNode = null;
  32635. /**
  32636. * A reference to the current environment node.
  32637. *
  32638. * @type {?Node}
  32639. * @default null
  32640. */
  32641. this.environmentNode = null;
  32642. /**
  32643. * A reference to the current fog node.
  32644. *
  32645. * @type {?Node}
  32646. * @default null
  32647. */
  32648. this.fogNode = null;
  32649. /**
  32650. * The current clipping context.
  32651. *
  32652. * @type {?ClippingContext}
  32653. */
  32654. this.clippingContext = null;
  32655. /**
  32656. * The generated vertex shader.
  32657. *
  32658. * @type {?string}
  32659. */
  32660. this.vertexShader = null;
  32661. /**
  32662. * The generated fragment shader.
  32663. *
  32664. * @type {?string}
  32665. */
  32666. this.fragmentShader = null;
  32667. /**
  32668. * The generated compute shader.
  32669. *
  32670. * @type {?string}
  32671. */
  32672. this.computeShader = null;
  32673. /**
  32674. * Nodes used in the primary flow of code generation.
  32675. *
  32676. * @type {Object<string,Array<Node>>}
  32677. */
  32678. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  32679. /**
  32680. * Nodes code from `.flowNodes`.
  32681. *
  32682. * @type {Object<string,string>}
  32683. */
  32684. this.flowCode = { vertex: '', fragment: '', compute: '' };
  32685. /**
  32686. * This dictionary holds the node uniforms of the builder.
  32687. * The uniforms are maintained in an array for each shader stage.
  32688. *
  32689. * @type {Object}
  32690. */
  32691. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  32692. /**
  32693. * This dictionary holds the output structs of the builder.
  32694. * The structs are maintained in an array for each shader stage.
  32695. *
  32696. * @type {Object}
  32697. */
  32698. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  32699. /**
  32700. * This dictionary holds the bindings for each shader stage.
  32701. *
  32702. * @type {Object}
  32703. */
  32704. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  32705. /**
  32706. * This dictionary maintains the binding indices per bind group.
  32707. *
  32708. * @type {Object}
  32709. */
  32710. this.bindingsIndexes = {};
  32711. /**
  32712. * Reference to the array of bind groups.
  32713. *
  32714. * @type {?Array<BindGroup>}
  32715. */
  32716. this.bindGroups = null;
  32717. /**
  32718. * This array holds the node attributes of this builder
  32719. * created via {@link AttributeNode}.
  32720. *
  32721. * @type {Array<NodeAttribute>}
  32722. */
  32723. this.attributes = [];
  32724. /**
  32725. * This array holds the node attributes of this builder
  32726. * created via {@link BufferAttributeNode}.
  32727. *
  32728. * @type {Array<NodeAttribute>}
  32729. */
  32730. this.bufferAttributes = [];
  32731. /**
  32732. * This array holds the node varyings of this builder.
  32733. *
  32734. * @type {Array<NodeVarying>}
  32735. */
  32736. this.varyings = [];
  32737. /**
  32738. * This dictionary holds the (native) node codes of this builder.
  32739. * The codes are maintained in an array for each shader stage.
  32740. *
  32741. * @type {Object<string,Array<NodeCode>>}
  32742. */
  32743. this.codes = {};
  32744. /**
  32745. * This dictionary holds the node variables of this builder.
  32746. * The variables are maintained in an array for each shader stage.
  32747. * This dictionary is also used to count the number of variables
  32748. * according to their type (const, vars).
  32749. *
  32750. * @type {Object<string,Array<NodeVar>|number>}
  32751. */
  32752. this.vars = {};
  32753. /**
  32754. * This dictionary holds the declarations for each shader stage.
  32755. *
  32756. * @type {Object}
  32757. */
  32758. this.declarations = {};
  32759. /**
  32760. * Current code flow.
  32761. * All code generated in this stack will be stored in `.flow`.
  32762. *
  32763. * @type {{code: string}}
  32764. */
  32765. this.flow = { code: '' };
  32766. /**
  32767. * A chain of nodes.
  32768. * Used to check recursive calls in node-graph.
  32769. *
  32770. * @type {Array<Node>}
  32771. */
  32772. this.chaining = [];
  32773. /**
  32774. * The current stack.
  32775. * This reflects the current process in the code block hierarchy,
  32776. * it is useful to know if the current process is inside a conditional for example.
  32777. *
  32778. * @type {StackNode}
  32779. */
  32780. this.stack = stack();
  32781. /**
  32782. * List of stack nodes.
  32783. * The current stack hierarchy is stored in an array.
  32784. *
  32785. * @type {Array<StackNode>}
  32786. */
  32787. this.stacks = [];
  32788. /**
  32789. * A tab value. Used for shader string generation.
  32790. *
  32791. * @type {string}
  32792. * @default '\t'
  32793. */
  32794. this.tab = '\t';
  32795. /**
  32796. * Reference to the current function node.
  32797. *
  32798. * @type {?FunctionNode}
  32799. * @default null
  32800. */
  32801. this.currentFunctionNode = null;
  32802. /**
  32803. * The builder's context.
  32804. *
  32805. * @type {Object}
  32806. */
  32807. this.context = {
  32808. material: this.material
  32809. };
  32810. /**
  32811. * The builder's cache.
  32812. *
  32813. * @type {NodeCache}
  32814. */
  32815. this.cache = new NodeCache();
  32816. /**
  32817. * Since the {@link NodeBuilder#cache} might be temporarily
  32818. * overwritten by other caches, this member retains the reference
  32819. * to the builder's own cache.
  32820. *
  32821. * @type {NodeCache}
  32822. * @default this.cache
  32823. */
  32824. this.globalCache = this.cache;
  32825. this.flowsData = new WeakMap();
  32826. /**
  32827. * The current shader stage.
  32828. *
  32829. * @type {?('vertex'|'fragment'|'compute'|'any')}
  32830. */
  32831. this.shaderStage = null;
  32832. /**
  32833. * The current build stage.
  32834. *
  32835. * @type {?('setup'|'analyze'|'generate')}
  32836. */
  32837. this.buildStage = null;
  32838. /**
  32839. * The sub-build layers.
  32840. *
  32841. * @type {Array<SubBuildNode>}
  32842. * @default []
  32843. */
  32844. this.subBuildLayers = [];
  32845. /**
  32846. * The current stack of nodes.
  32847. *
  32848. * @type {?StackNode}
  32849. * @default null
  32850. */
  32851. this.currentStack = null;
  32852. /**
  32853. * The current sub-build TSL function(Fn).
  32854. *
  32855. * @type {?string}
  32856. * @default null
  32857. */
  32858. this.subBuildFn = null;
  32859. }
  32860. /**
  32861. * Returns the bind groups of the current renderer.
  32862. *
  32863. * @return {ChainMap} The cache.
  32864. */
  32865. getBindGroupsCache() {
  32866. let bindGroupsCache = rendererCache.get( this.renderer );
  32867. if ( bindGroupsCache === undefined ) {
  32868. bindGroupsCache = new ChainMap();
  32869. rendererCache.set( this.renderer, bindGroupsCache );
  32870. }
  32871. return bindGroupsCache;
  32872. }
  32873. /**
  32874. * Factory method for creating an instance of {@link RenderTarget} with the given
  32875. * dimensions and options.
  32876. *
  32877. * @param {number} width - The width of the render target.
  32878. * @param {number} height - The height of the render target.
  32879. * @param {Object} options - The options of the render target.
  32880. * @return {RenderTarget} The render target.
  32881. */
  32882. createRenderTarget( width, height, options ) {
  32883. return new RenderTarget( width, height, options );
  32884. }
  32885. /**
  32886. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  32887. * dimensions and options.
  32888. *
  32889. * @param {number} size - The size of the cube render target.
  32890. * @param {Object} options - The options of the cube render target.
  32891. * @return {CubeRenderTarget} The cube render target.
  32892. */
  32893. createCubeRenderTarget( size, options ) {
  32894. return new CubeRenderTarget( size, options );
  32895. }
  32896. /**
  32897. * Whether the given node is included in the internal array of nodes or not.
  32898. *
  32899. * @param {Node} node - The node to test.
  32900. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  32901. */
  32902. includes( node ) {
  32903. return this.nodes.includes( node );
  32904. }
  32905. /**
  32906. * Returns the output struct name which is required by
  32907. * {@link OutputStructNode}.
  32908. *
  32909. * @abstract
  32910. * @return {string} The name of the output struct.
  32911. */
  32912. getOutputStructName() {}
  32913. /**
  32914. * Returns a bind group for the given group name and binding.
  32915. *
  32916. * @private
  32917. * @param {string} groupName - The group name.
  32918. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  32919. * @return {BindGroup} The bind group
  32920. */
  32921. _getBindGroup( groupName, bindings ) {
  32922. const bindGroupsCache = this.getBindGroupsCache();
  32923. //
  32924. const bindingsArray = [];
  32925. let sharedGroup = true;
  32926. for ( const binding of bindings ) {
  32927. bindingsArray.push( binding );
  32928. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  32929. }
  32930. //
  32931. let bindGroup;
  32932. if ( sharedGroup ) {
  32933. bindGroup = bindGroupsCache.get( bindingsArray );
  32934. if ( bindGroup === undefined ) {
  32935. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  32936. bindGroupsCache.set( bindingsArray, bindGroup );
  32937. }
  32938. } else {
  32939. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  32940. }
  32941. return bindGroup;
  32942. }
  32943. /**
  32944. * Returns an array of node uniform groups for the given group name and shader stage.
  32945. *
  32946. * @param {string} groupName - The group name.
  32947. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32948. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  32949. */
  32950. getBindGroupArray( groupName, shaderStage ) {
  32951. const bindings = this.bindings[ shaderStage ];
  32952. let bindGroup = bindings[ groupName ];
  32953. if ( bindGroup === undefined ) {
  32954. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  32955. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  32956. }
  32957. bindings[ groupName ] = bindGroup = [];
  32958. }
  32959. return bindGroup;
  32960. }
  32961. /**
  32962. * Returns a list bindings of all shader stages separated by groups.
  32963. *
  32964. * @return {Array<BindGroup>} The list of bindings.
  32965. */
  32966. getBindings() {
  32967. let bindingsGroups = this.bindGroups;
  32968. if ( bindingsGroups === null ) {
  32969. const groups = {};
  32970. const bindings = this.bindings;
  32971. for ( const shaderStage of shaderStages ) {
  32972. for ( const groupName in bindings[ shaderStage ] ) {
  32973. const uniforms = bindings[ shaderStage ][ groupName ];
  32974. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  32975. groupUniforms.push( ...uniforms );
  32976. }
  32977. }
  32978. bindingsGroups = [];
  32979. for ( const groupName in groups ) {
  32980. const group = groups[ groupName ];
  32981. const bindingsGroup = this._getBindGroup( groupName, group );
  32982. bindingsGroups.push( bindingsGroup );
  32983. }
  32984. this.bindGroups = bindingsGroups;
  32985. }
  32986. return bindingsGroups;
  32987. }
  32988. /**
  32989. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  32990. */
  32991. sortBindingGroups() {
  32992. const bindingsGroups = this.getBindings();
  32993. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  32994. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  32995. const bindingGroup = bindingsGroups[ i ];
  32996. this.bindingsIndexes[ bindingGroup.name ].group = i;
  32997. bindingGroup.index = i;
  32998. }
  32999. }
  33000. /**
  33001. * The builder maintains each node in a hash-based dictionary.
  33002. * This method sets the given node (value) with the given hash (key) into this dictionary.
  33003. *
  33004. * @param {Node} node - The node to add.
  33005. * @param {number} hash - The hash of the node.
  33006. */
  33007. setHashNode( node, hash ) {
  33008. this.hashNodes[ hash ] = node;
  33009. }
  33010. /**
  33011. * Adds a node to this builder.
  33012. *
  33013. * @param {Node} node - The node to add.
  33014. */
  33015. addNode( node ) {
  33016. if ( this.nodes.includes( node ) === false ) {
  33017. this.nodes.push( node );
  33018. this.setHashNode( node, node.getHash( this ) );
  33019. }
  33020. }
  33021. /**
  33022. * It is used to add Nodes that will be used as FRAME and RENDER events,
  33023. * and need to follow a certain sequence in the calls to work correctly.
  33024. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  33025. *
  33026. * @param {Node} node - The node to add.
  33027. */
  33028. addSequentialNode( node ) {
  33029. if ( this.sequentialNodes.includes( node ) === false ) {
  33030. this.sequentialNodes.push( node );
  33031. }
  33032. }
  33033. /**
  33034. * Checks the update types of nodes
  33035. */
  33036. buildUpdateNodes() {
  33037. for ( const node of this.nodes ) {
  33038. const updateType = node.getUpdateType();
  33039. if ( updateType !== NodeUpdateType.NONE ) {
  33040. this.updateNodes.push( node.getSelf() );
  33041. }
  33042. }
  33043. for ( const node of this.sequentialNodes ) {
  33044. const updateBeforeType = node.getUpdateBeforeType();
  33045. const updateAfterType = node.getUpdateAfterType();
  33046. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  33047. this.updateBeforeNodes.push( node.getSelf() );
  33048. }
  33049. if ( updateAfterType !== NodeUpdateType.NONE ) {
  33050. this.updateAfterNodes.push( node.getSelf() );
  33051. }
  33052. }
  33053. }
  33054. /**
  33055. * A reference the current node which is the
  33056. * last node in the chain of nodes.
  33057. *
  33058. * @type {Node}
  33059. */
  33060. get currentNode() {
  33061. return this.chaining[ this.chaining.length - 1 ];
  33062. }
  33063. /**
  33064. * Whether the given texture is filtered or not.
  33065. *
  33066. * @param {Texture} texture - The texture to check.
  33067. * @return {boolean} Whether the given texture is filtered or not.
  33068. */
  33069. isFilteredTexture( texture ) {
  33070. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  33071. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  33072. }
  33073. /**
  33074. * Adds the given node to the internal node chain.
  33075. * This is used to check recursive calls in node-graph.
  33076. *
  33077. * @param {Node} node - The node to add.
  33078. */
  33079. addChain( node ) {
  33080. /*
  33081. if ( this.chaining.indexOf( node ) !== - 1 ) {
  33082. console.warn( 'Recursive node: ', node );
  33083. }
  33084. */
  33085. this.chaining.push( node );
  33086. }
  33087. /**
  33088. * Removes the given node from the internal node chain.
  33089. *
  33090. * @param {Node} node - The node to remove.
  33091. */
  33092. removeChain( node ) {
  33093. const lastChain = this.chaining.pop();
  33094. if ( lastChain !== node ) {
  33095. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  33096. }
  33097. }
  33098. /**
  33099. * Returns the native shader method name for a given generic name. E.g.
  33100. * the method name `textureDimensions` matches the WGSL name but must be
  33101. * resolved to `textureSize` in GLSL.
  33102. *
  33103. * @abstract
  33104. * @param {string} method - The method name to resolve.
  33105. * @return {string} The resolved method name.
  33106. */
  33107. getMethod( method ) {
  33108. return method;
  33109. }
  33110. /**
  33111. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  33112. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  33113. *
  33114. * @abstract
  33115. * @param {string} condSnippet - The condition determining which expression gets resolved.
  33116. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  33117. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  33118. * @return {string} The resolved method name.
  33119. */
  33120. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  33121. return null;
  33122. }
  33123. /**
  33124. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  33125. *
  33126. * @param {number} hash - The hash of the node.
  33127. * @return {Node} The found node.
  33128. */
  33129. getNodeFromHash( hash ) {
  33130. return this.hashNodes[ hash ];
  33131. }
  33132. /**
  33133. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  33134. *
  33135. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  33136. * @param {Node} node - The node to add.
  33137. * @return {Node} The node.
  33138. */
  33139. addFlow( shaderStage, node ) {
  33140. this.flowNodes[ shaderStage ].push( node );
  33141. return node;
  33142. }
  33143. /**
  33144. * Sets builder's context.
  33145. *
  33146. * @param {Object} context - The context to set.
  33147. */
  33148. setContext( context ) {
  33149. this.context = context;
  33150. }
  33151. /**
  33152. * Returns the builder's current context.
  33153. *
  33154. * @return {Object} The builder's current context.
  33155. */
  33156. getContext() {
  33157. return this.context;
  33158. }
  33159. /**
  33160. * Gets a context used in shader construction that can be shared across different materials.
  33161. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  33162. *
  33163. * @return {Object} The builder's current context without material.
  33164. */
  33165. getSharedContext() {
  33166. ({ ...this.context });
  33167. return this.context;
  33168. }
  33169. /**
  33170. * Sets builder's cache.
  33171. *
  33172. * @param {NodeCache} cache - The cache to set.
  33173. */
  33174. setCache( cache ) {
  33175. this.cache = cache;
  33176. }
  33177. /**
  33178. * Returns the builder's current cache.
  33179. *
  33180. * @return {NodeCache} The builder's current cache.
  33181. */
  33182. getCache() {
  33183. return this.cache;
  33184. }
  33185. /**
  33186. * Returns a cache for the given node.
  33187. *
  33188. * @param {Node} node - The node.
  33189. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  33190. * @return {NodeCache} The cache.
  33191. */
  33192. getCacheFromNode( node, parent = true ) {
  33193. const data = this.getDataFromNode( node );
  33194. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  33195. return data.cache;
  33196. }
  33197. /**
  33198. * Whether the requested feature is available or not.
  33199. *
  33200. * @abstract
  33201. * @param {string} name - The requested feature.
  33202. * @return {boolean} Whether the requested feature is supported or not.
  33203. */
  33204. isAvailable( /*name*/ ) {
  33205. return false;
  33206. }
  33207. /**
  33208. * Returns the vertexIndex input variable as a native shader string.
  33209. *
  33210. * @abstract
  33211. * @return {string} The instanceIndex shader string.
  33212. */
  33213. getVertexIndex() {
  33214. console.warn( 'Abstract function.' );
  33215. }
  33216. /**
  33217. * Returns the instanceIndex input variable as a native shader string.
  33218. *
  33219. * @abstract
  33220. * @return {string} The instanceIndex shader string.
  33221. */
  33222. getInstanceIndex() {
  33223. console.warn( 'Abstract function.' );
  33224. }
  33225. /**
  33226. * Returns the drawIndex input variable as a native shader string.
  33227. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  33228. *
  33229. * @abstract
  33230. * @return {?string} The drawIndex shader string.
  33231. */
  33232. getDrawIndex() {
  33233. console.warn( 'Abstract function.' );
  33234. }
  33235. /**
  33236. * Returns the frontFacing input variable as a native shader string.
  33237. *
  33238. * @abstract
  33239. * @return {string} The frontFacing shader string.
  33240. */
  33241. getFrontFacing() {
  33242. console.warn( 'Abstract function.' );
  33243. }
  33244. /**
  33245. * Returns the fragCoord input variable as a native shader string.
  33246. *
  33247. * @abstract
  33248. * @return {string} The fragCoord shader string.
  33249. */
  33250. getFragCoord() {
  33251. console.warn( 'Abstract function.' );
  33252. }
  33253. /**
  33254. * Whether to flip texture data along its vertical axis or not. WebGL needs
  33255. * this method evaluate to `true`, WebGPU to `false`.
  33256. *
  33257. * @abstract
  33258. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  33259. */
  33260. isFlipY() {
  33261. return false;
  33262. }
  33263. /**
  33264. * Calling this method increases the usage count for the given node by one.
  33265. *
  33266. * @param {Node} node - The node to increase the usage count for.
  33267. * @return {number} The updated usage count.
  33268. */
  33269. increaseUsage( node ) {
  33270. const nodeData = this.getDataFromNode( node );
  33271. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  33272. return nodeData.usageCount;
  33273. }
  33274. /**
  33275. * Generates a texture sample shader string for the given texture data.
  33276. *
  33277. * @abstract
  33278. * @param {Texture} texture - The texture.
  33279. * @param {string} textureProperty - The texture property name.
  33280. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  33281. * @return {string} The generated shader string.
  33282. */
  33283. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  33284. console.warn( 'Abstract function.' );
  33285. }
  33286. /**
  33287. * Generates a texture LOD shader string for the given texture data.
  33288. *
  33289. * @abstract
  33290. * @param {Texture} texture - The texture.
  33291. * @param {string} textureProperty - The texture property name.
  33292. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  33293. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  33294. * @param {string} levelSnippet - Snippet defining the mip level.
  33295. * @return {string} The generated shader string.
  33296. */
  33297. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  33298. console.warn( 'Abstract function.' );
  33299. }
  33300. /**
  33301. * Generates the array declaration string.
  33302. *
  33303. * @param {string} type - The type.
  33304. * @param {?number} [count] - The count.
  33305. * @return {string} The generated value as a shader string.
  33306. */
  33307. generateArrayDeclaration( type, count ) {
  33308. return this.getType( type ) + '[ ' + count + ' ]';
  33309. }
  33310. /**
  33311. * Generates the array shader string for the given type and value.
  33312. *
  33313. * @param {string} type - The type.
  33314. * @param {?number} [count] - The count.
  33315. * @param {?Array<Node>} [values=null] - The default values.
  33316. * @return {string} The generated value as a shader string.
  33317. */
  33318. generateArray( type, count, values = null ) {
  33319. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  33320. for ( let i = 0; i < count; i ++ ) {
  33321. const value = values ? values[ i ] : null;
  33322. if ( value !== null ) {
  33323. snippet += value.build( this, type );
  33324. } else {
  33325. snippet += this.generateConst( type );
  33326. }
  33327. if ( i < count - 1 ) snippet += ', ';
  33328. }
  33329. snippet += ' )';
  33330. return snippet;
  33331. }
  33332. /**
  33333. * Generates the struct shader string.
  33334. *
  33335. * @param {string} type - The type.
  33336. * @param {Array<Object>} [membersLayout] - The count.
  33337. * @param {?Array<Node>} [values=null] - The default values.
  33338. * @return {string} The generated value as a shader string.
  33339. */
  33340. generateStruct( type, membersLayout, values = null ) {
  33341. const snippets = [];
  33342. for ( const member of membersLayout ) {
  33343. const { name, type } = member;
  33344. if ( values && values[ name ] && values[ name ].isNode ) {
  33345. snippets.push( values[ name ].build( this, type ) );
  33346. } else {
  33347. snippets.push( this.generateConst( type ) );
  33348. }
  33349. }
  33350. return type + '( ' + snippets.join( ', ' ) + ' )';
  33351. }
  33352. /**
  33353. * Generates the shader string for the given type and value.
  33354. *
  33355. * @param {string} type - The type.
  33356. * @param {?any} [value=null] - The value.
  33357. * @return {string} The generated value as a shader string.
  33358. */
  33359. generateConst( type, value = null ) {
  33360. if ( value === null ) {
  33361. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  33362. else if ( type === 'bool' ) value = false;
  33363. else if ( type === 'color' ) value = new Color();
  33364. else if ( type === 'vec2' ) value = new Vector2();
  33365. else if ( type === 'vec3' ) value = new Vector3();
  33366. else if ( type === 'vec4' ) value = new Vector4();
  33367. }
  33368. if ( type === 'float' ) return toFloat( value );
  33369. if ( type === 'int' ) return `${ Math.round( value ) }`;
  33370. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  33371. if ( type === 'bool' ) return value ? 'true' : 'false';
  33372. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  33373. const typeLength = this.getTypeLength( type );
  33374. const componentType = this.getComponentType( type );
  33375. const generateConst = value => this.generateConst( componentType, value );
  33376. if ( typeLength === 2 ) {
  33377. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  33378. } else if ( typeLength === 3 ) {
  33379. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  33380. } else if ( typeLength === 4 && type !== 'mat2' ) {
  33381. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  33382. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  33383. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  33384. } else if ( typeLength > 4 ) {
  33385. return `${ this.getType( type ) }()`;
  33386. }
  33387. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  33388. }
  33389. /**
  33390. * It might be necessary to convert certain data types to different ones
  33391. * so this method can be used to hide the conversion.
  33392. *
  33393. * @param {string} type - The type.
  33394. * @return {string} The updated type.
  33395. */
  33396. getType( type ) {
  33397. if ( type === 'color' ) return 'vec3';
  33398. return type;
  33399. }
  33400. /**
  33401. * Whether the given attribute name is defined in the geometry or not.
  33402. *
  33403. * @param {string} name - The attribute name.
  33404. * @return {boolean} Whether the given attribute name is defined in the geometry.
  33405. */
  33406. hasGeometryAttribute( name ) {
  33407. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  33408. }
  33409. /**
  33410. * Returns a node attribute for the given name and type.
  33411. *
  33412. * @param {string} name - The attribute's name.
  33413. * @param {string} type - The attribute's type.
  33414. * @return {NodeAttribute} The node attribute.
  33415. */
  33416. getAttribute( name, type ) {
  33417. const attributes = this.attributes;
  33418. // find attribute
  33419. for ( const attribute of attributes ) {
  33420. if ( attribute.name === name ) {
  33421. return attribute;
  33422. }
  33423. }
  33424. // create a new if no exist
  33425. const attribute = new NodeAttribute( name, type );
  33426. this.registerDeclaration( attribute );
  33427. attributes.push( attribute );
  33428. return attribute;
  33429. }
  33430. /**
  33431. * Returns for the given node and shader stage the property name for the shader.
  33432. *
  33433. * @param {Node} node - The node.
  33434. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33435. * @return {string} The property name.
  33436. */
  33437. getPropertyName( node/*, shaderStage*/ ) {
  33438. return node.name;
  33439. }
  33440. /**
  33441. * Whether the given type is a vector type or not.
  33442. *
  33443. * @param {string} type - The type to check.
  33444. * @return {boolean} Whether the given type is a vector type or not.
  33445. */
  33446. isVector( type ) {
  33447. return /vec\d/.test( type );
  33448. }
  33449. /**
  33450. * Whether the given type is a matrix type or not.
  33451. *
  33452. * @param {string} type - The type to check.
  33453. * @return {boolean} Whether the given type is a matrix type or not.
  33454. */
  33455. isMatrix( type ) {
  33456. return /mat\d/.test( type );
  33457. }
  33458. /**
  33459. * Whether the given type is a reference type or not.
  33460. *
  33461. * @param {string} type - The type to check.
  33462. * @return {boolean} Whether the given type is a reference type or not.
  33463. */
  33464. isReference( type ) {
  33465. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  33466. }
  33467. /**
  33468. * Checks if the given texture requires a manual conversion to the working color space.
  33469. *
  33470. * @abstract
  33471. * @param {Texture} texture - The texture to check.
  33472. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  33473. */
  33474. needsToWorkingColorSpace( /*texture*/ ) {
  33475. return false;
  33476. }
  33477. /**
  33478. * Returns the component type of a given texture.
  33479. *
  33480. * @param {Texture} texture - The texture.
  33481. * @return {string} The component type.
  33482. */
  33483. getComponentTypeFromTexture( texture ) {
  33484. const type = texture.type;
  33485. if ( texture.isDataTexture ) {
  33486. if ( type === IntType ) return 'int';
  33487. if ( type === UnsignedIntType ) return 'uint';
  33488. }
  33489. return 'float';
  33490. }
  33491. /**
  33492. * Returns the element type for a given type.
  33493. *
  33494. * @param {string} type - The type.
  33495. * @return {string} The element type.
  33496. */
  33497. getElementType( type ) {
  33498. if ( type === 'mat2' ) return 'vec2';
  33499. if ( type === 'mat3' ) return 'vec3';
  33500. if ( type === 'mat4' ) return 'vec4';
  33501. return this.getComponentType( type );
  33502. }
  33503. /**
  33504. * Returns the component type for a given type.
  33505. *
  33506. * @param {string} type - The type.
  33507. * @return {string} The component type.
  33508. */
  33509. getComponentType( type ) {
  33510. type = this.getVectorType( type );
  33511. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  33512. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  33513. if ( componentType === null ) return null;
  33514. if ( componentType[ 1 ] === 'b' ) return 'bool';
  33515. if ( componentType[ 1 ] === 'i' ) return 'int';
  33516. if ( componentType[ 1 ] === 'u' ) return 'uint';
  33517. return 'float';
  33518. }
  33519. /**
  33520. * Returns the vector type for a given type.
  33521. *
  33522. * @param {string} type - The type.
  33523. * @return {string} The vector type.
  33524. */
  33525. getVectorType( type ) {
  33526. if ( type === 'color' ) return 'vec3';
  33527. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  33528. return type;
  33529. }
  33530. /**
  33531. * Returns the data type for the given the length and component type.
  33532. *
  33533. * @param {number} length - The length.
  33534. * @param {string} [componentType='float'] - The component type.
  33535. * @return {string} The type.
  33536. */
  33537. getTypeFromLength( length, componentType = 'float' ) {
  33538. if ( length === 1 ) return componentType;
  33539. let baseType = getTypeFromLength( length );
  33540. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  33541. // fix edge case for mat2x2 being same size as vec4
  33542. if ( /mat2/.test( componentType ) === true ) {
  33543. baseType = baseType.replace( 'vec', 'mat' );
  33544. }
  33545. return prefix + baseType;
  33546. }
  33547. /**
  33548. * Returns the type for a given typed array.
  33549. *
  33550. * @param {TypedArray} array - The typed array.
  33551. * @return {string} The type.
  33552. */
  33553. getTypeFromArray( array ) {
  33554. return typeFromArray.get( array.constructor );
  33555. }
  33556. /**
  33557. * Returns the type is an integer type.
  33558. *
  33559. * @param {string} type - The type.
  33560. * @return {boolean} Whether the type is an integer type or not.
  33561. */
  33562. isInteger( type ) {
  33563. return /int|uint|(i|u)vec/.test( type );
  33564. }
  33565. /**
  33566. * Returns the type for a given buffer attribute.
  33567. *
  33568. * @param {BufferAttribute} attribute - The buffer attribute.
  33569. * @return {string} The type.
  33570. */
  33571. getTypeFromAttribute( attribute ) {
  33572. let dataAttribute = attribute;
  33573. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  33574. const array = dataAttribute.array;
  33575. const itemSize = attribute.itemSize;
  33576. const normalized = attribute.normalized;
  33577. let arrayType;
  33578. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  33579. arrayType = this.getTypeFromArray( array );
  33580. }
  33581. return this.getTypeFromLength( itemSize, arrayType );
  33582. }
  33583. /**
  33584. * Returns the length for the given data type.
  33585. *
  33586. * @param {string} type - The data type.
  33587. * @return {number} The length.
  33588. */
  33589. getTypeLength( type ) {
  33590. const vecType = this.getVectorType( type );
  33591. const vecNum = /vec([2-4])/.exec( vecType );
  33592. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  33593. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  33594. if ( /mat2/.test( type ) === true ) return 4;
  33595. if ( /mat3/.test( type ) === true ) return 9;
  33596. if ( /mat4/.test( type ) === true ) return 16;
  33597. return 0;
  33598. }
  33599. /**
  33600. * Returns the vector type for a given matrix type.
  33601. *
  33602. * @param {string} type - The matrix type.
  33603. * @return {string} The vector type.
  33604. */
  33605. getVectorFromMatrix( type ) {
  33606. return type.replace( 'mat', 'vec' );
  33607. }
  33608. /**
  33609. * For a given type this method changes the component type to the
  33610. * given value. E.g. `vec4` should be changed to the new component type
  33611. * `uint` which results in `uvec4`.
  33612. *
  33613. * @param {string} type - The type.
  33614. * @param {string} newComponentType - The new component type.
  33615. * @return {string} The new type.
  33616. */
  33617. changeComponentType( type, newComponentType ) {
  33618. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  33619. }
  33620. /**
  33621. * Returns the integer type pendant for the given type.
  33622. *
  33623. * @param {string} type - The type.
  33624. * @return {string} The integer type.
  33625. */
  33626. getIntegerType( type ) {
  33627. const componentType = this.getComponentType( type );
  33628. if ( componentType === 'int' || componentType === 'uint' ) return type;
  33629. return this.changeComponentType( type, 'int' );
  33630. }
  33631. /**
  33632. * Adds a stack node to the internal stack.
  33633. *
  33634. * @return {StackNode} The added stack node.
  33635. */
  33636. addStack() {
  33637. this.stack = stack( this.stack );
  33638. this.stacks.push( getCurrentStack() || this.stack );
  33639. setCurrentStack( this.stack );
  33640. return this.stack;
  33641. }
  33642. /**
  33643. * Removes the last stack node from the internal stack.
  33644. *
  33645. * @return {StackNode} The removed stack node.
  33646. */
  33647. removeStack() {
  33648. const lastStack = this.stack;
  33649. this.stack = lastStack.parent;
  33650. setCurrentStack( this.stacks.pop() );
  33651. return lastStack;
  33652. }
  33653. /**
  33654. * The builder maintains (cached) data for each node during the building process. This method
  33655. * can be used to get these data for a specific shader stage and cache.
  33656. *
  33657. * @param {Node} node - The node to get the data for.
  33658. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  33659. * @param {?NodeCache} cache - An optional cache.
  33660. * @return {Object} The node data.
  33661. */
  33662. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  33663. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  33664. let nodeData = cache.getData( node );
  33665. if ( nodeData === undefined ) {
  33666. nodeData = {};
  33667. cache.setData( node, nodeData );
  33668. }
  33669. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  33670. //
  33671. let data = nodeData[ shaderStage ];
  33672. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  33673. const subBuild = this.getClosestSubBuild( subBuilds );
  33674. if ( subBuild ) {
  33675. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  33676. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  33677. data.subBuilds = subBuilds;
  33678. }
  33679. return data;
  33680. }
  33681. /**
  33682. * Returns the properties for the given node and shader stage.
  33683. *
  33684. * @param {Node} node - The node to get the properties for.
  33685. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  33686. * @return {Object} The node properties.
  33687. */
  33688. getNodeProperties( node, shaderStage = 'any' ) {
  33689. const nodeData = this.getDataFromNode( node, shaderStage );
  33690. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  33691. }
  33692. /**
  33693. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  33694. *
  33695. * @param {BufferAttributeNode} node - The buffer attribute node.
  33696. * @param {string} type - The node type.
  33697. * @return {NodeAttribute} The node attribute.
  33698. */
  33699. getBufferAttributeFromNode( node, type ) {
  33700. const nodeData = this.getDataFromNode( node );
  33701. let bufferAttribute = nodeData.bufferAttribute;
  33702. if ( bufferAttribute === undefined ) {
  33703. const index = this.uniforms.index ++;
  33704. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  33705. this.bufferAttributes.push( bufferAttribute );
  33706. nodeData.bufferAttribute = bufferAttribute;
  33707. }
  33708. return bufferAttribute;
  33709. }
  33710. /**
  33711. * Returns an instance of {@link StructType} for the given output struct node.
  33712. *
  33713. * @param {OutputStructNode} node - The output struct node.
  33714. * @param {Array<Object>} membersLayout - The output struct types.
  33715. * @param {?string} [name=null] - The name of the struct.
  33716. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  33717. * @return {StructType} The struct type attribute.
  33718. */
  33719. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  33720. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  33721. let structType = nodeData.structType;
  33722. if ( structType === undefined ) {
  33723. const index = this.structs.index ++;
  33724. if ( name === null ) name = 'StructType' + index;
  33725. structType = new StructType( name, membersLayout );
  33726. this.structs[ shaderStage ].push( structType );
  33727. nodeData.structType = structType;
  33728. }
  33729. return structType;
  33730. }
  33731. /**
  33732. * Returns an instance of {@link StructType} for the given output struct node.
  33733. *
  33734. * @param {OutputStructNode} node - The output struct node.
  33735. * @param {Array<Object>} membersLayout - The output struct types.
  33736. * @return {StructType} The struct type attribute.
  33737. */
  33738. getOutputStructTypeFromNode( node, membersLayout ) {
  33739. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  33740. structType.output = true;
  33741. return structType;
  33742. }
  33743. /**
  33744. * Returns an instance of {@link NodeUniform} for the given uniform node.
  33745. *
  33746. * @param {UniformNode} node - The uniform node.
  33747. * @param {string} type - The uniform type.
  33748. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  33749. * @param {?string} name - The name of the uniform.
  33750. * @return {NodeUniform} The node uniform.
  33751. */
  33752. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  33753. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  33754. let nodeUniform = nodeData.uniform;
  33755. if ( nodeUniform === undefined ) {
  33756. const index = this.uniforms.index ++;
  33757. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  33758. this.uniforms[ shaderStage ].push( nodeUniform );
  33759. this.registerDeclaration( nodeUniform );
  33760. nodeData.uniform = nodeUniform;
  33761. }
  33762. return nodeUniform;
  33763. }
  33764. /**
  33765. * Returns an instance of {@link NodeVar} for the given variable node.
  33766. *
  33767. * @param {VarNode} node - The variable node.
  33768. * @param {?string} name - The variable's name.
  33769. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  33770. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  33771. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  33772. *
  33773. * @return {NodeVar} The node variable.
  33774. */
  33775. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  33776. const nodeData = this.getDataFromNode( node, shaderStage );
  33777. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  33778. let nodeVar = nodeData[ subBuildVariable ];
  33779. if ( nodeVar === undefined ) {
  33780. const idNS = readOnly ? '_const' : '_var';
  33781. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  33782. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  33783. if ( name === null ) {
  33784. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  33785. this.vars[ idNS ] ++;
  33786. }
  33787. //
  33788. if ( subBuildVariable !== 'variable' ) {
  33789. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  33790. }
  33791. //
  33792. const count = node.getArrayCount( this );
  33793. nodeVar = new NodeVar( name, type, readOnly, count );
  33794. if ( ! readOnly ) {
  33795. vars.push( nodeVar );
  33796. }
  33797. this.registerDeclaration( nodeVar );
  33798. nodeData[ subBuildVariable ] = nodeVar;
  33799. }
  33800. return nodeVar;
  33801. }
  33802. /**
  33803. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  33804. *
  33805. * @param {Node} node - The varying node.
  33806. * @return {boolean} Returns true if deterministic.
  33807. */
  33808. isDeterministic( node ) {
  33809. if ( node.isMathNode ) {
  33810. return this.isDeterministic( node.aNode ) &&
  33811. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  33812. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  33813. } else if ( node.isOperatorNode ) {
  33814. return this.isDeterministic( node.aNode ) &&
  33815. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  33816. } else if ( node.isArrayNode ) {
  33817. if ( node.values !== null ) {
  33818. for ( const n of node.values ) {
  33819. if ( ! this.isDeterministic( n ) ) {
  33820. return false;
  33821. }
  33822. }
  33823. }
  33824. return true;
  33825. } else if ( node.isConstNode ) {
  33826. return true;
  33827. }
  33828. return false;
  33829. }
  33830. /**
  33831. * Returns an instance of {@link NodeVarying} for the given varying node.
  33832. *
  33833. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  33834. * @param {?string} name - The varying's name.
  33835. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  33836. * @param {?string} interpolationType - The interpolation type of the varying.
  33837. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  33838. * @return {NodeVar} The node varying.
  33839. */
  33840. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  33841. const nodeData = this.getDataFromNode( node, 'any' );
  33842. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  33843. let nodeVarying = nodeData[ subBuildVarying ];
  33844. if ( nodeVarying === undefined ) {
  33845. const varyings = this.varyings;
  33846. const index = varyings.length;
  33847. if ( name === null ) name = 'nodeVarying' + index;
  33848. //
  33849. if ( subBuildVarying !== 'varying' ) {
  33850. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  33851. }
  33852. //
  33853. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  33854. varyings.push( nodeVarying );
  33855. this.registerDeclaration( nodeVarying );
  33856. nodeData[ subBuildVarying ] = nodeVarying;
  33857. }
  33858. return nodeVarying;
  33859. }
  33860. /**
  33861. * Registers a node declaration in the current shader stage.
  33862. *
  33863. * @param {Object} node - The node to be registered.
  33864. */
  33865. registerDeclaration( node ) {
  33866. const shaderStage = this.shaderStage;
  33867. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  33868. const property = this.getPropertyName( node );
  33869. let index = 1;
  33870. let name = property;
  33871. // Automatically renames the property if the name is already in use.
  33872. while ( declarations[ name ] !== undefined ) {
  33873. name = property + '_' + index ++;
  33874. }
  33875. if ( index > 1 ) {
  33876. node.name = name;
  33877. console.warn( `THREE.TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  33878. }
  33879. declarations[ name ] = node;
  33880. }
  33881. /**
  33882. * Returns an instance of {@link NodeCode} for the given code node.
  33883. *
  33884. * @param {CodeNode} node - The code node.
  33885. * @param {string} type - The node type.
  33886. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  33887. * @return {NodeCode} The node code.
  33888. */
  33889. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  33890. const nodeData = this.getDataFromNode( node );
  33891. let nodeCode = nodeData.code;
  33892. if ( nodeCode === undefined ) {
  33893. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  33894. const index = codes.length;
  33895. nodeCode = new NodeCode( 'nodeCode' + index, type );
  33896. codes.push( nodeCode );
  33897. nodeData.code = nodeCode;
  33898. }
  33899. return nodeCode;
  33900. }
  33901. /**
  33902. * Adds a code flow based on the code-block hierarchy.
  33903. * This is used so that code-blocks like If,Else create their variables locally if the Node
  33904. * is only used inside one of these conditionals in the current shader stage.
  33905. *
  33906. * @param {Node} node - The node to add.
  33907. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  33908. */
  33909. addFlowCodeHierarchy( node, nodeBlock ) {
  33910. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  33911. let needsFlowCode = true;
  33912. let nodeBlockHierarchy = nodeBlock;
  33913. while ( nodeBlockHierarchy ) {
  33914. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  33915. needsFlowCode = false;
  33916. break;
  33917. }
  33918. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  33919. }
  33920. if ( needsFlowCode ) {
  33921. for ( const flowCode of flowCodes ) {
  33922. this.addLineFlowCode( flowCode );
  33923. }
  33924. }
  33925. }
  33926. /**
  33927. * Add a inline-code to the current flow code-block.
  33928. *
  33929. * @param {Node} node - The node to add.
  33930. * @param {string} code - The code to add.
  33931. * @param {Node} nodeBlock - Current ConditionalNode
  33932. */
  33933. addLineFlowCodeBlock( node, code, nodeBlock ) {
  33934. const nodeData = this.getDataFromNode( node );
  33935. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  33936. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  33937. flowCodes.push( code );
  33938. codeBlock.set( nodeBlock, true );
  33939. }
  33940. /**
  33941. * Add a inline-code to the current flow.
  33942. *
  33943. * @param {string} code - The code to add.
  33944. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  33945. * @return {NodeBuilder} A reference to this node builder.
  33946. */
  33947. addLineFlowCode( code, node = null ) {
  33948. if ( code === '' ) return this;
  33949. if ( node !== null && this.context.nodeBlock ) {
  33950. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  33951. }
  33952. code = this.tab + code;
  33953. if ( ! /;\s*$/.test( code ) ) {
  33954. code = code + ';\n';
  33955. }
  33956. this.flow.code += code;
  33957. return this;
  33958. }
  33959. /**
  33960. * Adds a code to the current code flow.
  33961. *
  33962. * @param {string} code - Shader code.
  33963. * @return {NodeBuilder} A reference to this node builder.
  33964. */
  33965. addFlowCode( code ) {
  33966. this.flow.code += code;
  33967. return this;
  33968. }
  33969. /**
  33970. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  33971. * Typically used in codes with If,Else.
  33972. *
  33973. * @return {NodeBuilder} A reference to this node builder.
  33974. */
  33975. addFlowTab() {
  33976. this.tab += '\t';
  33977. return this;
  33978. }
  33979. /**
  33980. * Removes a tab.
  33981. *
  33982. * @return {NodeBuilder} A reference to this node builder.
  33983. */
  33984. removeFlowTab() {
  33985. this.tab = this.tab.slice( 0, -1 );
  33986. return this;
  33987. }
  33988. /**
  33989. * Gets the current flow data based on a Node.
  33990. *
  33991. * @param {Node} node - Node that the flow was started.
  33992. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33993. * @return {Object} The flow data.
  33994. */
  33995. getFlowData( node/*, shaderStage*/ ) {
  33996. return this.flowsData.get( node );
  33997. }
  33998. /**
  33999. * Executes the node flow based on a root node to generate the final shader code.
  34000. *
  34001. * @param {Node} node - The node to execute.
  34002. * @return {Object} The code flow.
  34003. */
  34004. flowNode( node ) {
  34005. const output = node.getNodeType( this );
  34006. const flowData = this.flowChildNode( node, output );
  34007. this.flowsData.set( node, flowData );
  34008. return flowData;
  34009. }
  34010. /**
  34011. * Includes a node in the current function node.
  34012. *
  34013. * @param {Node} node - The node to include.
  34014. * @returns {void}
  34015. */
  34016. addInclude( node ) {
  34017. if ( this.currentFunctionNode !== null ) {
  34018. this.currentFunctionNode.includes.push( node );
  34019. }
  34020. }
  34021. /**
  34022. * Returns the native shader operator name for a given generic name.
  34023. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  34024. *
  34025. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  34026. * @return {FunctionNode} The build function node.
  34027. */
  34028. buildFunctionNode( shaderNode ) {
  34029. const fn = new FunctionNode();
  34030. const previous = this.currentFunctionNode;
  34031. this.currentFunctionNode = fn;
  34032. fn.code = this.buildFunctionCode( shaderNode );
  34033. this.currentFunctionNode = previous;
  34034. return fn;
  34035. }
  34036. /**
  34037. * Generates a code flow based on a TSL function: Fn().
  34038. *
  34039. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  34040. * @return {Object}
  34041. */
  34042. flowShaderNode( shaderNode ) {
  34043. const layout = shaderNode.layout;
  34044. const inputs = {
  34045. [ Symbol.iterator ]() {
  34046. let index = 0;
  34047. const values = Object.values( this );
  34048. return {
  34049. next: () => ( {
  34050. value: values[ index ],
  34051. done: index ++ >= values.length
  34052. } )
  34053. };
  34054. }
  34055. };
  34056. for ( const input of layout.inputs ) {
  34057. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  34058. }
  34059. //
  34060. shaderNode.layout = null;
  34061. const callNode = shaderNode.call( inputs );
  34062. const flowData = this.flowStagesNode( callNode, layout.type );
  34063. shaderNode.layout = layout;
  34064. return flowData;
  34065. }
  34066. /**
  34067. * Executes the node in a specific build stage.
  34068. *
  34069. * @param {Node} node - The node to execute.
  34070. * @param {string} buildStage - The build stage to execute the node in.
  34071. * @param {Node|string|null} output - Expected output type. For example 'vec3'.
  34072. * @return {Node|string|null} The result of the node build.
  34073. */
  34074. flowBuildStage( node, buildStage, output = null ) {
  34075. const previousBuildStage = this.getBuildStage();
  34076. this.setBuildStage( buildStage );
  34077. const result = node.build( this, output );
  34078. this.setBuildStage( previousBuildStage );
  34079. return result;
  34080. }
  34081. /**
  34082. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  34083. *
  34084. * @param {Node} node - The node to execute.
  34085. * @param {?string} output - Expected output type. For example 'vec3'.
  34086. * @return {Object}
  34087. */
  34088. flowStagesNode( node, output = null ) {
  34089. const previousFlow = this.flow;
  34090. const previousVars = this.vars;
  34091. const previousDeclarations = this.declarations;
  34092. const previousCache = this.cache;
  34093. const previousBuildStage = this.buildStage;
  34094. const previousStack = this.stack;
  34095. const flow = {
  34096. code: ''
  34097. };
  34098. this.flow = flow;
  34099. this.vars = {};
  34100. this.declarations = {};
  34101. this.cache = new NodeCache();
  34102. this.stack = stack();
  34103. for ( const buildStage of defaultBuildStages ) {
  34104. this.setBuildStage( buildStage );
  34105. flow.result = node.build( this, output );
  34106. }
  34107. flow.vars = this.getVars( this.shaderStage );
  34108. this.flow = previousFlow;
  34109. this.vars = previousVars;
  34110. this.declarations = previousDeclarations;
  34111. this.cache = previousCache;
  34112. this.stack = previousStack;
  34113. this.setBuildStage( previousBuildStage );
  34114. return flow;
  34115. }
  34116. /**
  34117. * Returns the native shader operator name for a given generic name.
  34118. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  34119. *
  34120. * @abstract
  34121. * @param {string} op - The operator name to resolve.
  34122. * @return {?string} The resolved operator name.
  34123. */
  34124. getFunctionOperator( /* op */ ) {
  34125. return null;
  34126. }
  34127. /**
  34128. * Builds the given shader node.
  34129. *
  34130. * @abstract
  34131. * @param {ShaderNodeInternal} shaderNode - The shader node.
  34132. * @return {string} The function code.
  34133. */
  34134. buildFunctionCode( /* shaderNode */ ) {
  34135. console.warn( 'Abstract function.' );
  34136. }
  34137. /**
  34138. * Generates a code flow based on a child Node.
  34139. *
  34140. * @param {Node} node - The node to execute.
  34141. * @param {?string} output - Expected output type. For example 'vec3'.
  34142. * @return {Object} The code flow.
  34143. */
  34144. flowChildNode( node, output = null ) {
  34145. const previousFlow = this.flow;
  34146. const flow = {
  34147. code: ''
  34148. };
  34149. this.flow = flow;
  34150. flow.result = node.build( this, output );
  34151. this.flow = previousFlow;
  34152. return flow;
  34153. }
  34154. /**
  34155. * Executes a flow of code in a different stage.
  34156. *
  34157. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  34158. * return the value in fragment-stage even if it is being executed in an input fragment.
  34159. *
  34160. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34161. * @param {Node} node - The node to execute.
  34162. * @param {?string} output - Expected output type. For example 'vec3'.
  34163. * @param {?string} propertyName - The property name to assign the result.
  34164. * @return {Object|Node|null} The code flow or node.build() result.
  34165. */
  34166. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  34167. const previousTab = this.tab;
  34168. const previousCache = this.cache;
  34169. const previousShaderStage = this.shaderStage;
  34170. const previousContext = this.context;
  34171. this.setShaderStage( shaderStage );
  34172. const context = { ...this.context };
  34173. delete context.nodeBlock;
  34174. this.cache = this.globalCache;
  34175. this.tab = '\t';
  34176. this.context = context;
  34177. let result = null;
  34178. if ( this.buildStage === 'generate' ) {
  34179. const flowData = this.flowChildNode( node, output );
  34180. if ( propertyName !== null ) {
  34181. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  34182. }
  34183. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  34184. result = flowData;
  34185. } else {
  34186. result = node.build( this );
  34187. }
  34188. this.setShaderStage( previousShaderStage );
  34189. this.cache = previousCache;
  34190. this.tab = previousTab;
  34191. this.context = previousContext;
  34192. return result;
  34193. }
  34194. /**
  34195. * Returns an array holding all node attributes of this node builder.
  34196. *
  34197. * @return {Array<NodeAttribute>} The node attributes of this builder.
  34198. */
  34199. getAttributesArray() {
  34200. return this.attributes.concat( this.bufferAttributes );
  34201. }
  34202. /**
  34203. * Returns the attribute definitions as a shader string for the given shader stage.
  34204. *
  34205. * @abstract
  34206. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34207. * @return {string} The attribute code section.
  34208. */
  34209. getAttributes( /*shaderStage*/ ) {
  34210. console.warn( 'Abstract function.' );
  34211. }
  34212. /**
  34213. * Returns the varying definitions as a shader string for the given shader stage.
  34214. *
  34215. * @abstract
  34216. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34217. * @return {string} The varying code section.
  34218. */
  34219. getVaryings( /*shaderStage*/ ) {
  34220. console.warn( 'Abstract function.' );
  34221. }
  34222. /**
  34223. * Returns a single variable definition as a shader string for the given variable type and name.
  34224. *
  34225. * @param {string} type - The variable's type.
  34226. * @param {string} name - The variable's name.
  34227. * @param {?number} [count=null] - The array length.
  34228. * @return {string} The shader string.
  34229. */
  34230. getVar( type, name, count = null ) {
  34231. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  34232. }
  34233. /**
  34234. * Returns the variable definitions as a shader string for the given shader stage.
  34235. *
  34236. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34237. * @return {string} The variable code section.
  34238. */
  34239. getVars( shaderStage ) {
  34240. let snippet = '';
  34241. const vars = this.vars[ shaderStage ];
  34242. if ( vars !== undefined ) {
  34243. for ( const variable of vars ) {
  34244. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  34245. }
  34246. }
  34247. return snippet;
  34248. }
  34249. /**
  34250. * Returns the uniform definitions as a shader string for the given shader stage.
  34251. *
  34252. * @abstract
  34253. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34254. * @return {string} The uniform code section.
  34255. */
  34256. getUniforms( /*shaderStage*/ ) {
  34257. console.warn( 'Abstract function.' );
  34258. }
  34259. /**
  34260. * Returns the native code definitions as a shader string for the given shader stage.
  34261. *
  34262. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34263. * @return {string} The native code section.
  34264. */
  34265. getCodes( shaderStage ) {
  34266. const codes = this.codes[ shaderStage ];
  34267. let code = '';
  34268. if ( codes !== undefined ) {
  34269. for ( const nodeCode of codes ) {
  34270. code += nodeCode.code + '\n';
  34271. }
  34272. }
  34273. return code;
  34274. }
  34275. /**
  34276. * Returns the hash of this node builder.
  34277. *
  34278. * @return {string} The hash.
  34279. */
  34280. getHash() {
  34281. return this.vertexShader + this.fragmentShader + this.computeShader;
  34282. }
  34283. /**
  34284. * Sets the current shader stage.
  34285. *
  34286. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  34287. */
  34288. setShaderStage( shaderStage ) {
  34289. this.shaderStage = shaderStage;
  34290. }
  34291. /**
  34292. * Returns the current shader stage.
  34293. *
  34294. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  34295. */
  34296. getShaderStage() {
  34297. return this.shaderStage;
  34298. }
  34299. /**
  34300. * Sets the current build stage.
  34301. *
  34302. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  34303. */
  34304. setBuildStage( buildStage ) {
  34305. this.buildStage = buildStage;
  34306. }
  34307. /**
  34308. * Returns the current build stage.
  34309. *
  34310. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  34311. */
  34312. getBuildStage() {
  34313. return this.buildStage;
  34314. }
  34315. /**
  34316. * Controls the code build of the shader stages.
  34317. *
  34318. * @abstract
  34319. */
  34320. buildCode() {
  34321. console.warn( 'Abstract function.' );
  34322. }
  34323. /**
  34324. * Returns the current sub-build layer.
  34325. *
  34326. * @return {SubBuildNode} The current sub-build layers.
  34327. */
  34328. get subBuild() {
  34329. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  34330. }
  34331. /**
  34332. * Adds a sub-build layer to the node builder.
  34333. *
  34334. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  34335. */
  34336. addSubBuild( subBuild ) {
  34337. this.subBuildLayers.push( subBuild );
  34338. }
  34339. /**
  34340. * Removes the last sub-build layer from the node builder.
  34341. *
  34342. * @return {SubBuildNode} The removed sub-build layer.
  34343. */
  34344. removeSubBuild() {
  34345. return this.subBuildLayers.pop();
  34346. }
  34347. /**
  34348. * Returns the closest sub-build layer for the given data.
  34349. *
  34350. * @param {Node|Set|Array} data - The data to get the closest sub-build layer from.
  34351. * @return {?string} The closest sub-build name or null if none found.
  34352. */
  34353. getClosestSubBuild( data ) {
  34354. let subBuilds;
  34355. if ( data && data.isNode ) {
  34356. if ( data.isShaderCallNodeInternal ) {
  34357. subBuilds = data.shaderNode.subBuilds;
  34358. } else if ( data.isStackNode ) {
  34359. subBuilds = [ data.subBuild ];
  34360. } else {
  34361. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  34362. }
  34363. } else if ( data instanceof Set ) {
  34364. subBuilds = [ ...data ];
  34365. } else {
  34366. subBuilds = data;
  34367. }
  34368. if ( ! subBuilds ) return null;
  34369. const subBuildLayers = this.subBuildLayers;
  34370. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  34371. const subBuild = subBuilds[ i ];
  34372. if ( subBuildLayers.includes( subBuild ) ) {
  34373. return subBuild;
  34374. }
  34375. }
  34376. return null;
  34377. }
  34378. /**
  34379. * Returns the output node of a sub-build layer.
  34380. *
  34381. * @param {Node} node - The node to get the output from.
  34382. * @return {string} The output node name.
  34383. */
  34384. getSubBuildOutput( node ) {
  34385. return this.getSubBuildProperty( 'outputNode', node );
  34386. }
  34387. /**
  34388. * Returns the sub-build property name for the given property and node.
  34389. *
  34390. * @param {string} [property=''] - The property name.
  34391. * @param {?Node} [node=null] - The node to get the sub-build from.
  34392. * @return {string} The sub-build property name.
  34393. */
  34394. getSubBuildProperty( property = '', node = null ) {
  34395. let subBuild;
  34396. if ( node !== null ) {
  34397. subBuild = this.getClosestSubBuild( node );
  34398. } else {
  34399. subBuild = this.subBuildFn;
  34400. }
  34401. let result;
  34402. if ( subBuild ) {
  34403. result = property ? ( subBuild + '_' + property ) : subBuild;
  34404. } else {
  34405. result = property;
  34406. }
  34407. return result;
  34408. }
  34409. /**
  34410. * Central build method which controls the build for the given object.
  34411. *
  34412. * @return {NodeBuilder} A reference to this node builder.
  34413. */
  34414. build() {
  34415. const { object, material, renderer } = this;
  34416. if ( material !== null ) {
  34417. let nodeMaterial = renderer.library.fromMaterial( material );
  34418. if ( nodeMaterial === null ) {
  34419. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  34420. nodeMaterial = new NodeMaterial();
  34421. }
  34422. nodeMaterial.build( this );
  34423. } else {
  34424. this.addFlow( 'compute', object );
  34425. }
  34426. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  34427. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  34428. // generate() -> stage 3: generate shader
  34429. for ( const buildStage of defaultBuildStages ) {
  34430. this.setBuildStage( buildStage );
  34431. if ( this.context.vertex && this.context.vertex.isNode ) {
  34432. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  34433. }
  34434. for ( const shaderStage of shaderStages ) {
  34435. this.setShaderStage( shaderStage );
  34436. const flowNodes = this.flowNodes[ shaderStage ];
  34437. for ( const node of flowNodes ) {
  34438. if ( buildStage === 'generate' ) {
  34439. this.flowNode( node );
  34440. } else {
  34441. node.build( this );
  34442. }
  34443. }
  34444. }
  34445. }
  34446. this.setBuildStage( null );
  34447. this.setShaderStage( null );
  34448. // stage 4: build code for a specific output
  34449. this.buildCode();
  34450. this.buildUpdateNodes();
  34451. return this;
  34452. }
  34453. /**
  34454. * Returns a uniform representation which is later used for UBO generation and rendering.
  34455. *
  34456. * @param {NodeUniform} uniformNode - The uniform node.
  34457. * @param {string} type - The requested type.
  34458. * @return {Uniform} The uniform.
  34459. */
  34460. getNodeUniform( uniformNode, type ) {
  34461. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  34462. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  34463. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  34464. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  34465. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  34466. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  34467. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  34468. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  34469. throw new Error( `Uniform "${type}" not declared.` );
  34470. }
  34471. /**
  34472. * Formats the given shader snippet from a given type into another one. E.g.
  34473. * this method might be used to convert a simple float string `"1.0"` into a
  34474. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  34475. *
  34476. * @param {string} snippet - The shader snippet.
  34477. * @param {string} fromType - The source type.
  34478. * @param {string} toType - The target type.
  34479. * @return {string} The updated shader string.
  34480. */
  34481. format( snippet, fromType, toType ) {
  34482. fromType = this.getVectorType( fromType );
  34483. toType = this.getVectorType( toType );
  34484. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  34485. return snippet;
  34486. }
  34487. const fromTypeLength = this.getTypeLength( fromType );
  34488. const toTypeLength = this.getTypeLength( toType );
  34489. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  34490. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  34491. }
  34492. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  34493. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  34494. }
  34495. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  34496. // @TODO: ignore for now
  34497. return snippet;
  34498. }
  34499. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  34500. // @TODO: ignore for now
  34501. return snippet;
  34502. }
  34503. if ( fromTypeLength === toTypeLength ) {
  34504. return `${ this.getType( toType ) }( ${ snippet } )`;
  34505. }
  34506. if ( fromTypeLength > toTypeLength ) {
  34507. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  34508. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  34509. }
  34510. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  34511. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  34512. }
  34513. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  34514. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  34515. }
  34516. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  34517. // convert a number value to vector type, e.g:
  34518. // vec3( 1u ) -> vec3( float( 1u ) )
  34519. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  34520. }
  34521. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  34522. }
  34523. /**
  34524. * Returns a signature with the engine's current revision.
  34525. *
  34526. * @return {string} The signature.
  34527. */
  34528. getSignature() {
  34529. return `// Three.js r${ REVISION } - Node System\n`;
  34530. }
  34531. }
  34532. /**
  34533. * Management class for updating nodes. The module tracks metrics like
  34534. * the elapsed time, delta time, the render and frame ID to correctly
  34535. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  34536. * and {@link Node#updateAfter} depending on the node's configuration.
  34537. */
  34538. class NodeFrame {
  34539. /**
  34540. * Constructs a new node fame.
  34541. */
  34542. constructor() {
  34543. /**
  34544. * The elapsed time in seconds.
  34545. *
  34546. * @type {number}
  34547. * @default 0
  34548. */
  34549. this.time = 0;
  34550. /**
  34551. * The delta time in seconds.
  34552. *
  34553. * @type {number}
  34554. * @default 0
  34555. */
  34556. this.deltaTime = 0;
  34557. /**
  34558. * The frame ID.
  34559. *
  34560. * @type {number}
  34561. * @default 0
  34562. */
  34563. this.frameId = 0;
  34564. /**
  34565. * The render ID.
  34566. *
  34567. * @type {number}
  34568. * @default 0
  34569. */
  34570. this.renderId = 0;
  34571. /**
  34572. * Used to control the {@link Node#update} call.
  34573. *
  34574. * @type {WeakMap<Node, Object>}
  34575. */
  34576. this.updateMap = new WeakMap();
  34577. /**
  34578. * Used to control the {@link Node#updateBefore} call.
  34579. *
  34580. * @type {WeakMap<Node, Object>}
  34581. */
  34582. this.updateBeforeMap = new WeakMap();
  34583. /**
  34584. * Used to control the {@link Node#updateAfter} call.
  34585. *
  34586. * @type {WeakMap<Node, Object>}
  34587. */
  34588. this.updateAfterMap = new WeakMap();
  34589. /**
  34590. * A reference to the current renderer.
  34591. *
  34592. * @type {?Renderer}
  34593. * @default null
  34594. */
  34595. this.renderer = null;
  34596. /**
  34597. * A reference to the current material.
  34598. *
  34599. * @type {?Material}
  34600. * @default null
  34601. */
  34602. this.material = null;
  34603. /**
  34604. * A reference to the current camera.
  34605. *
  34606. * @type {?Camera}
  34607. * @default null
  34608. */
  34609. this.camera = null;
  34610. /**
  34611. * A reference to the current 3D object.
  34612. *
  34613. * @type {?Object3D}
  34614. * @default null
  34615. */
  34616. this.object = null;
  34617. /**
  34618. * A reference to the current scene.
  34619. *
  34620. * @type {?Scene}
  34621. * @default null
  34622. */
  34623. this.scene = null;
  34624. }
  34625. /**
  34626. * Returns a dictionary for a given node and update map which
  34627. * is used to correctly call node update methods per frame or render.
  34628. *
  34629. * @private
  34630. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  34631. * @param {Node} nodeRef - The reference to the current node.
  34632. * @return {Object<string,WeakMap>} The dictionary.
  34633. */
  34634. _getMaps( referenceMap, nodeRef ) {
  34635. let maps = referenceMap.get( nodeRef );
  34636. if ( maps === undefined ) {
  34637. maps = {
  34638. renderMap: new WeakMap(),
  34639. frameMap: new WeakMap()
  34640. };
  34641. referenceMap.set( nodeRef, maps );
  34642. }
  34643. return maps;
  34644. }
  34645. /**
  34646. * This method executes the {@link Node#updateBefore} for the given node.
  34647. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  34648. * is only executed once per frame, render or object depending on the update
  34649. * type.
  34650. *
  34651. * @param {Node} node - The node that should be updated.
  34652. */
  34653. updateBeforeNode( node ) {
  34654. const updateType = node.getUpdateBeforeType();
  34655. const reference = node.updateReference( this );
  34656. if ( updateType === NodeUpdateType.FRAME ) {
  34657. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  34658. if ( frameMap.get( reference ) !== this.frameId ) {
  34659. if ( node.updateBefore( this ) !== false ) {
  34660. frameMap.set( reference, this.frameId );
  34661. }
  34662. }
  34663. } else if ( updateType === NodeUpdateType.RENDER ) {
  34664. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  34665. if ( renderMap.get( reference ) !== this.renderId ) {
  34666. if ( node.updateBefore( this ) !== false ) {
  34667. renderMap.set( reference, this.renderId );
  34668. }
  34669. }
  34670. } else if ( updateType === NodeUpdateType.OBJECT ) {
  34671. node.updateBefore( this );
  34672. }
  34673. }
  34674. /**
  34675. * This method executes the {@link Node#updateAfter} for the given node.
  34676. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  34677. * is only executed once per frame, render or object depending on the update
  34678. * type.
  34679. *
  34680. * @param {Node} node - The node that should be updated.
  34681. */
  34682. updateAfterNode( node ) {
  34683. const updateType = node.getUpdateAfterType();
  34684. const reference = node.updateReference( this );
  34685. if ( updateType === NodeUpdateType.FRAME ) {
  34686. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  34687. if ( frameMap.get( reference ) !== this.frameId ) {
  34688. if ( node.updateAfter( this ) !== false ) {
  34689. frameMap.set( reference, this.frameId );
  34690. }
  34691. }
  34692. } else if ( updateType === NodeUpdateType.RENDER ) {
  34693. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  34694. if ( renderMap.get( reference ) !== this.renderId ) {
  34695. if ( node.updateAfter( this ) !== false ) {
  34696. renderMap.set( reference, this.renderId );
  34697. }
  34698. }
  34699. } else if ( updateType === NodeUpdateType.OBJECT ) {
  34700. node.updateAfter( this );
  34701. }
  34702. }
  34703. /**
  34704. * This method executes the {@link Node#update} for the given node.
  34705. * It makes sure {@link Node#updateType} is honored meaning the update
  34706. * is only executed once per frame, render or object depending on the update
  34707. * type.
  34708. *
  34709. * @param {Node} node - The node that should be updated.
  34710. */
  34711. updateNode( node ) {
  34712. const updateType = node.getUpdateType();
  34713. const reference = node.updateReference( this );
  34714. if ( updateType === NodeUpdateType.FRAME ) {
  34715. const { frameMap } = this._getMaps( this.updateMap, reference );
  34716. if ( frameMap.get( reference ) !== this.frameId ) {
  34717. if ( node.update( this ) !== false ) {
  34718. frameMap.set( reference, this.frameId );
  34719. }
  34720. }
  34721. } else if ( updateType === NodeUpdateType.RENDER ) {
  34722. const { renderMap } = this._getMaps( this.updateMap, reference );
  34723. if ( renderMap.get( reference ) !== this.renderId ) {
  34724. if ( node.update( this ) !== false ) {
  34725. renderMap.set( reference, this.renderId );
  34726. }
  34727. }
  34728. } else if ( updateType === NodeUpdateType.OBJECT ) {
  34729. node.update( this );
  34730. }
  34731. }
  34732. /**
  34733. * Updates the internal state of the node frame. This method is
  34734. * called by the renderer in its internal animation loop.
  34735. */
  34736. update() {
  34737. this.frameId ++;
  34738. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  34739. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  34740. this.lastTime = performance.now();
  34741. this.time += this.deltaTime;
  34742. }
  34743. }
  34744. /**
  34745. * Describes the input of a {@link NodeFunction}.
  34746. */
  34747. class NodeFunctionInput {
  34748. /**
  34749. * Constructs a new node function input.
  34750. *
  34751. * @param {string} type - The input type.
  34752. * @param {string} name - The input name.
  34753. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  34754. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  34755. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  34756. */
  34757. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  34758. /**
  34759. * The input type.
  34760. *
  34761. * @type {string}
  34762. */
  34763. this.type = type;
  34764. /**
  34765. * The input name.
  34766. *
  34767. * @type {string}
  34768. */
  34769. this.name = name;
  34770. /**
  34771. * If the input is an Array, count will be the length.
  34772. *
  34773. * @type {?number}
  34774. * @default null
  34775. */
  34776. this.count = count;
  34777. /**
  34778. *The parameter qualifier (only relevant for GLSL).
  34779. *
  34780. * @type {('in'|'out'|'inout')}
  34781. * @default ''
  34782. */
  34783. this.qualifier = qualifier;
  34784. /**
  34785. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  34786. *
  34787. * @type {boolean}
  34788. * @default false
  34789. */
  34790. this.isConst = isConst;
  34791. }
  34792. }
  34793. NodeFunctionInput.isNodeFunctionInput = true;
  34794. /**
  34795. * Module for representing directional lights as nodes.
  34796. *
  34797. * @augments AnalyticLightNode
  34798. */
  34799. class DirectionalLightNode extends AnalyticLightNode {
  34800. static get type() {
  34801. return 'DirectionalLightNode';
  34802. }
  34803. /**
  34804. * Constructs a new directional light node.
  34805. *
  34806. * @param {?DirectionalLight} [light=null] - The directional light source.
  34807. */
  34808. constructor( light = null ) {
  34809. super( light );
  34810. }
  34811. setupDirect() {
  34812. const lightColor = this.colorNode;
  34813. const lightDirection = lightTargetDirection( this.light );
  34814. return { lightDirection, lightColor };
  34815. }
  34816. }
  34817. const _matrix41 = /*@__PURE__*/ new Matrix4();
  34818. const _matrix42 = /*@__PURE__*/ new Matrix4();
  34819. let _ltcLib = null;
  34820. /**
  34821. * Module for representing rect area lights as nodes.
  34822. *
  34823. * @augments AnalyticLightNode
  34824. */
  34825. class RectAreaLightNode extends AnalyticLightNode {
  34826. static get type() {
  34827. return 'RectAreaLightNode';
  34828. }
  34829. /**
  34830. * Constructs a new rect area light node.
  34831. *
  34832. * @param {?RectAreaLight} [light=null] - The rect area light source.
  34833. */
  34834. constructor( light = null ) {
  34835. super( light );
  34836. /**
  34837. * Uniform node representing the half height of the are light.
  34838. *
  34839. * @type {UniformNode<vec3>}
  34840. */
  34841. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  34842. /**
  34843. * Uniform node representing the half width of the are light.
  34844. *
  34845. * @type {UniformNode<vec3>}
  34846. */
  34847. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  34848. /**
  34849. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  34850. * relies on `viewMatrix` which might vary per render call.
  34851. *
  34852. * @type {string}
  34853. * @default 'render'
  34854. */
  34855. this.updateType = NodeUpdateType.RENDER;
  34856. }
  34857. /**
  34858. * Overwritten to updated rect area light specific uniforms.
  34859. *
  34860. * @param {NodeFrame} frame - A reference to the current node frame.
  34861. */
  34862. update( frame ) {
  34863. super.update( frame );
  34864. const { light } = this;
  34865. const viewMatrix = frame.camera.matrixWorldInverse;
  34866. _matrix42.identity();
  34867. _matrix41.copy( light.matrixWorld );
  34868. _matrix41.premultiply( viewMatrix );
  34869. _matrix42.extractRotation( _matrix41 );
  34870. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  34871. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  34872. this.halfWidth.value.applyMatrix4( _matrix42 );
  34873. this.halfHeight.value.applyMatrix4( _matrix42 );
  34874. }
  34875. setupDirectRectArea( builder ) {
  34876. let ltc_1, ltc_2;
  34877. if ( builder.isAvailable( 'float32Filterable' ) ) {
  34878. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  34879. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  34880. } else {
  34881. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  34882. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  34883. }
  34884. const { colorNode, light } = this;
  34885. const lightPosition = lightViewPosition( light );
  34886. return {
  34887. lightColor: colorNode,
  34888. lightPosition,
  34889. halfWidth: this.halfWidth,
  34890. halfHeight: this.halfHeight,
  34891. ltc_1,
  34892. ltc_2
  34893. };
  34894. }
  34895. /**
  34896. * Used to configure the internal BRDF approximation texture data.
  34897. *
  34898. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  34899. */
  34900. static setLTC( ltc ) {
  34901. _ltcLib = ltc;
  34902. }
  34903. }
  34904. /**
  34905. * Module for representing spot lights as nodes.
  34906. *
  34907. * @augments AnalyticLightNode
  34908. */
  34909. class SpotLightNode extends AnalyticLightNode {
  34910. static get type() {
  34911. return 'SpotLightNode';
  34912. }
  34913. /**
  34914. * Constructs a new spot light node.
  34915. *
  34916. * @param {?SpotLight} [light=null] - The spot light source.
  34917. */
  34918. constructor( light = null ) {
  34919. super( light );
  34920. /**
  34921. * Uniform node representing the cone cosine.
  34922. *
  34923. * @type {UniformNode<float>}
  34924. */
  34925. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  34926. /**
  34927. * Uniform node representing the penumbra cosine.
  34928. *
  34929. * @type {UniformNode<float>}
  34930. */
  34931. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  34932. /**
  34933. * Uniform node representing the cutoff distance.
  34934. *
  34935. * @type {UniformNode<float>}
  34936. */
  34937. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  34938. /**
  34939. * Uniform node representing the decay exponent.
  34940. *
  34941. * @type {UniformNode<float>}
  34942. */
  34943. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  34944. /**
  34945. * Uniform node representing the light color.
  34946. *
  34947. * @type {UniformNode<Color>}
  34948. */
  34949. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  34950. }
  34951. /**
  34952. * Overwritten to updated spot light specific uniforms.
  34953. *
  34954. * @param {NodeFrame} frame - A reference to the current node frame.
  34955. */
  34956. update( frame ) {
  34957. super.update( frame );
  34958. const { light } = this;
  34959. this.coneCosNode.value = Math.cos( light.angle );
  34960. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  34961. this.cutoffDistanceNode.value = light.distance;
  34962. this.decayExponentNode.value = light.decay;
  34963. }
  34964. /**
  34965. * Computes the spot attenuation for the given angle.
  34966. *
  34967. * @param {NodeBuilder} builder - The node builder.
  34968. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  34969. * @return {Node<float>} The spot attenuation.
  34970. */
  34971. getSpotAttenuation( builder, angleCosine ) {
  34972. const { coneCosNode, penumbraCosNode } = this;
  34973. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  34974. }
  34975. getLightCoord( builder ) {
  34976. const properties = builder.getNodeProperties( this );
  34977. let projectionUV = properties.projectionUV;
  34978. if ( projectionUV === undefined ) {
  34979. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  34980. properties.projectionUV = projectionUV;
  34981. }
  34982. return projectionUV;
  34983. }
  34984. setupDirect( builder ) {
  34985. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  34986. const lightVector = this.getLightVector( builder );
  34987. const lightDirection = lightVector.normalize();
  34988. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  34989. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  34990. const lightDistance = lightVector.length();
  34991. const lightAttenuation = getDistanceAttenuation( {
  34992. lightDistance,
  34993. cutoffDistance: cutoffDistanceNode,
  34994. decayExponent: decayExponentNode
  34995. } );
  34996. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  34997. let projected, lightCoord;
  34998. if ( light.colorNode ) {
  34999. lightCoord = this.getLightCoord( builder );
  35000. projected = light.colorNode( lightCoord );
  35001. } else if ( light.map ) {
  35002. lightCoord = this.getLightCoord( builder );
  35003. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  35004. }
  35005. if ( projected ) {
  35006. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  35007. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  35008. }
  35009. return { lightColor, lightDirection };
  35010. }
  35011. }
  35012. /**
  35013. * An IES version of the default spot light node.
  35014. *
  35015. * @augments SpotLightNode
  35016. */
  35017. class IESSpotLightNode extends SpotLightNode {
  35018. static get type() {
  35019. return 'IESSpotLightNode';
  35020. }
  35021. /**
  35022. * Overwrites the default implementation to compute an IES conform spot attenuation.
  35023. *
  35024. * @param {NodeBuilder} builder - The node builder.
  35025. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  35026. * @return {Node<float>} The spot attenuation.
  35027. */
  35028. getSpotAttenuation( builder, angleCosine ) {
  35029. const iesMap = this.light.iesMap;
  35030. let spotAttenuation = null;
  35031. if ( iesMap && iesMap.isTexture === true ) {
  35032. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  35033. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  35034. } else {
  35035. spotAttenuation = super.getSpotAttenuation( angleCosine );
  35036. }
  35037. return spotAttenuation;
  35038. }
  35039. }
  35040. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  35041. const d = p.abs().sub( b );
  35042. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  35043. } );
  35044. /**
  35045. * An implementation of a projector light node.
  35046. *
  35047. * @augments SpotLightNode
  35048. */
  35049. class ProjectorLightNode extends SpotLightNode {
  35050. static get type() {
  35051. return 'ProjectorLightNode';
  35052. }
  35053. update( frame ) {
  35054. super.update( frame );
  35055. const light = this.light;
  35056. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  35057. if ( light.aspect === null ) {
  35058. let aspect = 1;
  35059. if ( light.map !== null ) {
  35060. aspect = light.map.width / light.map.height;
  35061. }
  35062. light.shadow.aspect = aspect;
  35063. } else {
  35064. light.shadow.aspect = light.aspect;
  35065. }
  35066. }
  35067. /**
  35068. * Overwrites the default implementation to compute projection attenuation.
  35069. *
  35070. * @param {NodeBuilder} builder - The node builder.
  35071. * @return {Node<float>} The spot attenuation.
  35072. */
  35073. getSpotAttenuation( builder ) {
  35074. const attenuation = float( 0 );
  35075. const penumbraCos = this.penumbraCosNode;
  35076. // compute the fragment's position in the light's clip space
  35077. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  35078. // the sign of w determines whether the current fragment is in front or behind the light.
  35079. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  35080. If( spotLightCoord.w.greaterThan( 0 ), () => {
  35081. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  35082. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  35083. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  35084. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  35085. } );
  35086. return attenuation;
  35087. }
  35088. }
  35089. /**
  35090. * Module for representing ambient lights as nodes.
  35091. *
  35092. * @augments AnalyticLightNode
  35093. */
  35094. class AmbientLightNode extends AnalyticLightNode {
  35095. static get type() {
  35096. return 'AmbientLightNode';
  35097. }
  35098. /**
  35099. * Constructs a new ambient light node.
  35100. *
  35101. * @param {?AmbientLight} [light=null] - The ambient light source.
  35102. */
  35103. constructor( light = null ) {
  35104. super( light );
  35105. }
  35106. setup( { context } ) {
  35107. context.irradiance.addAssign( this.colorNode );
  35108. }
  35109. }
  35110. /**
  35111. * Module for representing hemisphere lights as nodes.
  35112. *
  35113. * @augments AnalyticLightNode
  35114. */
  35115. class HemisphereLightNode extends AnalyticLightNode {
  35116. static get type() {
  35117. return 'HemisphereLightNode';
  35118. }
  35119. /**
  35120. * Constructs a new hemisphere light node.
  35121. *
  35122. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  35123. */
  35124. constructor( light = null ) {
  35125. super( light );
  35126. /**
  35127. * Uniform node representing the light's position.
  35128. *
  35129. * @type {UniformNode<vec3>}
  35130. */
  35131. this.lightPositionNode = lightPosition( light );
  35132. /**
  35133. * A node representing the light's direction.
  35134. *
  35135. * @type {Node<vec3>}
  35136. */
  35137. this.lightDirectionNode = this.lightPositionNode.normalize();
  35138. /**
  35139. * Uniform node representing the light's ground color.
  35140. *
  35141. * @type {UniformNode<vec3>}
  35142. */
  35143. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  35144. }
  35145. /**
  35146. * Overwritten to updated hemisphere light specific uniforms.
  35147. *
  35148. * @param {NodeFrame} frame - A reference to the current node frame.
  35149. */
  35150. update( frame ) {
  35151. const { light } = this;
  35152. super.update( frame );
  35153. this.lightPositionNode.object3d = light;
  35154. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  35155. }
  35156. setup( builder ) {
  35157. const { colorNode, groundColorNode, lightDirectionNode } = this;
  35158. const dotNL = normalWorld.dot( lightDirectionNode );
  35159. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  35160. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  35161. builder.context.irradiance.addAssign( irradiance );
  35162. }
  35163. }
  35164. /**
  35165. * Module for representing light probes as nodes.
  35166. *
  35167. * @augments AnalyticLightNode
  35168. */
  35169. class LightProbeNode extends AnalyticLightNode {
  35170. static get type() {
  35171. return 'LightProbeNode';
  35172. }
  35173. /**
  35174. * Constructs a new light probe node.
  35175. *
  35176. * @param {?LightProbe} [light=null] - The light probe.
  35177. */
  35178. constructor( light = null ) {
  35179. super( light );
  35180. const array = [];
  35181. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  35182. /**
  35183. * Light probe represented as a uniform of spherical harmonics.
  35184. *
  35185. * @type {UniformArrayNode}
  35186. */
  35187. this.lightProbe = uniformArray( array );
  35188. }
  35189. /**
  35190. * Overwritten to updated light probe specific uniforms.
  35191. *
  35192. * @param {NodeFrame} frame - A reference to the current node frame.
  35193. */
  35194. update( frame ) {
  35195. const { light } = this;
  35196. super.update( frame );
  35197. //
  35198. for ( let i = 0; i < 9; i ++ ) {
  35199. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  35200. }
  35201. }
  35202. setup( builder ) {
  35203. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  35204. builder.context.irradiance.addAssign( irradiance );
  35205. }
  35206. }
  35207. /**
  35208. * Base class for node parsers. A derived parser must be implemented
  35209. * for each supported native shader language.
  35210. */
  35211. class NodeParser {
  35212. /**
  35213. * The method parses the given native code an returns a node function.
  35214. *
  35215. * @abstract
  35216. * @param {string} source - The native shader code.
  35217. * @return {NodeFunction} A node function.
  35218. */
  35219. parseFunction( /*source*/ ) {
  35220. console.warn( 'Abstract function.' );
  35221. }
  35222. }
  35223. /**
  35224. * Base class for node functions. A derived module must be implemented
  35225. * for each supported native shader language. Similar to other `Node*` modules,
  35226. * this class is only relevant during the building process and not used
  35227. * in user-level code.
  35228. */
  35229. class NodeFunction {
  35230. /**
  35231. * Constructs a new node function.
  35232. *
  35233. * @param {string} type - The node type. This type is the return type of the node function.
  35234. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  35235. * @param {string} [name=''] - The function's name.
  35236. * @param {string} [precision=''] - The precision qualifier.
  35237. */
  35238. constructor( type, inputs, name = '', precision = '' ) {
  35239. /**
  35240. * The node type. This type is the return type of the node function.
  35241. *
  35242. * @type {string}
  35243. */
  35244. this.type = type;
  35245. /**
  35246. * The function's inputs.
  35247. *
  35248. * @type {Array<NodeFunctionInput>}
  35249. */
  35250. this.inputs = inputs;
  35251. /**
  35252. * The name of the uniform.
  35253. *
  35254. * @type {string}
  35255. * @default ''
  35256. */
  35257. this.name = name;
  35258. /**
  35259. * The precision qualifier.
  35260. *
  35261. * @type {string}
  35262. * @default ''
  35263. */
  35264. this.precision = precision;
  35265. }
  35266. /**
  35267. * This method returns the native code of the node function.
  35268. *
  35269. * @abstract
  35270. * @param {string} name - The function's name.
  35271. * @return {string} A shader code.
  35272. */
  35273. getCode( /*name = this.name*/ ) {
  35274. console.warn( 'Abstract function.' );
  35275. }
  35276. }
  35277. NodeFunction.isNodeFunction = true;
  35278. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  35279. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  35280. const pragmaMain = '#pragma main';
  35281. const parse$1 = ( source ) => {
  35282. source = source.trim();
  35283. const pragmaMainIndex = source.indexOf( pragmaMain );
  35284. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  35285. const declaration = mainCode.match( declarationRegexp$1 );
  35286. if ( declaration !== null && declaration.length === 5 ) {
  35287. // tokenizer
  35288. const inputsCode = declaration[ 4 ];
  35289. const propsMatches = [];
  35290. let nameMatch = null;
  35291. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  35292. propsMatches.push( nameMatch );
  35293. }
  35294. // parser
  35295. const inputs = [];
  35296. let i = 0;
  35297. while ( i < propsMatches.length ) {
  35298. const isConst = propsMatches[ i ][ 0 ] === 'const';
  35299. if ( isConst === true ) {
  35300. i ++;
  35301. }
  35302. let qualifier = propsMatches[ i ][ 0 ];
  35303. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  35304. i ++;
  35305. } else {
  35306. qualifier = '';
  35307. }
  35308. const type = propsMatches[ i ++ ][ 0 ];
  35309. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  35310. if ( Number.isNaN( count ) === false ) i ++;
  35311. else count = null;
  35312. const name = propsMatches[ i ++ ][ 0 ];
  35313. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  35314. }
  35315. //
  35316. const blockCode = mainCode.substring( declaration[ 0 ].length );
  35317. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  35318. const type = declaration[ 2 ];
  35319. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  35320. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  35321. return {
  35322. type,
  35323. inputs,
  35324. name,
  35325. precision,
  35326. inputsCode,
  35327. blockCode,
  35328. headerCode
  35329. };
  35330. } else {
  35331. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  35332. }
  35333. };
  35334. /**
  35335. * This class represents a GLSL node function.
  35336. *
  35337. * @augments NodeFunction
  35338. */
  35339. class GLSLNodeFunction extends NodeFunction {
  35340. /**
  35341. * Constructs a new GLSL node function.
  35342. *
  35343. * @param {string} source - The GLSL source.
  35344. */
  35345. constructor( source ) {
  35346. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  35347. super( type, inputs, name, precision );
  35348. this.inputsCode = inputsCode;
  35349. this.blockCode = blockCode;
  35350. this.headerCode = headerCode;
  35351. }
  35352. /**
  35353. * This method returns the GLSL code of the node function.
  35354. *
  35355. * @param {string} [name=this.name] - The function's name.
  35356. * @return {string} The shader code.
  35357. */
  35358. getCode( name = this.name ) {
  35359. let code;
  35360. const blockCode = this.blockCode;
  35361. if ( blockCode !== '' ) {
  35362. const { type, inputsCode, headerCode, precision } = this;
  35363. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  35364. if ( precision !== '' ) {
  35365. declarationCode = `${ precision } ${ declarationCode }`;
  35366. }
  35367. code = headerCode + declarationCode + blockCode;
  35368. } else {
  35369. // interface function
  35370. code = '';
  35371. }
  35372. return code;
  35373. }
  35374. }
  35375. /**
  35376. * A GLSL node parser.
  35377. *
  35378. * @augments NodeParser
  35379. */
  35380. class GLSLNodeParser extends NodeParser {
  35381. /**
  35382. * The method parses the given GLSL code an returns a node function.
  35383. *
  35384. * @param {string} source - The GLSL code.
  35385. * @return {GLSLNodeFunction} A node function.
  35386. */
  35387. parseFunction( source ) {
  35388. return new GLSLNodeFunction( source );
  35389. }
  35390. }
  35391. const _outputNodeMap = new WeakMap();
  35392. const _chainKeys$2 = [];
  35393. const _cacheKeyValues = [];
  35394. /**
  35395. * This renderer module manages node-related objects and is the
  35396. * primary interface between the renderer and the node system.
  35397. *
  35398. * @private
  35399. * @augments DataMap
  35400. */
  35401. class Nodes extends DataMap {
  35402. /**
  35403. * Constructs a new nodes management component.
  35404. *
  35405. * @param {Renderer} renderer - The renderer.
  35406. * @param {Backend} backend - The renderer's backend.
  35407. */
  35408. constructor( renderer, backend ) {
  35409. super();
  35410. /**
  35411. * The renderer.
  35412. *
  35413. * @type {Renderer}
  35414. */
  35415. this.renderer = renderer;
  35416. /**
  35417. * The renderer's backend.
  35418. *
  35419. * @type {Backend}
  35420. */
  35421. this.backend = backend;
  35422. /**
  35423. * The node frame.
  35424. *
  35425. * @type {Renderer}
  35426. */
  35427. this.nodeFrame = new NodeFrame();
  35428. /**
  35429. * A cache for managing node builder states.
  35430. *
  35431. * @type {Map<number,NodeBuilderState>}
  35432. */
  35433. this.nodeBuilderCache = new Map();
  35434. /**
  35435. * A cache for managing data cache key data.
  35436. *
  35437. * @type {ChainMap}
  35438. */
  35439. this.callHashCache = new ChainMap();
  35440. /**
  35441. * A cache for managing node uniforms group data.
  35442. *
  35443. * @type {ChainMap}
  35444. */
  35445. this.groupsData = new ChainMap();
  35446. /**
  35447. * A cache for managing node objects of
  35448. * scene properties like fog or environments.
  35449. *
  35450. * @type {Object<string,WeakMap>}
  35451. */
  35452. this.cacheLib = {};
  35453. }
  35454. /**
  35455. * Returns `true` if the given node uniforms group must be updated or not.
  35456. *
  35457. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  35458. * @return {boolean} Whether the node uniforms group requires an update or not.
  35459. */
  35460. updateGroup( nodeUniformsGroup ) {
  35461. const groupNode = nodeUniformsGroup.groupNode;
  35462. const name = groupNode.name;
  35463. // objectGroup is always updated
  35464. if ( name === objectGroup.name ) return true;
  35465. // renderGroup is updated once per render/compute call
  35466. if ( name === renderGroup.name ) {
  35467. const uniformsGroupData = this.get( nodeUniformsGroup );
  35468. const renderId = this.nodeFrame.renderId;
  35469. if ( uniformsGroupData.renderId !== renderId ) {
  35470. uniformsGroupData.renderId = renderId;
  35471. return true;
  35472. }
  35473. return false;
  35474. }
  35475. // frameGroup is updated once per frame
  35476. if ( name === frameGroup.name ) {
  35477. const uniformsGroupData = this.get( nodeUniformsGroup );
  35478. const frameId = this.nodeFrame.frameId;
  35479. if ( uniformsGroupData.frameId !== frameId ) {
  35480. uniformsGroupData.frameId = frameId;
  35481. return true;
  35482. }
  35483. return false;
  35484. }
  35485. // other groups are updated just when groupNode.needsUpdate is true
  35486. _chainKeys$2[ 0 ] = groupNode;
  35487. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  35488. let groupData = this.groupsData.get( _chainKeys$2 );
  35489. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  35490. _chainKeys$2.length = 0;
  35491. if ( groupData.version !== groupNode.version ) {
  35492. groupData.version = groupNode.version;
  35493. return true;
  35494. }
  35495. return false;
  35496. }
  35497. /**
  35498. * Returns the cache key for the given render object.
  35499. *
  35500. * @param {RenderObject} renderObject - The render object.
  35501. * @return {number} The cache key.
  35502. */
  35503. getForRenderCacheKey( renderObject ) {
  35504. return renderObject.initialCacheKey;
  35505. }
  35506. /**
  35507. * Returns a node builder state for the given render object.
  35508. *
  35509. * @param {RenderObject} renderObject - The render object.
  35510. * @return {NodeBuilderState} The node builder state.
  35511. */
  35512. getForRender( renderObject ) {
  35513. const renderObjectData = this.get( renderObject );
  35514. let nodeBuilderState = renderObjectData.nodeBuilderState;
  35515. if ( nodeBuilderState === undefined ) {
  35516. const { nodeBuilderCache } = this;
  35517. const cacheKey = this.getForRenderCacheKey( renderObject );
  35518. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  35519. if ( nodeBuilderState === undefined ) {
  35520. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  35521. nodeBuilder.scene = renderObject.scene;
  35522. nodeBuilder.material = renderObject.material;
  35523. nodeBuilder.camera = renderObject.camera;
  35524. nodeBuilder.context.material = renderObject.material;
  35525. nodeBuilder.lightsNode = renderObject.lightsNode;
  35526. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  35527. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  35528. nodeBuilder.clippingContext = renderObject.clippingContext;
  35529. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  35530. nodeBuilder.enableMultiview();
  35531. }
  35532. nodeBuilder.build();
  35533. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  35534. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  35535. }
  35536. nodeBuilderState.usedTimes ++;
  35537. renderObjectData.nodeBuilderState = nodeBuilderState;
  35538. }
  35539. return nodeBuilderState;
  35540. }
  35541. /**
  35542. * Deletes the given object from the internal data map
  35543. *
  35544. * @param {any} object - The object to delete.
  35545. * @return {?Object} The deleted dictionary.
  35546. */
  35547. delete( object ) {
  35548. if ( object.isRenderObject ) {
  35549. const nodeBuilderState = this.get( object ).nodeBuilderState;
  35550. nodeBuilderState.usedTimes --;
  35551. if ( nodeBuilderState.usedTimes === 0 ) {
  35552. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  35553. }
  35554. }
  35555. return super.delete( object );
  35556. }
  35557. /**
  35558. * Returns a node builder state for the given compute node.
  35559. *
  35560. * @param {Node} computeNode - The compute node.
  35561. * @return {NodeBuilderState} The node builder state.
  35562. */
  35563. getForCompute( computeNode ) {
  35564. const computeData = this.get( computeNode );
  35565. let nodeBuilderState = computeData.nodeBuilderState;
  35566. if ( nodeBuilderState === undefined ) {
  35567. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  35568. nodeBuilder.build();
  35569. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  35570. computeData.nodeBuilderState = nodeBuilderState;
  35571. }
  35572. return nodeBuilderState;
  35573. }
  35574. /**
  35575. * Creates a node builder state for the given node builder.
  35576. *
  35577. * @private
  35578. * @param {NodeBuilder} nodeBuilder - The node builder.
  35579. * @return {NodeBuilderState} The node builder state.
  35580. */
  35581. _createNodeBuilderState( nodeBuilder ) {
  35582. return new NodeBuilderState(
  35583. nodeBuilder.vertexShader,
  35584. nodeBuilder.fragmentShader,
  35585. nodeBuilder.computeShader,
  35586. nodeBuilder.getAttributesArray(),
  35587. nodeBuilder.getBindings(),
  35588. nodeBuilder.updateNodes,
  35589. nodeBuilder.updateBeforeNodes,
  35590. nodeBuilder.updateAfterNodes,
  35591. nodeBuilder.observer,
  35592. nodeBuilder.transforms
  35593. );
  35594. }
  35595. /**
  35596. * Returns an environment node for the current configured
  35597. * scene environment.
  35598. *
  35599. * @param {Scene} scene - The scene.
  35600. * @return {Node} A node representing the current scene environment.
  35601. */
  35602. getEnvironmentNode( scene ) {
  35603. this.updateEnvironment( scene );
  35604. let environmentNode = null;
  35605. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  35606. environmentNode = scene.environmentNode;
  35607. } else {
  35608. const sceneData = this.get( scene );
  35609. if ( sceneData.environmentNode ) {
  35610. environmentNode = sceneData.environmentNode;
  35611. }
  35612. }
  35613. return environmentNode;
  35614. }
  35615. /**
  35616. * Returns a background node for the current configured
  35617. * scene background.
  35618. *
  35619. * @param {Scene} scene - The scene.
  35620. * @return {Node} A node representing the current scene background.
  35621. */
  35622. getBackgroundNode( scene ) {
  35623. this.updateBackground( scene );
  35624. let backgroundNode = null;
  35625. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  35626. backgroundNode = scene.backgroundNode;
  35627. } else {
  35628. const sceneData = this.get( scene );
  35629. if ( sceneData.backgroundNode ) {
  35630. backgroundNode = sceneData.backgroundNode;
  35631. }
  35632. }
  35633. return backgroundNode;
  35634. }
  35635. /**
  35636. * Returns a fog node for the current configured scene fog.
  35637. *
  35638. * @param {Scene} scene - The scene.
  35639. * @return {Node} A node representing the current scene fog.
  35640. */
  35641. getFogNode( scene ) {
  35642. this.updateFog( scene );
  35643. return scene.fogNode || this.get( scene ).fogNode || null;
  35644. }
  35645. /**
  35646. * Returns a cache key for the given scene and lights node.
  35647. * This key is used by `RenderObject` as a part of the dynamic
  35648. * cache key (a key that must be checked every time the render
  35649. * objects is drawn).
  35650. *
  35651. * @param {Scene} scene - The scene.
  35652. * @param {LightsNode} lightsNode - The lights node.
  35653. * @return {number} The cache key.
  35654. */
  35655. getCacheKey( scene, lightsNode ) {
  35656. _chainKeys$2[ 0 ] = scene;
  35657. _chainKeys$2[ 1 ] = lightsNode;
  35658. const callId = this.renderer.info.calls;
  35659. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  35660. if ( cacheKeyData.callId !== callId ) {
  35661. const environmentNode = this.getEnvironmentNode( scene );
  35662. const fogNode = this.getFogNode( scene );
  35663. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  35664. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  35665. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  35666. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  35667. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  35668. cacheKeyData.callId = callId;
  35669. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  35670. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  35671. _cacheKeyValues.length = 0;
  35672. }
  35673. _chainKeys$2.length = 0;
  35674. return cacheKeyData.cacheKey;
  35675. }
  35676. /**
  35677. * A boolean that indicates whether tone mapping should be enabled
  35678. * or not.
  35679. *
  35680. * @type {boolean}
  35681. */
  35682. get isToneMappingState() {
  35683. return this.renderer.getRenderTarget() ? false : true;
  35684. }
  35685. /**
  35686. * If a scene background is configured, this method makes sure to
  35687. * represent the background with a corresponding node-based implementation.
  35688. *
  35689. * @param {Scene} scene - The scene.
  35690. */
  35691. updateBackground( scene ) {
  35692. const sceneData = this.get( scene );
  35693. const background = scene.background;
  35694. if ( background ) {
  35695. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  35696. if ( sceneData.background !== background || forceUpdate ) {
  35697. const backgroundNode = this.getCacheNode( 'background', background, () => {
  35698. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  35699. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  35700. return pmremTexture( background );
  35701. } else {
  35702. let envMap;
  35703. if ( background.isCubeTexture === true ) {
  35704. envMap = cubeTexture( background );
  35705. } else {
  35706. envMap = texture( background );
  35707. }
  35708. return cubeMapNode( envMap );
  35709. }
  35710. } else if ( background.isTexture === true ) {
  35711. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  35712. } else if ( background.isColor !== true ) {
  35713. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  35714. }
  35715. }, forceUpdate );
  35716. sceneData.backgroundNode = backgroundNode;
  35717. sceneData.background = background;
  35718. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  35719. }
  35720. } else if ( sceneData.backgroundNode ) {
  35721. delete sceneData.backgroundNode;
  35722. delete sceneData.background;
  35723. }
  35724. }
  35725. /**
  35726. * This method is part of the caching of nodes which are used to represents the
  35727. * scene's background, fog or environment.
  35728. *
  35729. * @param {string} type - The type of object to cache.
  35730. * @param {Object} object - The object.
  35731. * @param {Function} callback - A callback that produces a node representation for the given object.
  35732. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  35733. * @return {Node} The node representation.
  35734. */
  35735. getCacheNode( type, object, callback, forceUpdate = false ) {
  35736. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  35737. let node = nodeCache.get( object );
  35738. if ( node === undefined || forceUpdate ) {
  35739. node = callback();
  35740. nodeCache.set( object, node );
  35741. }
  35742. return node;
  35743. }
  35744. /**
  35745. * If a scene fog is configured, this method makes sure to
  35746. * represent the fog with a corresponding node-based implementation.
  35747. *
  35748. * @param {Scene} scene - The scene.
  35749. */
  35750. updateFog( scene ) {
  35751. const sceneData = this.get( scene );
  35752. const sceneFog = scene.fog;
  35753. if ( sceneFog ) {
  35754. if ( sceneData.fog !== sceneFog ) {
  35755. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  35756. if ( sceneFog.isFogExp2 ) {
  35757. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  35758. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  35759. return fog( color, densityFogFactor( density ) );
  35760. } else if ( sceneFog.isFog ) {
  35761. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  35762. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  35763. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  35764. return fog( color, rangeFogFactor( near, far ) );
  35765. } else {
  35766. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  35767. }
  35768. } );
  35769. sceneData.fogNode = fogNode;
  35770. sceneData.fog = sceneFog;
  35771. }
  35772. } else {
  35773. delete sceneData.fogNode;
  35774. delete sceneData.fog;
  35775. }
  35776. }
  35777. /**
  35778. * If a scene environment is configured, this method makes sure to
  35779. * represent the environment with a corresponding node-based implementation.
  35780. *
  35781. * @param {Scene} scene - The scene.
  35782. */
  35783. updateEnvironment( scene ) {
  35784. const sceneData = this.get( scene );
  35785. const environment = scene.environment;
  35786. if ( environment ) {
  35787. if ( sceneData.environment !== environment ) {
  35788. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  35789. if ( environment.isCubeTexture === true ) {
  35790. return cubeTexture( environment );
  35791. } else if ( environment.isTexture === true ) {
  35792. return texture( environment );
  35793. } else {
  35794. console.error( 'Nodes: Unsupported environment configuration.', environment );
  35795. }
  35796. } );
  35797. sceneData.environmentNode = environmentNode;
  35798. sceneData.environment = environment;
  35799. }
  35800. } else if ( sceneData.environmentNode ) {
  35801. delete sceneData.environmentNode;
  35802. delete sceneData.environment;
  35803. }
  35804. }
  35805. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  35806. const nodeFrame = this.nodeFrame;
  35807. nodeFrame.renderer = renderer;
  35808. nodeFrame.scene = scene;
  35809. nodeFrame.object = object;
  35810. nodeFrame.camera = camera;
  35811. nodeFrame.material = material;
  35812. return nodeFrame;
  35813. }
  35814. getNodeFrameForRender( renderObject ) {
  35815. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  35816. }
  35817. /**
  35818. * Returns the current output cache key.
  35819. *
  35820. * @return {string} The output cache key.
  35821. */
  35822. getOutputCacheKey() {
  35823. const renderer = this.renderer;
  35824. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  35825. }
  35826. /**
  35827. * Checks if the output configuration (tone mapping and color space) for
  35828. * the given target has changed.
  35829. *
  35830. * @param {Texture} outputTarget - The output target.
  35831. * @return {boolean} Whether the output configuration has changed or not.
  35832. */
  35833. hasOutputChange( outputTarget ) {
  35834. const cacheKey = _outputNodeMap.get( outputTarget );
  35835. return cacheKey !== this.getOutputCacheKey();
  35836. }
  35837. /**
  35838. * Returns a node that represents the output configuration (tone mapping and
  35839. * color space) for the current target.
  35840. *
  35841. * @param {Texture} outputTarget - The output target.
  35842. * @return {Node} The output node.
  35843. */
  35844. getOutputNode( outputTarget ) {
  35845. const renderer = this.renderer;
  35846. const cacheKey = this.getOutputCacheKey();
  35847. const output = outputTarget.isArrayTexture ?
  35848. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  35849. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  35850. _outputNodeMap.set( outputTarget, cacheKey );
  35851. return output;
  35852. }
  35853. /**
  35854. * Triggers the call of `updateBefore()` methods
  35855. * for all nodes of the given render object.
  35856. *
  35857. * @param {RenderObject} renderObject - The render object.
  35858. */
  35859. updateBefore( renderObject ) {
  35860. const nodeBuilder = renderObject.getNodeBuilderState();
  35861. for ( const node of nodeBuilder.updateBeforeNodes ) {
  35862. // update frame state for each node
  35863. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  35864. }
  35865. }
  35866. /**
  35867. * Triggers the call of `updateAfter()` methods
  35868. * for all nodes of the given render object.
  35869. *
  35870. * @param {RenderObject} renderObject - The render object.
  35871. */
  35872. updateAfter( renderObject ) {
  35873. const nodeBuilder = renderObject.getNodeBuilderState();
  35874. for ( const node of nodeBuilder.updateAfterNodes ) {
  35875. // update frame state for each node
  35876. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  35877. }
  35878. }
  35879. /**
  35880. * Triggers the call of `update()` methods
  35881. * for all nodes of the given compute node.
  35882. *
  35883. * @param {Node} computeNode - The compute node.
  35884. */
  35885. updateForCompute( computeNode ) {
  35886. const nodeFrame = this.getNodeFrame();
  35887. const nodeBuilder = this.getForCompute( computeNode );
  35888. for ( const node of nodeBuilder.updateNodes ) {
  35889. nodeFrame.updateNode( node );
  35890. }
  35891. }
  35892. /**
  35893. * Triggers the call of `update()` methods
  35894. * for all nodes of the given compute node.
  35895. *
  35896. * @param {RenderObject} renderObject - The render object.
  35897. */
  35898. updateForRender( renderObject ) {
  35899. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35900. const nodeBuilder = renderObject.getNodeBuilderState();
  35901. for ( const node of nodeBuilder.updateNodes ) {
  35902. nodeFrame.updateNode( node );
  35903. }
  35904. }
  35905. /**
  35906. * Returns `true` if the given render object requires a refresh.
  35907. *
  35908. * @param {RenderObject} renderObject - The render object.
  35909. * @return {boolean} Whether the given render object requires a refresh or not.
  35910. */
  35911. needsRefresh( renderObject ) {
  35912. const nodeFrame = this.getNodeFrameForRender( renderObject );
  35913. const monitor = renderObject.getMonitor();
  35914. return monitor.needsRefresh( renderObject, nodeFrame );
  35915. }
  35916. /**
  35917. * Frees the internal resources.
  35918. */
  35919. dispose() {
  35920. super.dispose();
  35921. this.nodeFrame = new NodeFrame();
  35922. this.nodeBuilderCache = new Map();
  35923. this.cacheLib = {};
  35924. }
  35925. }
  35926. const _plane = /*@__PURE__*/ new Plane();
  35927. /**
  35928. * Represents the state that is used to perform clipping via clipping planes.
  35929. * There is a default clipping context for each render context. When the
  35930. * scene holds instances of `ClippingGroup`, there will be a context for each
  35931. * group.
  35932. *
  35933. * @private
  35934. */
  35935. class ClippingContext {
  35936. /**
  35937. * Constructs a new clipping context.
  35938. *
  35939. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  35940. */
  35941. constructor( parentContext = null ) {
  35942. /**
  35943. * The clipping context's version.
  35944. *
  35945. * @type {number}
  35946. * @readonly
  35947. */
  35948. this.version = 0;
  35949. /**
  35950. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  35951. *
  35952. * @type {?boolean}
  35953. * @default null
  35954. */
  35955. this.clipIntersection = null;
  35956. /**
  35957. * The clipping context's cache key.
  35958. *
  35959. * @type {string}
  35960. */
  35961. this.cacheKey = '';
  35962. /**
  35963. * Whether the shadow pass is active or not.
  35964. *
  35965. * @type {boolean}
  35966. * @default false
  35967. */
  35968. this.shadowPass = false;
  35969. /**
  35970. * The view normal matrix.
  35971. *
  35972. * @type {Matrix3}
  35973. */
  35974. this.viewNormalMatrix = new Matrix3();
  35975. /**
  35976. * Internal cache for maintaining clipping contexts.
  35977. *
  35978. * @type {WeakMap<ClippingGroup,ClippingContext>}
  35979. */
  35980. this.clippingGroupContexts = new WeakMap();
  35981. /**
  35982. * The intersection planes.
  35983. *
  35984. * @type {Array<Vector4>}
  35985. */
  35986. this.intersectionPlanes = [];
  35987. /**
  35988. * The intersection planes.
  35989. *
  35990. * @type {Array<Vector4>}
  35991. */
  35992. this.unionPlanes = [];
  35993. /**
  35994. * The version of the clipping context's parent context.
  35995. *
  35996. * @type {?number}
  35997. * @readonly
  35998. */
  35999. this.parentVersion = null;
  36000. if ( parentContext !== null ) {
  36001. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  36002. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  36003. this.shadowPass = parentContext.shadowPass;
  36004. this.viewMatrix = parentContext.viewMatrix;
  36005. }
  36006. }
  36007. /**
  36008. * Projects the given source clipping planes and writes the result into the
  36009. * destination array.
  36010. *
  36011. * @param {Array<Plane>} source - The source clipping planes.
  36012. * @param {Array<Vector4>} destination - The destination.
  36013. * @param {number} offset - The offset.
  36014. */
  36015. projectPlanes( source, destination, offset ) {
  36016. const l = source.length;
  36017. for ( let i = 0; i < l; i ++ ) {
  36018. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  36019. const v = destination[ offset + i ];
  36020. const normal = _plane.normal;
  36021. v.x = - normal.x;
  36022. v.y = - normal.y;
  36023. v.z = - normal.z;
  36024. v.w = _plane.constant;
  36025. }
  36026. }
  36027. /**
  36028. * Updates the root clipping context of a scene.
  36029. *
  36030. * @param {Scene} scene - The scene.
  36031. * @param {Camera} camera - The camera that is used to render the scene.
  36032. */
  36033. updateGlobal( scene, camera ) {
  36034. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  36035. this.viewMatrix = camera.matrixWorldInverse;
  36036. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  36037. }
  36038. /**
  36039. * Updates the clipping context.
  36040. *
  36041. * @param {ClippingContext} parentContext - The parent context.
  36042. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  36043. */
  36044. update( parentContext, clippingGroup ) {
  36045. let update = false;
  36046. if ( parentContext.version !== this.parentVersion ) {
  36047. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  36048. this.unionPlanes = Array.from( parentContext.unionPlanes );
  36049. this.parentVersion = parentContext.version;
  36050. }
  36051. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  36052. this.clipIntersection = clippingGroup.clipIntersection;
  36053. if ( this.clipIntersection ) {
  36054. this.unionPlanes.length = parentContext.unionPlanes.length;
  36055. } else {
  36056. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  36057. }
  36058. }
  36059. const srcClippingPlanes = clippingGroup.clippingPlanes;
  36060. const l = srcClippingPlanes.length;
  36061. let dstClippingPlanes;
  36062. let offset;
  36063. if ( this.clipIntersection ) {
  36064. dstClippingPlanes = this.intersectionPlanes;
  36065. offset = parentContext.intersectionPlanes.length;
  36066. } else {
  36067. dstClippingPlanes = this.unionPlanes;
  36068. offset = parentContext.unionPlanes.length;
  36069. }
  36070. if ( dstClippingPlanes.length !== offset + l ) {
  36071. dstClippingPlanes.length = offset + l;
  36072. for ( let i = 0; i < l; i ++ ) {
  36073. dstClippingPlanes[ offset + i ] = new Vector4();
  36074. }
  36075. update = true;
  36076. }
  36077. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  36078. if ( update ) {
  36079. this.version ++;
  36080. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  36081. }
  36082. }
  36083. /**
  36084. * Returns a clipping context for the given clipping group.
  36085. *
  36086. * @param {ClippingGroup} clippingGroup - The clipping group.
  36087. * @return {ClippingContext} The clipping context.
  36088. */
  36089. getGroupContext( clippingGroup ) {
  36090. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  36091. let context = this.clippingGroupContexts.get( clippingGroup );
  36092. if ( context === undefined ) {
  36093. context = new ClippingContext( this );
  36094. this.clippingGroupContexts.set( clippingGroup, context );
  36095. }
  36096. context.update( this, clippingGroup );
  36097. return context;
  36098. }
  36099. /**
  36100. * The count of union clipping planes.
  36101. *
  36102. * @type {number}
  36103. * @readonly
  36104. */
  36105. get unionClippingCount() {
  36106. return this.unionPlanes.length;
  36107. }
  36108. }
  36109. /**
  36110. * This module is used to represent render bundles inside the renderer
  36111. * for further processing.
  36112. *
  36113. * @private
  36114. */
  36115. class RenderBundle {
  36116. /**
  36117. * Constructs a new bundle group.
  36118. *
  36119. * @param {BundleGroup} bundleGroup - The bundle group.
  36120. * @param {Camera} camera - The camera the bundle group is rendered with.
  36121. */
  36122. constructor( bundleGroup, camera ) {
  36123. this.bundleGroup = bundleGroup;
  36124. this.camera = camera;
  36125. }
  36126. }
  36127. const _chainKeys$1 = [];
  36128. /**
  36129. * This renderer module manages render bundles.
  36130. *
  36131. * @private
  36132. */
  36133. class RenderBundles {
  36134. /**
  36135. * Constructs a new render bundle management component.
  36136. */
  36137. constructor() {
  36138. /**
  36139. * A chain map for maintaining the render bundles.
  36140. *
  36141. * @type {ChainMap}
  36142. */
  36143. this.bundles = new ChainMap();
  36144. }
  36145. /**
  36146. * Returns a render bundle for the given bundle group and camera.
  36147. *
  36148. * @param {BundleGroup} bundleGroup - The bundle group.
  36149. * @param {Camera} camera - The camera the bundle group is rendered with.
  36150. * @return {RenderBundle} The render bundle.
  36151. */
  36152. get( bundleGroup, camera ) {
  36153. const bundles = this.bundles;
  36154. _chainKeys$1[ 0 ] = bundleGroup;
  36155. _chainKeys$1[ 1 ] = camera;
  36156. let bundle = bundles.get( _chainKeys$1 );
  36157. if ( bundle === undefined ) {
  36158. bundle = new RenderBundle( bundleGroup, camera );
  36159. bundles.set( _chainKeys$1, bundle );
  36160. }
  36161. _chainKeys$1.length = 0;
  36162. return bundle;
  36163. }
  36164. /**
  36165. * Frees all internal resources.
  36166. */
  36167. dispose() {
  36168. this.bundles = new ChainMap();
  36169. }
  36170. }
  36171. /**
  36172. * The purpose of a node library is to assign node implementations
  36173. * to existing library features. In `WebGPURenderer` lights, materials
  36174. * which are not based on `NodeMaterial` as well as tone mapping techniques
  36175. * are implemented with node-based modules.
  36176. *
  36177. * @private
  36178. */
  36179. class NodeLibrary {
  36180. /**
  36181. * Constructs a new node library.
  36182. */
  36183. constructor() {
  36184. /**
  36185. * A weak map that maps lights to light nodes.
  36186. *
  36187. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  36188. */
  36189. this.lightNodes = new WeakMap();
  36190. /**
  36191. * A map that maps materials to node materials.
  36192. *
  36193. * @type {Map<string,NodeMaterial.constructor>}
  36194. */
  36195. this.materialNodes = new Map();
  36196. /**
  36197. * A map that maps tone mapping techniques (constants)
  36198. * to tone mapping node functions.
  36199. *
  36200. * @type {Map<number,Function>}
  36201. */
  36202. this.toneMappingNodes = new Map();
  36203. }
  36204. /**
  36205. * Returns a matching node material instance for the given material object.
  36206. *
  36207. * This method also assigns/copies the properties of the given material object
  36208. * to the node material. This is done to make sure the current material
  36209. * configuration carries over to the node version.
  36210. *
  36211. * @param {Material} material - A material.
  36212. * @return {NodeMaterial} The corresponding node material.
  36213. */
  36214. fromMaterial( material ) {
  36215. if ( material.isNodeMaterial ) return material;
  36216. let nodeMaterial = null;
  36217. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  36218. if ( nodeMaterialClass !== null ) {
  36219. nodeMaterial = new nodeMaterialClass();
  36220. for ( const key in material ) {
  36221. nodeMaterial[ key ] = material[ key ];
  36222. }
  36223. }
  36224. return nodeMaterial;
  36225. }
  36226. /**
  36227. * Adds a tone mapping node function for a tone mapping technique (constant).
  36228. *
  36229. * @param {Function} toneMappingNode - The tone mapping node function.
  36230. * @param {number} toneMapping - The tone mapping.
  36231. */
  36232. addToneMapping( toneMappingNode, toneMapping ) {
  36233. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  36234. }
  36235. /**
  36236. * Returns a tone mapping node function for a tone mapping technique (constant).
  36237. *
  36238. * @param {number} toneMapping - The tone mapping.
  36239. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  36240. */
  36241. getToneMappingFunction( toneMapping ) {
  36242. return this.toneMappingNodes.get( toneMapping ) || null;
  36243. }
  36244. /**
  36245. * Returns a node material class definition for a material type.
  36246. *
  36247. * @param {string} materialType - The material type.
  36248. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  36249. */
  36250. getMaterialNodeClass( materialType ) {
  36251. return this.materialNodes.get( materialType ) || null;
  36252. }
  36253. /**
  36254. * Adds a node material class definition for a given material type.
  36255. *
  36256. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  36257. * @param {string} materialClassType - The material type.
  36258. */
  36259. addMaterial( materialNodeClass, materialClassType ) {
  36260. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  36261. }
  36262. /**
  36263. * Returns a light node class definition for a light class definition.
  36264. *
  36265. * @param {Light.constructor} light - The light class definition.
  36266. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  36267. */
  36268. getLightNodeClass( light ) {
  36269. return this.lightNodes.get( light ) || null;
  36270. }
  36271. /**
  36272. * Adds a light node class definition for a given light class definition.
  36273. *
  36274. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  36275. * @param {Light.constructor} lightClass - The light class definition.
  36276. */
  36277. addLight( lightNodeClass, lightClass ) {
  36278. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  36279. }
  36280. /**
  36281. * Adds a node class definition for the given type to the provided type library.
  36282. *
  36283. * @param {any} nodeClass - The node class definition.
  36284. * @param {number|string} type - The object type.
  36285. * @param {Map} library - The type library.
  36286. */
  36287. addType( nodeClass, type, library ) {
  36288. if ( library.has( type ) ) {
  36289. console.warn( `Redefinition of node ${ type }` );
  36290. return;
  36291. }
  36292. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  36293. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  36294. library.set( type, nodeClass );
  36295. }
  36296. /**
  36297. * Adds a node class definition for the given class definition to the provided type library.
  36298. *
  36299. * @param {any} nodeClass - The node class definition.
  36300. * @param {any} baseClass - The class definition.
  36301. * @param {WeakMap} library - The type library.
  36302. */
  36303. addClass( nodeClass, baseClass, library ) {
  36304. if ( library.has( baseClass ) ) {
  36305. console.warn( `Redefinition of node ${ baseClass.name }` );
  36306. return;
  36307. }
  36308. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  36309. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  36310. library.set( baseClass, nodeClass );
  36311. }
  36312. }
  36313. const _defaultLights = /*@__PURE__*/ new LightsNode();
  36314. const _chainKeys = [];
  36315. /**
  36316. * This renderer module manages the lights nodes which are unique
  36317. * per scene and camera combination.
  36318. *
  36319. * The lights node itself is later configured in the render list
  36320. * with the actual lights from the scene.
  36321. *
  36322. * @private
  36323. * @augments ChainMap
  36324. */
  36325. class Lighting extends ChainMap {
  36326. /**
  36327. * Constructs a lighting management component.
  36328. */
  36329. constructor() {
  36330. super();
  36331. }
  36332. /**
  36333. * Creates a new lights node for the given array of lights.
  36334. *
  36335. * @param {Array<Light>} lights - The render object.
  36336. * @return {LightsNode} The lights node.
  36337. */
  36338. createNode( lights = [] ) {
  36339. return new LightsNode().setLights( lights );
  36340. }
  36341. /**
  36342. * Returns a lights node for the given scene and camera.
  36343. *
  36344. * @param {Scene} scene - The scene.
  36345. * @param {Camera} camera - The camera.
  36346. * @return {LightsNode} The lights node.
  36347. */
  36348. getNode( scene, camera ) {
  36349. // ignore post-processing
  36350. if ( scene.isQuadMesh ) return _defaultLights;
  36351. _chainKeys[ 0 ] = scene;
  36352. _chainKeys[ 1 ] = camera;
  36353. let node = this.get( _chainKeys );
  36354. if ( node === undefined ) {
  36355. node = this.createNode();
  36356. this.set( _chainKeys, node );
  36357. }
  36358. _chainKeys.length = 0;
  36359. return node;
  36360. }
  36361. }
  36362. /**
  36363. * A special type of render target that is used when rendering
  36364. * with the WebXR Device API.
  36365. *
  36366. * @private
  36367. * @augments RenderTarget
  36368. */
  36369. class XRRenderTarget extends RenderTarget {
  36370. /**
  36371. * Constructs a new XR render target.
  36372. *
  36373. * @param {number} [width=1] - The width of the render target.
  36374. * @param {number} [height=1] - The height of the render target.
  36375. * @param {Object} [options={}] - The configuration options.
  36376. */
  36377. constructor( width = 1, height = 1, options = {} ) {
  36378. super( width, height, options );
  36379. /**
  36380. * This flag can be used for type testing.
  36381. *
  36382. * @type {boolean}
  36383. * @readonly
  36384. * @default true
  36385. */
  36386. this.isXRRenderTarget = true;
  36387. /**
  36388. * Whether the attachments of the render target
  36389. * are defined by external textures. This flag is
  36390. * set to `true` when using the WebXR Layers API.
  36391. *
  36392. * @private
  36393. * @type {boolean}
  36394. * @default false
  36395. */
  36396. this._hasExternalTextures = false;
  36397. /**
  36398. * Whether a depth buffer should automatically be allocated
  36399. * for this XR render target or not.
  36400. *
  36401. * Allocating a depth buffer is the default behavior of XR render
  36402. * targets. However, when using the WebXR Layers API, this flag
  36403. * must be set to `false` when the `ignoreDepthValues` property of
  36404. * the projection layers evaluates to `false`.
  36405. *
  36406. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  36407. *
  36408. * @private
  36409. * @type {boolean}
  36410. * @default true
  36411. */
  36412. this._autoAllocateDepthBuffer = true;
  36413. /**
  36414. * Whether this render target is associated with a XRWebGLLayer.
  36415. *
  36416. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  36417. * this means that you don't have access to its bound color,
  36418. * stencil and depth buffers. We need to handle this framebuffer
  36419. * differently since its textures are always bound.
  36420. *
  36421. * @private
  36422. * @type {boolean}
  36423. * @default false
  36424. * */
  36425. this._isOpaqueFramebuffer = false;
  36426. }
  36427. copy( source ) {
  36428. super.copy( source );
  36429. this._hasExternalTextures = source._hasExternalTextures;
  36430. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  36431. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  36432. return this;
  36433. }
  36434. }
  36435. const _cameraLPos = /*@__PURE__*/ new Vector3();
  36436. const _cameraRPos = /*@__PURE__*/ new Vector3();
  36437. /**
  36438. * The XR manager is built on top of the WebXR Device API to
  36439. * manage XR sessions with `WebGPURenderer`.
  36440. *
  36441. * XR is currently only supported with a WebGL 2 backend.
  36442. *
  36443. * @augments EventDispatcher
  36444. */
  36445. class XRManager extends EventDispatcher {
  36446. /**
  36447. * Constructs a new XR manager.
  36448. *
  36449. * @param {Renderer} renderer - The renderer.
  36450. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  36451. */
  36452. constructor( renderer, multiview = false ) {
  36453. super();
  36454. /**
  36455. * This flag globally enables XR rendering.
  36456. *
  36457. * @type {boolean}
  36458. * @default false
  36459. */
  36460. this.enabled = false;
  36461. /**
  36462. * Whether the XR device is currently presenting or not.
  36463. *
  36464. * @type {boolean}
  36465. * @default false
  36466. * @readonly
  36467. */
  36468. this.isPresenting = false;
  36469. /**
  36470. * Whether the XR camera should automatically be updated or not.
  36471. *
  36472. * @type {boolean}
  36473. * @default true
  36474. */
  36475. this.cameraAutoUpdate = true;
  36476. /**
  36477. * The renderer.
  36478. *
  36479. * @private
  36480. * @type {Renderer}
  36481. */
  36482. this._renderer = renderer;
  36483. // camera
  36484. /**
  36485. * Represents the camera for the left eye.
  36486. *
  36487. * @private
  36488. * @type {PerspectiveCamera}
  36489. */
  36490. this._cameraL = new PerspectiveCamera();
  36491. this._cameraL.viewport = new Vector4();
  36492. /**
  36493. * Represents the camera for the right eye.
  36494. *
  36495. * @private
  36496. * @type {PerspectiveCamera}
  36497. */
  36498. this._cameraR = new PerspectiveCamera();
  36499. this._cameraR.viewport = new Vector4();
  36500. /**
  36501. * A list of cameras used for rendering the XR views.
  36502. *
  36503. * @private
  36504. * @type {Array<Camera>}
  36505. */
  36506. this._cameras = [ this._cameraL, this._cameraR ];
  36507. /**
  36508. * The main XR camera.
  36509. *
  36510. * @private
  36511. * @type {ArrayCamera}
  36512. */
  36513. this._cameraXR = new ArrayCamera();
  36514. /**
  36515. * The current near value of the XR camera.
  36516. *
  36517. * @private
  36518. * @type {?number}
  36519. * @default null
  36520. */
  36521. this._currentDepthNear = null;
  36522. /**
  36523. * The current far value of the XR camera.
  36524. *
  36525. * @private
  36526. * @type {?number}
  36527. * @default null
  36528. */
  36529. this._currentDepthFar = null;
  36530. /**
  36531. * A list of WebXR controllers requested by the application.
  36532. *
  36533. * @private
  36534. * @type {Array<WebXRController>}
  36535. */
  36536. this._controllers = [];
  36537. /**
  36538. * A list of XR input source. Each input source belongs to
  36539. * an instance of WebXRController.
  36540. *
  36541. * @private
  36542. * @type {Array<XRInputSource?>}
  36543. */
  36544. this._controllerInputSources = [];
  36545. /**
  36546. * The XR render target that represents the rendering destination
  36547. * during an active XR session.
  36548. *
  36549. * @private
  36550. * @type {?RenderTarget}
  36551. * @default null
  36552. */
  36553. this._xrRenderTarget = null;
  36554. /**
  36555. * An array holding all the non-projection layers
  36556. *
  36557. * @private
  36558. * @type {Array<Object>}
  36559. * @default []
  36560. */
  36561. this._layers = [];
  36562. /**
  36563. * Whether the device has support for all layer types.
  36564. *
  36565. * @type {boolean}
  36566. * @default false
  36567. */
  36568. this._supportsLayers = false;
  36569. /**
  36570. * Whether the device supports binding gl objects.
  36571. *
  36572. * @private
  36573. * @type {boolean}
  36574. * @readonly
  36575. */
  36576. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  36577. this._frameBufferTargets = null;
  36578. /**
  36579. * Helper function to create native WebXR Layer.
  36580. *
  36581. * @private
  36582. * @type {Function}
  36583. */
  36584. this._createXRLayer = createXRLayer.bind( this );
  36585. /**
  36586. * The current WebGL context.
  36587. *
  36588. * @private
  36589. * @type {?WebGL2RenderingContext}
  36590. * @default null
  36591. */
  36592. this._gl = null;
  36593. /**
  36594. * The current animation context.
  36595. *
  36596. * @private
  36597. * @type {?Window}
  36598. * @default null
  36599. */
  36600. this._currentAnimationContext = null;
  36601. /**
  36602. * The current animation loop.
  36603. *
  36604. * @private
  36605. * @type {?Function}
  36606. * @default null
  36607. */
  36608. this._currentAnimationLoop = null;
  36609. /**
  36610. * The current pixel ratio.
  36611. *
  36612. * @private
  36613. * @type {?number}
  36614. * @default null
  36615. */
  36616. this._currentPixelRatio = null;
  36617. /**
  36618. * The current size of the renderer's canvas
  36619. * in logical pixel unit.
  36620. *
  36621. * @private
  36622. * @type {Vector2}
  36623. */
  36624. this._currentSize = new Vector2();
  36625. /**
  36626. * The default event listener for handling events inside a XR session.
  36627. *
  36628. * @private
  36629. * @type {Function}
  36630. */
  36631. this._onSessionEvent = onSessionEvent.bind( this );
  36632. /**
  36633. * The event listener for handling the end of a XR session.
  36634. *
  36635. * @private
  36636. * @type {Function}
  36637. */
  36638. this._onSessionEnd = onSessionEnd.bind( this );
  36639. /**
  36640. * The event listener for handling the `inputsourceschange` event.
  36641. *
  36642. * @private
  36643. * @type {Function}
  36644. */
  36645. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  36646. /**
  36647. * The animation loop which is used as a replacement for the default
  36648. * animation loop of the application. It is only used when a XR session
  36649. * is active.
  36650. *
  36651. * @private
  36652. * @type {Function}
  36653. */
  36654. this._onAnimationFrame = onAnimationFrame.bind( this );
  36655. /**
  36656. * The current XR reference space.
  36657. *
  36658. * @private
  36659. * @type {?XRReferenceSpace}
  36660. * @default null
  36661. */
  36662. this._referenceSpace = null;
  36663. /**
  36664. * The current XR reference space type.
  36665. *
  36666. * @private
  36667. * @type {XRReferenceSpaceType}
  36668. * @default 'local-floor'
  36669. */
  36670. this._referenceSpaceType = 'local-floor';
  36671. /**
  36672. * A custom reference space defined by the application.
  36673. *
  36674. * @private
  36675. * @type {?XRReferenceSpace}
  36676. * @default null
  36677. */
  36678. this._customReferenceSpace = null;
  36679. /**
  36680. * The framebuffer scale factor.
  36681. *
  36682. * @private
  36683. * @type {number}
  36684. * @default 1
  36685. */
  36686. this._framebufferScaleFactor = 1;
  36687. /**
  36688. * The foveation factor.
  36689. *
  36690. * @private
  36691. * @type {number}
  36692. * @default 1
  36693. */
  36694. this._foveation = 1.0;
  36695. /**
  36696. * A reference to the current XR session.
  36697. *
  36698. * @private
  36699. * @type {?XRSession}
  36700. * @default null
  36701. */
  36702. this._session = null;
  36703. /**
  36704. * A reference to the current XR base layer.
  36705. *
  36706. * @private
  36707. * @type {?XRWebGLLayer}
  36708. * @default null
  36709. */
  36710. this._glBaseLayer = null;
  36711. /**
  36712. * A reference to the current XR binding.
  36713. *
  36714. * @private
  36715. * @type {?XRWebGLBinding}
  36716. * @default null
  36717. */
  36718. this._glBinding = null;
  36719. /**
  36720. * A reference to the current XR projection layer.
  36721. *
  36722. * @private
  36723. * @type {?XRProjectionLayer}
  36724. * @default null
  36725. */
  36726. this._glProjLayer = null;
  36727. /**
  36728. * A reference to the current XR frame.
  36729. *
  36730. * @private
  36731. * @type {?XRFrame}
  36732. * @default null
  36733. */
  36734. this._xrFrame = null;
  36735. /**
  36736. * Whether to use the WebXR Layers API or not.
  36737. *
  36738. * @private
  36739. * @type {boolean}
  36740. * @readonly
  36741. */
  36742. this._useLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  36743. /**
  36744. * Whether the usage of multiview has been requested by the application or not.
  36745. *
  36746. * @private
  36747. * @type {boolean}
  36748. * @default false
  36749. * @readonly
  36750. */
  36751. this._useMultiviewIfPossible = multiview;
  36752. /**
  36753. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  36754. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  36755. *
  36756. * @private
  36757. * @type {boolean}
  36758. * @readonly
  36759. */
  36760. this._useMultiview = false;
  36761. }
  36762. /**
  36763. * Returns an instance of `THREE.Group` that represents the transformation
  36764. * of a XR controller in target ray space. The requested controller is defined
  36765. * by the given index.
  36766. *
  36767. * @param {number} index - The index of the XR controller.
  36768. * @return {Group} A group that represents the controller's transformation.
  36769. */
  36770. getController( index ) {
  36771. const controller = this._getController( index );
  36772. return controller.getTargetRaySpace();
  36773. }
  36774. /**
  36775. * Returns an instance of `THREE.Group` that represents the transformation
  36776. * of a XR controller in grip space. The requested controller is defined
  36777. * by the given index.
  36778. *
  36779. * @param {number} index - The index of the XR controller.
  36780. * @return {Group} A group that represents the controller's transformation.
  36781. */
  36782. getControllerGrip( index ) {
  36783. const controller = this._getController( index );
  36784. return controller.getGripSpace();
  36785. }
  36786. /**
  36787. * Returns an instance of `THREE.Group` that represents the transformation
  36788. * of a XR controller in hand space. The requested controller is defined
  36789. * by the given index.
  36790. *
  36791. * @param {number} index - The index of the XR controller.
  36792. * @return {Group} A group that represents the controller's transformation.
  36793. */
  36794. getHand( index ) {
  36795. const controller = this._getController( index );
  36796. return controller.getHandSpace();
  36797. }
  36798. /**
  36799. * Returns the foveation value.
  36800. *
  36801. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  36802. */
  36803. getFoveation() {
  36804. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  36805. return undefined;
  36806. }
  36807. return this._foveation;
  36808. }
  36809. /**
  36810. * Sets the foveation value.
  36811. *
  36812. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  36813. * and `1` means maximum foveation (the edges render at lower resolution).
  36814. */
  36815. setFoveation( foveation ) {
  36816. this._foveation = foveation;
  36817. if ( this._glProjLayer !== null ) {
  36818. this._glProjLayer.fixedFoveation = foveation;
  36819. }
  36820. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  36821. this._glBaseLayer.fixedFoveation = foveation;
  36822. }
  36823. }
  36824. /**
  36825. * Returns the framebuffer scale factor.
  36826. *
  36827. * @return {number} The framebuffer scale factor.
  36828. */
  36829. getFramebufferScaleFactor() {
  36830. return this._framebufferScaleFactor;
  36831. }
  36832. /**
  36833. * Sets the framebuffer scale factor.
  36834. *
  36835. * This method can not be used during a XR session.
  36836. *
  36837. * @param {number} factor - The framebuffer scale factor.
  36838. */
  36839. setFramebufferScaleFactor( factor ) {
  36840. this._framebufferScaleFactor = factor;
  36841. if ( this.isPresenting === true ) {
  36842. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  36843. }
  36844. }
  36845. /**
  36846. * Returns the reference space type.
  36847. *
  36848. * @return {XRReferenceSpaceType} The reference space type.
  36849. */
  36850. getReferenceSpaceType() {
  36851. return this._referenceSpaceType;
  36852. }
  36853. /**
  36854. * Sets the reference space type.
  36855. *
  36856. * This method can not be used during a XR session.
  36857. *
  36858. * @param {XRReferenceSpaceType} type - The reference space type.
  36859. */
  36860. setReferenceSpaceType( type ) {
  36861. this._referenceSpaceType = type;
  36862. if ( this.isPresenting === true ) {
  36863. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  36864. }
  36865. }
  36866. /**
  36867. * Returns the XR reference space.
  36868. *
  36869. * @return {XRReferenceSpace} The XR reference space.
  36870. */
  36871. getReferenceSpace() {
  36872. return this._customReferenceSpace || this._referenceSpace;
  36873. }
  36874. /**
  36875. * Sets a custom XR reference space.
  36876. *
  36877. * @param {XRReferenceSpace} space - The XR reference space.
  36878. */
  36879. setReferenceSpace( space ) {
  36880. this._customReferenceSpace = space;
  36881. }
  36882. /**
  36883. * Returns the XR camera.
  36884. *
  36885. * @return {ArrayCamera} The XR camera.
  36886. */
  36887. getCamera() {
  36888. return this._cameraXR;
  36889. }
  36890. /**
  36891. * Returns the environment blend mode from the current XR session.
  36892. *
  36893. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  36894. */
  36895. getEnvironmentBlendMode() {
  36896. if ( this._session !== null ) {
  36897. return this._session.environmentBlendMode;
  36898. }
  36899. }
  36900. /**
  36901. * Returns the current XR frame.
  36902. *
  36903. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  36904. */
  36905. getFrame() {
  36906. return this._xrFrame;
  36907. }
  36908. /**
  36909. * Returns `true` if the engine renders to a multiview target.
  36910. *
  36911. * @return {boolean} Whether the engine renders to a multiview render target or not.
  36912. */
  36913. useMultiview() {
  36914. return this._useMultiview;
  36915. }
  36916. /**
  36917. * This method can be used in XR applications to create a quadratic layer that presents a separate
  36918. * rendered scene.
  36919. *
  36920. * @param {number} width - The width of the layer plane in world units.
  36921. * @param {number} height - The height of the layer plane in world units.
  36922. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  36923. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  36924. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  36925. * @param {number} pixelheight - The height of the layer's render target in pixels.
  36926. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  36927. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  36928. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  36929. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  36930. */
  36931. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  36932. const geometry = new PlaneGeometry( width, height );
  36933. const renderTarget = new XRRenderTarget(
  36934. pixelwidth,
  36935. pixelheight,
  36936. {
  36937. format: RGBAFormat,
  36938. type: UnsignedByteType,
  36939. depthTexture: new DepthTexture(
  36940. pixelwidth,
  36941. pixelheight,
  36942. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  36943. undefined,
  36944. undefined,
  36945. undefined,
  36946. undefined,
  36947. undefined,
  36948. undefined,
  36949. attributes.stencil ? DepthStencilFormat : DepthFormat
  36950. ),
  36951. stencilBuffer: attributes.stencil,
  36952. resolveDepthBuffer: false,
  36953. resolveStencilBuffer: false
  36954. } );
  36955. renderTarget._autoAllocateDepthBuffer = true;
  36956. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  36957. material.map = renderTarget.texture;
  36958. material.map.offset.y = 1;
  36959. material.map.repeat.y = -1;
  36960. const plane = new Mesh( geometry, material );
  36961. plane.position.copy( translation );
  36962. plane.quaternion.copy( quaternion );
  36963. const layer = {
  36964. type: 'quad',
  36965. width: width,
  36966. height: height,
  36967. translation: translation,
  36968. quaternion: quaternion,
  36969. pixelwidth: pixelwidth,
  36970. pixelheight: pixelheight,
  36971. plane: plane,
  36972. material: material,
  36973. rendercall: rendercall,
  36974. renderTarget: renderTarget };
  36975. this._layers.push( layer );
  36976. if ( this._session !== null ) {
  36977. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  36978. layer.plane.material.blending = CustomBlending;
  36979. layer.plane.material.blendEquation = AddEquation;
  36980. layer.plane.material.blendSrc = ZeroFactor;
  36981. layer.plane.material.blendDst = ZeroFactor;
  36982. layer.xrlayer = this._createXRLayer( layer );
  36983. const xrlayers = this._session.renderState.layers;
  36984. xrlayers.unshift( layer.xrlayer );
  36985. this._session.updateRenderState( { layers: xrlayers } );
  36986. } else {
  36987. renderTarget.isXRRenderTarget = false;
  36988. }
  36989. return plane;
  36990. }
  36991. /**
  36992. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  36993. * rendered scene.
  36994. *
  36995. * @param {number} radius - The radius of the cylinder in world units.
  36996. * @param {number} centralAngle - The central angle of the cylinder in radians.
  36997. * @param {number} aspectratio - The aspect ratio.
  36998. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  36999. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  37000. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  37001. * @param {number} pixelheight - The height of the layer's render target in pixels.
  37002. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  37003. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  37004. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  37005. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  37006. */
  37007. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  37008. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  37009. const renderTarget = new XRRenderTarget(
  37010. pixelwidth,
  37011. pixelheight,
  37012. {
  37013. format: RGBAFormat,
  37014. type: UnsignedByteType,
  37015. depthTexture: new DepthTexture(
  37016. pixelwidth,
  37017. pixelheight,
  37018. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  37019. undefined,
  37020. undefined,
  37021. undefined,
  37022. undefined,
  37023. undefined,
  37024. undefined,
  37025. attributes.stencil ? DepthStencilFormat : DepthFormat
  37026. ),
  37027. stencilBuffer: attributes.stencil,
  37028. resolveDepthBuffer: false,
  37029. resolveStencilBuffer: false
  37030. } );
  37031. renderTarget._autoAllocateDepthBuffer = true;
  37032. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  37033. material.map = renderTarget.texture;
  37034. material.map.offset.y = 1;
  37035. material.map.repeat.y = -1;
  37036. const plane = new Mesh( geometry, material );
  37037. plane.position.copy( translation );
  37038. plane.quaternion.copy( quaternion );
  37039. const layer = {
  37040. type: 'cylinder',
  37041. radius: radius,
  37042. centralAngle: centralAngle,
  37043. aspectratio: aspectratio,
  37044. translation: translation,
  37045. quaternion: quaternion,
  37046. pixelwidth: pixelwidth,
  37047. pixelheight: pixelheight,
  37048. plane: plane,
  37049. material: material,
  37050. rendercall: rendercall,
  37051. renderTarget: renderTarget };
  37052. this._layers.push( layer );
  37053. if ( this._session !== null ) {
  37054. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  37055. layer.plane.material.blending = CustomBlending;
  37056. layer.plane.material.blendEquation = AddEquation;
  37057. layer.plane.material.blendSrc = ZeroFactor;
  37058. layer.plane.material.blendDst = ZeroFactor;
  37059. layer.xrlayer = this._createXRLayer( layer );
  37060. const xrlayers = this._session.renderState.layers;
  37061. xrlayers.unshift( layer.xrlayer );
  37062. this._session.updateRenderState( { layers: xrlayers } );
  37063. } else {
  37064. renderTarget.isXRRenderTarget = false;
  37065. }
  37066. return plane;
  37067. }
  37068. /**
  37069. * Renders the XR layers that have been previously added to the scene.
  37070. *
  37071. * This method is usually called in your animation loop before rendering
  37072. * the actual scene via `renderer.render( scene, camera );`.
  37073. */
  37074. renderLayers( ) {
  37075. const translationObject = new Vector3();
  37076. const quaternionObject = new Quaternion();
  37077. const renderer = this._renderer;
  37078. const wasPresenting = this.isPresenting;
  37079. const rendererOutputTarget = renderer.getOutputRenderTarget();
  37080. const rendererFramebufferTarget = renderer._frameBufferTarget;
  37081. this.isPresenting = false;
  37082. const rendererSize = new Vector2();
  37083. renderer.getSize( rendererSize );
  37084. const rendererQuad = renderer._quad;
  37085. for ( const layer of this._layers ) {
  37086. layer.renderTarget.isXRRenderTarget = this._session !== null;
  37087. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  37088. if ( layer.renderTarget.isXRRenderTarget && this._supportsLayers ) {
  37089. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  37090. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  37091. renderer.backend.setXRRenderTargetTextures(
  37092. layer.renderTarget,
  37093. glSubImage.colorTexture,
  37094. undefined );
  37095. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  37096. renderer.setOutputRenderTarget( layer.renderTarget );
  37097. renderer.setRenderTarget( null );
  37098. renderer._frameBufferTarget = null;
  37099. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  37100. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  37101. if ( ! frameBufferTarget ) {
  37102. renderer._quad = new QuadMesh( new NodeMaterial() );
  37103. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  37104. } else {
  37105. renderer._frameBufferTarget = frameBufferTarget;
  37106. renderer._quad = quad;
  37107. }
  37108. layer.rendercall();
  37109. renderer._frameBufferTarget = null;
  37110. } else {
  37111. renderer.setRenderTarget( layer.renderTarget );
  37112. layer.rendercall();
  37113. }
  37114. }
  37115. renderer.setRenderTarget( null );
  37116. renderer.setOutputRenderTarget( rendererOutputTarget );
  37117. renderer._frameBufferTarget = rendererFramebufferTarget;
  37118. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  37119. renderer._quad = rendererQuad;
  37120. this.isPresenting = wasPresenting;
  37121. }
  37122. /**
  37123. * Returns the current XR session.
  37124. *
  37125. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  37126. */
  37127. getSession() {
  37128. return this._session;
  37129. }
  37130. /**
  37131. * After a XR session has been requested usually with one of the `*Button` modules, it
  37132. * is injected into the renderer with this method. This method triggers the start of
  37133. * the actual XR rendering.
  37134. *
  37135. * @async
  37136. * @param {XRSession} session - The XR session to set.
  37137. * @return {Promise} A Promise that resolves when the session has been set.
  37138. */
  37139. async setSession( session ) {
  37140. const renderer = this._renderer;
  37141. const backend = renderer.backend;
  37142. this._gl = renderer.getContext();
  37143. const gl = this._gl;
  37144. const attributes = gl.getContextAttributes();
  37145. this._session = session;
  37146. if ( session !== null ) {
  37147. 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.' );
  37148. session.addEventListener( 'select', this._onSessionEvent );
  37149. session.addEventListener( 'selectstart', this._onSessionEvent );
  37150. session.addEventListener( 'selectend', this._onSessionEvent );
  37151. session.addEventListener( 'squeeze', this._onSessionEvent );
  37152. session.addEventListener( 'squeezestart', this._onSessionEvent );
  37153. session.addEventListener( 'squeezeend', this._onSessionEvent );
  37154. session.addEventListener( 'end', this._onSessionEnd );
  37155. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  37156. await backend.makeXRCompatible();
  37157. this._currentPixelRatio = renderer.getPixelRatio();
  37158. renderer.getSize( this._currentSize );
  37159. this._currentAnimationContext = renderer._animation.getContext();
  37160. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  37161. renderer._animation.stop();
  37162. //
  37163. if ( this._supportsGlBinding ) {
  37164. const glBinding = new XRWebGLBinding( session, gl );
  37165. this._glBinding = glBinding;
  37166. }
  37167. //
  37168. if ( this._useLayers === true ) {
  37169. // default path using XRProjectionLayer
  37170. let depthFormat = null;
  37171. let depthType = null;
  37172. let glDepthFormat = null;
  37173. if ( renderer.depth ) {
  37174. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  37175. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  37176. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  37177. }
  37178. const projectionlayerInit = {
  37179. colorFormat: gl.RGBA8,
  37180. depthFormat: glDepthFormat,
  37181. scaleFactor: this._framebufferScaleFactor,
  37182. clearOnAccess: false
  37183. };
  37184. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  37185. projectionlayerInit.textureType = 'texture-array';
  37186. this._useMultiview = true;
  37187. }
  37188. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  37189. const layersArray = [ glProjLayer ];
  37190. this._glProjLayer = glProjLayer;
  37191. renderer.setPixelRatio( 1 );
  37192. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  37193. const depth = this._useMultiview ? 2 : 1;
  37194. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  37195. this._xrRenderTarget = new XRRenderTarget(
  37196. glProjLayer.textureWidth,
  37197. glProjLayer.textureHeight,
  37198. {
  37199. format: RGBAFormat,
  37200. type: UnsignedByteType,
  37201. colorSpace: renderer.outputColorSpace,
  37202. depthTexture: depthTexture,
  37203. stencilBuffer: renderer.stencil,
  37204. samples: attributes.antialias ? 4 : 0,
  37205. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  37206. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  37207. depth: this._useMultiview ? 2 : 1,
  37208. multiview: this._useMultiview
  37209. } );
  37210. this._xrRenderTarget._hasExternalTextures = true;
  37211. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  37212. this._supportsLayers = session.enabledFeatures.includes( 'layers' );
  37213. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  37214. if ( this._supportsLayers ) {
  37215. // switch layers to native
  37216. for ( const layer of this._layers ) {
  37217. // change material so it "punches" out a hole to show the XR Layer.
  37218. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  37219. layer.plane.material.blending = CustomBlending;
  37220. layer.plane.material.blendEquation = AddEquation;
  37221. layer.plane.material.blendSrc = ZeroFactor;
  37222. layer.plane.material.blendDst = ZeroFactor;
  37223. layer.xrlayer = this._createXRLayer( layer );
  37224. layersArray.unshift( layer.xrlayer );
  37225. }
  37226. }
  37227. session.updateRenderState( { layers: layersArray } );
  37228. } else {
  37229. // fallback to XRWebGLLayer
  37230. const layerInit = {
  37231. antialias: renderer.samples > 0,
  37232. alpha: true,
  37233. depth: renderer.depth,
  37234. stencil: renderer.stencil,
  37235. framebufferScaleFactor: this.getFramebufferScaleFactor()
  37236. };
  37237. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  37238. this._glBaseLayer = glBaseLayer;
  37239. session.updateRenderState( { baseLayer: glBaseLayer } );
  37240. renderer.setPixelRatio( 1 );
  37241. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  37242. this._xrRenderTarget = new XRRenderTarget(
  37243. glBaseLayer.framebufferWidth,
  37244. glBaseLayer.framebufferHeight,
  37245. {
  37246. format: RGBAFormat,
  37247. type: UnsignedByteType,
  37248. colorSpace: renderer.outputColorSpace,
  37249. stencilBuffer: renderer.stencil,
  37250. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  37251. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  37252. }
  37253. );
  37254. this._xrRenderTarget._isOpaqueFramebuffer = true;
  37255. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  37256. }
  37257. //
  37258. this.setFoveation( this.getFoveation() );
  37259. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  37260. renderer._animation.setContext( session );
  37261. renderer._animation.start();
  37262. this.isPresenting = true;
  37263. this.dispatchEvent( { type: 'sessionstart' } );
  37264. }
  37265. }
  37266. /**
  37267. * This method is called by the renderer per frame and updates the XR camera
  37268. * and it sub cameras based on the given camera. The given camera is the "user"
  37269. * camera created on application level and used for non-XR rendering.
  37270. *
  37271. * @param {PerspectiveCamera} camera - The camera.
  37272. */
  37273. updateCamera( camera ) {
  37274. const session = this._session;
  37275. if ( session === null ) return;
  37276. const depthNear = camera.near;
  37277. const depthFar = camera.far;
  37278. const cameraXR = this._cameraXR;
  37279. const cameraL = this._cameraL;
  37280. const cameraR = this._cameraR;
  37281. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  37282. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  37283. cameraXR.isMultiViewCamera = this._useMultiview;
  37284. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  37285. // Note that the new renderState won't apply until the next frame. See #18320
  37286. session.updateRenderState( {
  37287. depthNear: cameraXR.near,
  37288. depthFar: cameraXR.far
  37289. } );
  37290. this._currentDepthNear = cameraXR.near;
  37291. this._currentDepthFar = cameraXR.far;
  37292. }
  37293. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  37294. cameraXR.layers.mask = camera.layers.mask | 0b110;
  37295. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  37296. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  37297. const parent = camera.parent;
  37298. const cameras = cameraXR.cameras;
  37299. updateCamera( cameraXR, parent );
  37300. for ( let i = 0; i < cameras.length; i ++ ) {
  37301. updateCamera( cameras[ i ], parent );
  37302. }
  37303. // update projection matrix for proper view frustum culling
  37304. if ( cameras.length === 2 ) {
  37305. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  37306. } else {
  37307. // assume single camera setup (AR)
  37308. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  37309. }
  37310. // update user camera and its children
  37311. updateUserCamera( camera, cameraXR, parent );
  37312. }
  37313. /**
  37314. * Returns a WebXR controller for the given controller index.
  37315. *
  37316. * @private
  37317. * @param {number} index - The controller index.
  37318. * @return {WebXRController} The XR controller.
  37319. */
  37320. _getController( index ) {
  37321. let controller = this._controllers[ index ];
  37322. if ( controller === undefined ) {
  37323. controller = new WebXRController();
  37324. this._controllers[ index ] = controller;
  37325. }
  37326. return controller;
  37327. }
  37328. }
  37329. /**
  37330. * Assumes 2 cameras that are parallel and share an X-axis, and that
  37331. * the cameras' projection and world matrices have already been set.
  37332. * And that near and far planes are identical for both cameras.
  37333. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  37334. *
  37335. * @param {ArrayCamera} camera - The camera to update.
  37336. * @param {PerspectiveCamera} cameraL - The left camera.
  37337. * @param {PerspectiveCamera} cameraR - The right camera.
  37338. */
  37339. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  37340. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  37341. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  37342. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  37343. const projL = cameraL.projectionMatrix.elements;
  37344. const projR = cameraR.projectionMatrix.elements;
  37345. // VR systems will have identical far and near planes, and
  37346. // most likely identical top and bottom frustum extents.
  37347. // Use the left camera for these values.
  37348. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  37349. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  37350. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  37351. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  37352. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  37353. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  37354. const left = near * leftFov;
  37355. const right = near * rightFov;
  37356. // Calculate the new camera's position offset from the
  37357. // left camera. xOffset should be roughly half `ipd`.
  37358. const zOffset = ipd / ( - leftFov + rightFov );
  37359. const xOffset = zOffset * - leftFov;
  37360. // TODO: Better way to apply this offset?
  37361. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  37362. camera.translateX( xOffset );
  37363. camera.translateZ( zOffset );
  37364. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  37365. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  37366. // Check if the projection uses an infinite far plane.
  37367. if ( projL[ 10 ] === -1 ) {
  37368. // Use the projection matrix from the left eye.
  37369. // The camera offset is sufficient to include the view volumes
  37370. // of both eyes (assuming symmetric projections).
  37371. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  37372. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  37373. } else {
  37374. // Find the union of the frustum values of the cameras and scale
  37375. // the values so that the near plane's position does not change in world space,
  37376. // although must now be relative to the new union camera.
  37377. const near2 = near + zOffset;
  37378. const far2 = far + zOffset;
  37379. const left2 = left - xOffset;
  37380. const right2 = right + ( ipd - xOffset );
  37381. const top2 = topFov * far / far2 * near2;
  37382. const bottom2 = bottomFov * far / far2 * near2;
  37383. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  37384. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  37385. }
  37386. }
  37387. /**
  37388. * Updates the world matrices for the given camera based on the parent 3D object.
  37389. *
  37390. * @inner
  37391. * @param {Camera} camera - The camera to update.
  37392. * @param {Object3D} parent - The parent 3D object.
  37393. */
  37394. function updateCamera( camera, parent ) {
  37395. if ( parent === null ) {
  37396. camera.matrixWorld.copy( camera.matrix );
  37397. } else {
  37398. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  37399. }
  37400. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  37401. }
  37402. /**
  37403. * Updates the given camera with the transformation of the XR camera and parent object.
  37404. *
  37405. * @inner
  37406. * @param {Camera} camera - The camera to update.
  37407. * @param {ArrayCamera} cameraXR - The XR camera.
  37408. * @param {Object3D} parent - The parent 3D object.
  37409. */
  37410. function updateUserCamera( camera, cameraXR, parent ) {
  37411. if ( parent === null ) {
  37412. camera.matrix.copy( cameraXR.matrixWorld );
  37413. } else {
  37414. camera.matrix.copy( parent.matrixWorld );
  37415. camera.matrix.invert();
  37416. camera.matrix.multiply( cameraXR.matrixWorld );
  37417. }
  37418. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  37419. camera.updateMatrixWorld( true );
  37420. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  37421. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  37422. if ( camera.isPerspectiveCamera ) {
  37423. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  37424. camera.zoom = 1;
  37425. }
  37426. }
  37427. function onSessionEvent( event ) {
  37428. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  37429. if ( controllerIndex === -1 ) {
  37430. return;
  37431. }
  37432. const controller = this._controllers[ controllerIndex ];
  37433. if ( controller !== undefined ) {
  37434. const referenceSpace = this.getReferenceSpace();
  37435. controller.update( event.inputSource, event.frame, referenceSpace );
  37436. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  37437. }
  37438. }
  37439. function onSessionEnd() {
  37440. const session = this._session;
  37441. const renderer = this._renderer;
  37442. session.removeEventListener( 'select', this._onSessionEvent );
  37443. session.removeEventListener( 'selectstart', this._onSessionEvent );
  37444. session.removeEventListener( 'selectend', this._onSessionEvent );
  37445. session.removeEventListener( 'squeeze', this._onSessionEvent );
  37446. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  37447. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  37448. session.removeEventListener( 'end', this._onSessionEnd );
  37449. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  37450. for ( let i = 0; i < this._controllers.length; i ++ ) {
  37451. const inputSource = this._controllerInputSources[ i ];
  37452. if ( inputSource === null ) continue;
  37453. this._controllerInputSources[ i ] = null;
  37454. this._controllers[ i ].disconnect( inputSource );
  37455. }
  37456. this._currentDepthNear = null;
  37457. this._currentDepthFar = null;
  37458. // restore framebuffer/rendering state
  37459. renderer._resetXRState();
  37460. this._session = null;
  37461. this._xrRenderTarget = null;
  37462. // switch layers back to emulated
  37463. if ( this._supportsLayers === true ) {
  37464. for ( const layer of this._layers ) {
  37465. // Recreate layer render target to reset state
  37466. layer.renderTarget = new XRRenderTarget(
  37467. layer.pixelwidth,
  37468. layer.pixelheight,
  37469. {
  37470. format: RGBAFormat,
  37471. type: UnsignedByteType,
  37472. depthTexture: new DepthTexture(
  37473. layer.pixelwidth,
  37474. layer.pixelheight,
  37475. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  37476. undefined,
  37477. undefined,
  37478. undefined,
  37479. undefined,
  37480. undefined,
  37481. undefined,
  37482. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  37483. ),
  37484. stencilBuffer: layer.stencilBuffer,
  37485. resolveDepthBuffer: false,
  37486. resolveStencilBuffer: false
  37487. } );
  37488. layer.renderTarget.isXRRenderTarget = false;
  37489. layer.plane.material = layer.material;
  37490. layer.material.map = layer.renderTarget.texture;
  37491. layer.material.map.offset.y = 1;
  37492. layer.material.map.repeat.y = -1;
  37493. delete layer.xrlayer;
  37494. }
  37495. }
  37496. //
  37497. this.isPresenting = false;
  37498. this._useMultiview = false;
  37499. renderer._animation.stop();
  37500. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  37501. renderer._animation.setContext( this._currentAnimationContext );
  37502. renderer._animation.start();
  37503. renderer.setPixelRatio( this._currentPixelRatio );
  37504. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  37505. this.dispatchEvent( { type: 'sessionend' } );
  37506. }
  37507. function onInputSourcesChange( event ) {
  37508. const controllers = this._controllers;
  37509. const controllerInputSources = this._controllerInputSources;
  37510. // Notify disconnected
  37511. for ( let i = 0; i < event.removed.length; i ++ ) {
  37512. const inputSource = event.removed[ i ];
  37513. const index = controllerInputSources.indexOf( inputSource );
  37514. if ( index >= 0 ) {
  37515. controllerInputSources[ index ] = null;
  37516. controllers[ index ].disconnect( inputSource );
  37517. }
  37518. }
  37519. // Notify connected
  37520. for ( let i = 0; i < event.added.length; i ++ ) {
  37521. const inputSource = event.added[ i ];
  37522. let controllerIndex = controllerInputSources.indexOf( inputSource );
  37523. if ( controllerIndex === -1 ) {
  37524. // Assign input source a controller that currently has no input source
  37525. for ( let i = 0; i < controllers.length; i ++ ) {
  37526. if ( i >= controllerInputSources.length ) {
  37527. controllerInputSources.push( inputSource );
  37528. controllerIndex = i;
  37529. break;
  37530. } else if ( controllerInputSources[ i ] === null ) {
  37531. controllerInputSources[ i ] = inputSource;
  37532. controllerIndex = i;
  37533. break;
  37534. }
  37535. }
  37536. // If all controllers do currently receive input we ignore new ones
  37537. if ( controllerIndex === -1 ) break;
  37538. }
  37539. const controller = controllers[ controllerIndex ];
  37540. if ( controller ) {
  37541. controller.connect( inputSource );
  37542. }
  37543. }
  37544. }
  37545. // Creation method for native WebXR layers
  37546. function createXRLayer( layer ) {
  37547. if ( layer.type === 'quad' ) {
  37548. return this._glBinding.createQuadLayer( {
  37549. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  37550. width: layer.width / 2,
  37551. height: layer.height / 2,
  37552. space: this._referenceSpace,
  37553. viewPixelWidth: layer.pixelwidth,
  37554. viewPixelHeight: layer.pixelheight,
  37555. clearOnAccess: false
  37556. } );
  37557. } else {
  37558. return this._glBinding.createCylinderLayer( {
  37559. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  37560. radius: layer.radius,
  37561. centralAngle: layer.centralAngle,
  37562. aspectRatio: layer.aspectRatio,
  37563. space: this._referenceSpace,
  37564. viewPixelWidth: layer.pixelwidth,
  37565. viewPixelHeight: layer.pixelheight,
  37566. clearOnAccess: false
  37567. } );
  37568. }
  37569. }
  37570. // Animation Loop
  37571. function onAnimationFrame( time, frame ) {
  37572. if ( frame === undefined ) return;
  37573. const cameraXR = this._cameraXR;
  37574. const renderer = this._renderer;
  37575. const backend = renderer.backend;
  37576. const glBaseLayer = this._glBaseLayer;
  37577. const referenceSpace = this.getReferenceSpace();
  37578. const pose = frame.getViewerPose( referenceSpace );
  37579. this._xrFrame = frame;
  37580. if ( pose !== null ) {
  37581. const views = pose.views;
  37582. if ( this._glBaseLayer !== null ) {
  37583. backend.setXRTarget( glBaseLayer.framebuffer );
  37584. }
  37585. let cameraXRNeedsUpdate = false;
  37586. // check if it's necessary to rebuild cameraXR's camera list
  37587. if ( views.length !== cameraXR.cameras.length ) {
  37588. cameraXR.cameras.length = 0;
  37589. cameraXRNeedsUpdate = true;
  37590. }
  37591. for ( let i = 0; i < views.length; i ++ ) {
  37592. const view = views[ i ];
  37593. let viewport;
  37594. if ( this._useLayers === true ) {
  37595. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  37596. viewport = glSubImage.viewport;
  37597. // For side-by-side projection, we only produce a single texture for both eyes.
  37598. if ( i === 0 ) {
  37599. backend.setXRRenderTargetTextures(
  37600. this._xrRenderTarget,
  37601. glSubImage.colorTexture,
  37602. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  37603. );
  37604. }
  37605. } else {
  37606. viewport = glBaseLayer.getViewport( view );
  37607. }
  37608. let camera = this._cameras[ i ];
  37609. if ( camera === undefined ) {
  37610. camera = new PerspectiveCamera();
  37611. camera.layers.enable( i );
  37612. camera.viewport = new Vector4();
  37613. this._cameras[ i ] = camera;
  37614. }
  37615. camera.matrix.fromArray( view.transform.matrix );
  37616. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  37617. camera.projectionMatrix.fromArray( view.projectionMatrix );
  37618. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  37619. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  37620. if ( i === 0 ) {
  37621. cameraXR.matrix.copy( camera.matrix );
  37622. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  37623. }
  37624. if ( cameraXRNeedsUpdate === true ) {
  37625. cameraXR.cameras.push( camera );
  37626. }
  37627. }
  37628. renderer.setOutputRenderTarget( this._xrRenderTarget );
  37629. }
  37630. //
  37631. for ( let i = 0; i < this._controllers.length; i ++ ) {
  37632. const inputSource = this._controllerInputSources[ i ];
  37633. const controller = this._controllers[ i ];
  37634. if ( inputSource !== null && controller !== undefined ) {
  37635. controller.update( inputSource, frame, referenceSpace );
  37636. }
  37637. }
  37638. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  37639. if ( frame.detectedPlanes ) {
  37640. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  37641. }
  37642. this._xrFrame = null;
  37643. }
  37644. const _scene = /*@__PURE__*/ new Scene();
  37645. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  37646. const _screen = /*@__PURE__*/ new Vector4();
  37647. const _frustum = /*@__PURE__*/ new Frustum();
  37648. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  37649. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  37650. const _vector4 = /*@__PURE__*/ new Vector4();
  37651. /**
  37652. * Base class for renderers.
  37653. */
  37654. class Renderer {
  37655. /**
  37656. * Renderer options.
  37657. *
  37658. * @typedef {Object} Renderer~Options
  37659. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  37660. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  37661. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  37662. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  37663. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  37664. * @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
  37665. * to overwrite the default.
  37666. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  37667. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  37668. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  37669. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  37670. */
  37671. /**
  37672. * Constructs a new renderer.
  37673. *
  37674. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  37675. * @param {Renderer~Options} [parameters] - The configuration parameter.
  37676. */
  37677. constructor( backend, parameters = {} ) {
  37678. /**
  37679. * This flag can be used for type testing.
  37680. *
  37681. * @type {boolean}
  37682. * @readonly
  37683. * @default true
  37684. */
  37685. this.isRenderer = true;
  37686. //
  37687. const {
  37688. logarithmicDepthBuffer = false,
  37689. alpha = true,
  37690. depth = true,
  37691. stencil = false,
  37692. antialias = false,
  37693. samples = 0,
  37694. getFallback = null,
  37695. colorBufferType = HalfFloatType,
  37696. multiview = false
  37697. } = parameters;
  37698. /**
  37699. * A reference to the canvas element the renderer is drawing to.
  37700. * This value of this property will automatically be created by
  37701. * the renderer.
  37702. *
  37703. * @type {HTMLCanvasElement|OffscreenCanvas}
  37704. */
  37705. this.domElement = backend.getDomElement();
  37706. /**
  37707. * A reference to the current backend.
  37708. *
  37709. * @type {Backend}
  37710. */
  37711. this.backend = backend;
  37712. /**
  37713. * The number of MSAA samples.
  37714. *
  37715. * @type {number}
  37716. * @default 0
  37717. */
  37718. this.samples = samples || ( antialias === true ) ? 4 : 0;
  37719. /**
  37720. * Whether the renderer should automatically clear the current rendering target
  37721. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  37722. * or the current bound render target (custom framebuffer).
  37723. *
  37724. * @type {boolean}
  37725. * @default true
  37726. */
  37727. this.autoClear = true;
  37728. /**
  37729. * When `autoClear` is set to `true`, this property defines whether the renderer
  37730. * should clear the color buffer.
  37731. *
  37732. * @type {boolean}
  37733. * @default true
  37734. */
  37735. this.autoClearColor = true;
  37736. /**
  37737. * When `autoClear` is set to `true`, this property defines whether the renderer
  37738. * should clear the depth buffer.
  37739. *
  37740. * @type {boolean}
  37741. * @default true
  37742. */
  37743. this.autoClearDepth = true;
  37744. /**
  37745. * When `autoClear` is set to `true`, this property defines whether the renderer
  37746. * should clear the stencil buffer.
  37747. *
  37748. * @type {boolean}
  37749. * @default true
  37750. */
  37751. this.autoClearStencil = true;
  37752. /**
  37753. * Whether the default framebuffer should be transparent or opaque.
  37754. *
  37755. * @type {boolean}
  37756. * @default true
  37757. */
  37758. this.alpha = alpha;
  37759. /**
  37760. * Whether logarithmic depth buffer is enabled or not.
  37761. *
  37762. * @type {boolean}
  37763. * @default false
  37764. */
  37765. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  37766. /**
  37767. * Defines the output color space of the renderer.
  37768. *
  37769. * @type {string}
  37770. * @default SRGBColorSpace
  37771. */
  37772. this.outputColorSpace = SRGBColorSpace;
  37773. /**
  37774. * Defines the tone mapping of the renderer.
  37775. *
  37776. * @type {number}
  37777. * @default NoToneMapping
  37778. */
  37779. this.toneMapping = NoToneMapping;
  37780. /**
  37781. * Defines the tone mapping exposure.
  37782. *
  37783. * @type {number}
  37784. * @default 1
  37785. */
  37786. this.toneMappingExposure = 1.0;
  37787. /**
  37788. * Whether the renderer should sort its render lists or not.
  37789. *
  37790. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  37791. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  37792. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  37793. * e.g. manually determining each object's rendering order.
  37794. *
  37795. * @type {boolean}
  37796. * @default true
  37797. */
  37798. this.sortObjects = true;
  37799. /**
  37800. * Whether the default framebuffer should have a depth buffer or not.
  37801. *
  37802. * @type {boolean}
  37803. * @default true
  37804. */
  37805. this.depth = depth;
  37806. /**
  37807. * Whether the default framebuffer should have a stencil buffer or not.
  37808. *
  37809. * @type {boolean}
  37810. * @default false
  37811. */
  37812. this.stencil = stencil;
  37813. /**
  37814. * Holds a series of statistical information about the GPU memory
  37815. * and the rendering process. Useful for debugging and monitoring.
  37816. *
  37817. * @type {Info}
  37818. */
  37819. this.info = new Info();
  37820. /**
  37821. * Stores override nodes for specific transformations or calculations.
  37822. * These nodes can be used to replace default behavior in the rendering pipeline.
  37823. *
  37824. * @type {Object}
  37825. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  37826. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  37827. */
  37828. this.overrideNodes = {
  37829. modelViewMatrix: null,
  37830. modelNormalViewMatrix: null
  37831. };
  37832. /**
  37833. * The node library defines how certain library objects like materials, lights
  37834. * or tone mapping functions are mapped to node types. This is required since
  37835. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  37836. * be part of the scene graph, they are internally represented as nodes for
  37837. * further processing.
  37838. *
  37839. * @type {NodeLibrary}
  37840. */
  37841. this.library = new NodeLibrary();
  37842. /**
  37843. * A map-like data structure for managing lights.
  37844. *
  37845. * @type {Lighting}
  37846. */
  37847. this.lighting = new Lighting();
  37848. // internals
  37849. /**
  37850. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  37851. *
  37852. * @private
  37853. * @type {?Function}
  37854. */
  37855. this._getFallback = getFallback;
  37856. /**
  37857. * The renderer's pixel ratio.
  37858. *
  37859. * @private
  37860. * @type {number}
  37861. * @default 1
  37862. */
  37863. this._pixelRatio = 1;
  37864. /**
  37865. * The width of the renderer's default framebuffer in logical pixel unit.
  37866. *
  37867. * @private
  37868. * @type {number}
  37869. */
  37870. this._width = this.domElement.width;
  37871. /**
  37872. * The height of the renderer's default framebuffer in logical pixel unit.
  37873. *
  37874. * @private
  37875. * @type {number}
  37876. */
  37877. this._height = this.domElement.height;
  37878. /**
  37879. * The viewport of the renderer in logical pixel unit.
  37880. *
  37881. * @private
  37882. * @type {Vector4}
  37883. */
  37884. this._viewport = new Vector4( 0, 0, this._width, this._height );
  37885. /**
  37886. * The scissor rectangle of the renderer in logical pixel unit.
  37887. *
  37888. * @private
  37889. * @type {Vector4}
  37890. */
  37891. this._scissor = new Vector4( 0, 0, this._width, this._height );
  37892. /**
  37893. * Whether the scissor test should be enabled or not.
  37894. *
  37895. * @private
  37896. * @type {boolean}
  37897. */
  37898. this._scissorTest = false;
  37899. /**
  37900. * A reference to a renderer module for managing shader attributes.
  37901. *
  37902. * @private
  37903. * @type {?Attributes}
  37904. * @default null
  37905. */
  37906. this._attributes = null;
  37907. /**
  37908. * A reference to a renderer module for managing geometries.
  37909. *
  37910. * @private
  37911. * @type {?Geometries}
  37912. * @default null
  37913. */
  37914. this._geometries = null;
  37915. /**
  37916. * A reference to a renderer module for managing node related logic.
  37917. *
  37918. * @private
  37919. * @type {?Nodes}
  37920. * @default null
  37921. */
  37922. this._nodes = null;
  37923. /**
  37924. * A reference to a renderer module for managing the internal animation loop.
  37925. *
  37926. * @private
  37927. * @type {?Animation}
  37928. * @default null
  37929. */
  37930. this._animation = null;
  37931. /**
  37932. * A reference to a renderer module for managing shader program bindings.
  37933. *
  37934. * @private
  37935. * @type {?Bindings}
  37936. * @default null
  37937. */
  37938. this._bindings = null;
  37939. /**
  37940. * A reference to a renderer module for managing render objects.
  37941. *
  37942. * @private
  37943. * @type {?RenderObjects}
  37944. * @default null
  37945. */
  37946. this._objects = null;
  37947. /**
  37948. * A reference to a renderer module for managing render and compute pipelines.
  37949. *
  37950. * @private
  37951. * @type {?Pipelines}
  37952. * @default null
  37953. */
  37954. this._pipelines = null;
  37955. /**
  37956. * A reference to a renderer module for managing render bundles.
  37957. *
  37958. * @private
  37959. * @type {?RenderBundles}
  37960. * @default null
  37961. */
  37962. this._bundles = null;
  37963. /**
  37964. * A reference to a renderer module for managing render lists.
  37965. *
  37966. * @private
  37967. * @type {?RenderLists}
  37968. * @default null
  37969. */
  37970. this._renderLists = null;
  37971. /**
  37972. * A reference to a renderer module for managing render contexts.
  37973. *
  37974. * @private
  37975. * @type {?RenderContexts}
  37976. * @default null
  37977. */
  37978. this._renderContexts = null;
  37979. /**
  37980. * A reference to a renderer module for managing textures.
  37981. *
  37982. * @private
  37983. * @type {?Textures}
  37984. * @default null
  37985. */
  37986. this._textures = null;
  37987. /**
  37988. * A reference to a renderer module for backgrounds.
  37989. *
  37990. * @private
  37991. * @type {?Background}
  37992. * @default null
  37993. */
  37994. this._background = null;
  37995. /**
  37996. * This fullscreen quad is used for internal render passes
  37997. * like the tone mapping and color space output pass.
  37998. *
  37999. * @private
  38000. * @type {QuadMesh}
  38001. */
  38002. this._quad = new QuadMesh( new NodeMaterial() );
  38003. this._quad.material.name = 'Renderer_output';
  38004. /**
  38005. * A reference to the current render context.
  38006. *
  38007. * @private
  38008. * @type {?RenderContext}
  38009. * @default null
  38010. */
  38011. this._currentRenderContext = null;
  38012. /**
  38013. * A custom sort function for the opaque render list.
  38014. *
  38015. * @private
  38016. * @type {?Function}
  38017. * @default null
  38018. */
  38019. this._opaqueSort = null;
  38020. /**
  38021. * A custom sort function for the transparent render list.
  38022. *
  38023. * @private
  38024. * @type {?Function}
  38025. * @default null
  38026. */
  38027. this._transparentSort = null;
  38028. /**
  38029. * The framebuffer target.
  38030. *
  38031. * @private
  38032. * @type {?RenderTarget}
  38033. * @default null
  38034. */
  38035. this._frameBufferTarget = null;
  38036. const alphaClear = this.alpha === true ? 0 : 1;
  38037. /**
  38038. * The clear color value.
  38039. *
  38040. * @private
  38041. * @type {Color4}
  38042. */
  38043. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  38044. /**
  38045. * The clear depth value.
  38046. *
  38047. * @private
  38048. * @type {number}
  38049. * @default 1
  38050. */
  38051. this._clearDepth = 1;
  38052. /**
  38053. * The clear stencil value.
  38054. *
  38055. * @private
  38056. * @type {number}
  38057. * @default 0
  38058. */
  38059. this._clearStencil = 0;
  38060. /**
  38061. * The current render target.
  38062. *
  38063. * @private
  38064. * @type {?RenderTarget}
  38065. * @default null
  38066. */
  38067. this._renderTarget = null;
  38068. /**
  38069. * The active cube face.
  38070. *
  38071. * @private
  38072. * @type {number}
  38073. * @default 0
  38074. */
  38075. this._activeCubeFace = 0;
  38076. /**
  38077. * The active mipmap level.
  38078. *
  38079. * @private
  38080. * @type {number}
  38081. * @default 0
  38082. */
  38083. this._activeMipmapLevel = 0;
  38084. /**
  38085. * The current output render target.
  38086. *
  38087. * @private
  38088. * @type {?RenderTarget}
  38089. * @default null
  38090. */
  38091. this._outputRenderTarget = null;
  38092. /**
  38093. * The MRT setting.
  38094. *
  38095. * @private
  38096. * @type {?MRTNode}
  38097. * @default null
  38098. */
  38099. this._mrt = null;
  38100. /**
  38101. * This function defines how a render object is going
  38102. * to be rendered.
  38103. *
  38104. * @private
  38105. * @type {?Function}
  38106. * @default null
  38107. */
  38108. this._renderObjectFunction = null;
  38109. /**
  38110. * Used to keep track of the current render object function.
  38111. *
  38112. * @private
  38113. * @type {?Function}
  38114. * @default null
  38115. */
  38116. this._currentRenderObjectFunction = null;
  38117. /**
  38118. * Used to keep track of the current render bundle.
  38119. *
  38120. * @private
  38121. * @type {?RenderBundle}
  38122. * @default null
  38123. */
  38124. this._currentRenderBundle = null;
  38125. /**
  38126. * Next to `_renderObjectFunction()`, this function provides another hook
  38127. * for influencing the render process of a render object. It is meant for internal
  38128. * use and only relevant for `compileAsync()` right now. Instead of using
  38129. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  38130. * a different function might be used which performs no draw but just the node
  38131. * and pipeline updates.
  38132. *
  38133. * @private
  38134. * @type {?Function}
  38135. * @default null
  38136. */
  38137. this._handleObjectFunction = this._renderObjectDirect;
  38138. /**
  38139. * Indicates whether the device has been lost or not. In WebGL terms, the device
  38140. * lost is considered as a context lost. When this is set to `true`, rendering
  38141. * isn't possible anymore.
  38142. *
  38143. * @private
  38144. * @type {boolean}
  38145. * @default false
  38146. */
  38147. this._isDeviceLost = false;
  38148. /**
  38149. * A callback function that defines what should happen when a device/context lost occurs.
  38150. *
  38151. * @type {Function}
  38152. */
  38153. this.onDeviceLost = this._onDeviceLost;
  38154. /**
  38155. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  38156. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  38157. * This will reduce rendering quality though.
  38158. *
  38159. * @private
  38160. * @type {number}
  38161. * @default HalfFloatType
  38162. */
  38163. this._colorBufferType = colorBufferType;
  38164. /**
  38165. * Whether the renderer has been initialized or not.
  38166. *
  38167. * @private
  38168. * @type {boolean}
  38169. * @default false
  38170. */
  38171. this._initialized = false;
  38172. /**
  38173. * A reference to the promise which initializes the renderer.
  38174. *
  38175. * @private
  38176. * @type {?Promise<this>}
  38177. * @default null
  38178. */
  38179. this._initPromise = null;
  38180. /**
  38181. * An array of compilation promises which are used in `compileAsync()`.
  38182. *
  38183. * @private
  38184. * @type {?Array<Promise>}
  38185. * @default null
  38186. */
  38187. this._compilationPromises = null;
  38188. /**
  38189. * Whether the renderer should render transparent render objects or not.
  38190. *
  38191. * @type {boolean}
  38192. * @default true
  38193. */
  38194. this.transparent = true;
  38195. /**
  38196. * Whether the renderer should render opaque render objects or not.
  38197. *
  38198. * @type {boolean}
  38199. * @default true
  38200. */
  38201. this.opaque = true;
  38202. /**
  38203. * Shadow map configuration
  38204. * @typedef {Object} ShadowMapConfig
  38205. * @property {boolean} enabled - Whether to globally enable shadows or not.
  38206. * @property {number} type - The shadow map type.
  38207. */
  38208. /**
  38209. * The renderer's shadow configuration.
  38210. *
  38211. * @type {ShadowMapConfig}
  38212. */
  38213. this.shadowMap = {
  38214. enabled: false,
  38215. type: PCFShadowMap
  38216. };
  38217. /**
  38218. * XR configuration.
  38219. * @typedef {Object} XRConfig
  38220. * @property {boolean} enabled - Whether to globally enable XR or not.
  38221. */
  38222. /**
  38223. * The renderer's XR manager.
  38224. *
  38225. * @type {XRManager}
  38226. */
  38227. this.xr = new XRManager( this, multiview );
  38228. /**
  38229. * Debug configuration.
  38230. * @typedef {Object} DebugConfig
  38231. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  38232. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  38233. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  38234. */
  38235. /**
  38236. * The renderer's debug configuration.
  38237. *
  38238. * @type {DebugConfig}
  38239. */
  38240. this.debug = {
  38241. checkShaderErrors: true,
  38242. onShaderError: null,
  38243. getShaderAsync: async ( scene, camera, object ) => {
  38244. await this.compileAsync( scene, camera );
  38245. const renderList = this._renderLists.get( scene, camera );
  38246. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  38247. const material = scene.overrideMaterial || object.material;
  38248. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  38249. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  38250. return { fragmentShader, vertexShader };
  38251. }
  38252. };
  38253. }
  38254. /**
  38255. * Initializes the renderer so it is ready for usage.
  38256. *
  38257. * @async
  38258. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  38259. */
  38260. async init() {
  38261. if ( this._initialized ) {
  38262. throw new Error( 'Renderer: Backend has already been initialized.' );
  38263. }
  38264. if ( this._initPromise !== null ) {
  38265. return this._initPromise;
  38266. }
  38267. this._initPromise = new Promise( async ( resolve, reject ) => {
  38268. let backend = this.backend;
  38269. try {
  38270. await backend.init( this );
  38271. } catch ( error ) {
  38272. if ( this._getFallback !== null ) {
  38273. // try the fallback
  38274. try {
  38275. this.backend = backend = this._getFallback( error );
  38276. await backend.init( this );
  38277. } catch ( error ) {
  38278. reject( error );
  38279. return;
  38280. }
  38281. } else {
  38282. reject( error );
  38283. return;
  38284. }
  38285. }
  38286. this._nodes = new Nodes( this, backend );
  38287. this._animation = new Animation( this._nodes, this.info );
  38288. this._attributes = new Attributes( backend );
  38289. this._background = new Background( this, this._nodes );
  38290. this._geometries = new Geometries( this._attributes, this.info );
  38291. this._textures = new Textures( this, backend, this.info );
  38292. this._pipelines = new Pipelines( backend, this._nodes );
  38293. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  38294. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  38295. this._renderLists = new RenderLists( this.lighting );
  38296. this._bundles = new RenderBundles();
  38297. this._renderContexts = new RenderContexts();
  38298. //
  38299. this._animation.start();
  38300. this._initialized = true;
  38301. resolve( this );
  38302. } );
  38303. return this._initPromise;
  38304. }
  38305. /**
  38306. * The coordinate system of the renderer. The value of this property
  38307. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  38308. * `THREE.WebGPUCoordinateSystem`.
  38309. *
  38310. * @readonly
  38311. * @type {number}
  38312. */
  38313. get coordinateSystem() {
  38314. return this.backend.coordinateSystem;
  38315. }
  38316. /**
  38317. * Compiles all materials in the given scene. This can be useful to avoid a
  38318. * phenomenon which is called "shader compilation stutter", which occurs when
  38319. * rendering an object with a new shader for the first time.
  38320. *
  38321. * If you want to add a 3D object to an existing scene, use the third optional
  38322. * parameter for applying the target scene. Note that the (target) scene's lighting
  38323. * and environment must be configured before calling this method.
  38324. *
  38325. * @async
  38326. * @param {Object3D} scene - The scene or 3D object to precompile.
  38327. * @param {Camera} camera - The camera that is used to render the scene.
  38328. * @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.
  38329. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  38330. */
  38331. async compileAsync( scene, camera, targetScene = null ) {
  38332. if ( this._isDeviceLost === true ) return;
  38333. if ( this._initialized === false ) await this.init();
  38334. // preserve render tree
  38335. const nodeFrame = this._nodes.nodeFrame;
  38336. const previousRenderId = nodeFrame.renderId;
  38337. const previousRenderContext = this._currentRenderContext;
  38338. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  38339. const previousCompilationPromises = this._compilationPromises;
  38340. //
  38341. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  38342. if ( targetScene === null ) targetScene = scene;
  38343. const renderTarget = this._renderTarget;
  38344. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  38345. const activeMipmapLevel = this._activeMipmapLevel;
  38346. const compilationPromises = [];
  38347. this._currentRenderContext = renderContext;
  38348. this._currentRenderObjectFunction = this.renderObject;
  38349. this._handleObjectFunction = this._createObjectPipeline;
  38350. this._compilationPromises = compilationPromises;
  38351. nodeFrame.renderId ++;
  38352. //
  38353. nodeFrame.update();
  38354. //
  38355. renderContext.depth = this.depth;
  38356. renderContext.stencil = this.stencil;
  38357. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  38358. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  38359. //
  38360. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  38361. //
  38362. const renderList = this._renderLists.get( scene, camera );
  38363. renderList.begin();
  38364. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  38365. // include lights from target scene
  38366. if ( targetScene !== scene ) {
  38367. targetScene.traverseVisible( function ( object ) {
  38368. if ( object.isLight && object.layers.test( camera.layers ) ) {
  38369. renderList.pushLight( object );
  38370. }
  38371. } );
  38372. }
  38373. renderList.finish();
  38374. //
  38375. if ( renderTarget !== null ) {
  38376. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  38377. const renderTargetData = this._textures.get( renderTarget );
  38378. renderContext.textures = renderTargetData.textures;
  38379. renderContext.depthTexture = renderTargetData.depthTexture;
  38380. } else {
  38381. renderContext.textures = null;
  38382. renderContext.depthTexture = null;
  38383. }
  38384. //
  38385. this._background.update( sceneRef, renderList, renderContext );
  38386. // process render lists
  38387. const opaqueObjects = renderList.opaque;
  38388. const transparentObjects = renderList.transparent;
  38389. const transparentDoublePassObjects = renderList.transparentDoublePass;
  38390. const lightsNode = renderList.lightsNode;
  38391. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  38392. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  38393. // restore render tree
  38394. nodeFrame.renderId = previousRenderId;
  38395. this._currentRenderContext = previousRenderContext;
  38396. this._currentRenderObjectFunction = previousRenderObjectFunction;
  38397. this._compilationPromises = previousCompilationPromises;
  38398. this._handleObjectFunction = this._renderObjectDirect;
  38399. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  38400. await Promise.all( compilationPromises );
  38401. }
  38402. /**
  38403. * Renders the scene in an async fashion.
  38404. *
  38405. * @async
  38406. * @param {Object3D} scene - The scene or 3D object to render.
  38407. * @param {Camera} camera - The camera.
  38408. * @return {Promise} A Promise that resolves when the render has been finished.
  38409. */
  38410. async renderAsync( scene, camera ) {
  38411. if ( this._initialized === false ) await this.init();
  38412. this._renderScene( scene, camera );
  38413. }
  38414. /**
  38415. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  38416. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  38417. *
  38418. * @async
  38419. * @return {Promise} A Promise that resolves when synchronization has been finished.
  38420. */
  38421. async waitForGPU() {
  38422. await this.backend.waitForGPU();
  38423. }
  38424. /**
  38425. * Enables or disables high precision for model-view and normal-view matrices.
  38426. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  38427. *
  38428. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  38429. *
  38430. * @param {boolean} value - Whether to enable or disable high precision.
  38431. * @type {boolean}
  38432. */
  38433. set highPrecision( value ) {
  38434. if ( value === true ) {
  38435. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  38436. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  38437. } else if ( this.highPrecision ) {
  38438. this.overrideNodes.modelViewMatrix = null;
  38439. this.overrideNodes.modelNormalViewMatrix = null;
  38440. }
  38441. }
  38442. /**
  38443. * Returns whether high precision is enabled or not.
  38444. *
  38445. * @return {boolean} Whether high precision is enabled or not.
  38446. * @type {boolean}
  38447. */
  38448. get highPrecision() {
  38449. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  38450. }
  38451. /**
  38452. * Sets the given MRT configuration.
  38453. *
  38454. * @param {MRTNode} mrt - The MRT node to set.
  38455. * @return {Renderer} A reference to this renderer.
  38456. */
  38457. setMRT( mrt ) {
  38458. this._mrt = mrt;
  38459. return this;
  38460. }
  38461. /**
  38462. * Returns the MRT configuration.
  38463. *
  38464. * @return {MRTNode} The MRT configuration.
  38465. */
  38466. getMRT() {
  38467. return this._mrt;
  38468. }
  38469. /**
  38470. * Returns the color buffer type.
  38471. *
  38472. * @return {number} The color buffer type.
  38473. */
  38474. getColorBufferType() {
  38475. return this._colorBufferType;
  38476. }
  38477. /**
  38478. * Default implementation of the device lost callback.
  38479. *
  38480. * @private
  38481. * @param {Object} info - Information about the context lost.
  38482. */
  38483. _onDeviceLost( info ) {
  38484. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  38485. if ( info.reason ) {
  38486. errorMessage += `\nReason: ${info.reason}`;
  38487. }
  38488. console.error( errorMessage );
  38489. this._isDeviceLost = true;
  38490. }
  38491. /**
  38492. * Renders the given render bundle.
  38493. *
  38494. * @private
  38495. * @param {Object} bundle - Render bundle data.
  38496. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  38497. * @param {LightsNode} lightsNode - The lights node.
  38498. */
  38499. _renderBundle( bundle, sceneRef, lightsNode ) {
  38500. const { bundleGroup, camera, renderList } = bundle;
  38501. const renderContext = this._currentRenderContext;
  38502. //
  38503. const renderBundle = this._bundles.get( bundleGroup, camera );
  38504. const renderBundleData = this.backend.get( renderBundle );
  38505. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  38506. //
  38507. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  38508. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  38509. renderBundleData.renderContexts.add( renderContext );
  38510. if ( renderBundleNeedsUpdate ) {
  38511. this.backend.beginBundle( renderContext );
  38512. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  38513. renderBundleData.renderObjects = [];
  38514. }
  38515. this._currentRenderBundle = renderBundle;
  38516. const {
  38517. transparentDoublePass: transparentDoublePassObjects,
  38518. transparent: transparentObjects,
  38519. opaque: opaqueObjects
  38520. } = renderList;
  38521. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  38522. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  38523. this._currentRenderBundle = null;
  38524. //
  38525. this.backend.finishBundle( renderContext, renderBundle );
  38526. renderBundleData.version = bundleGroup.version;
  38527. } else {
  38528. const { renderObjects } = renderBundleData;
  38529. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  38530. const renderObject = renderObjects[ i ];
  38531. if ( this._nodes.needsRefresh( renderObject ) ) {
  38532. this._nodes.updateBefore( renderObject );
  38533. this._nodes.updateForRender( renderObject );
  38534. this._bindings.updateForRender( renderObject );
  38535. this._nodes.updateAfter( renderObject );
  38536. }
  38537. }
  38538. }
  38539. this.backend.addBundle( renderContext, renderBundle );
  38540. }
  38541. /**
  38542. * Renders the scene or 3D object with the given camera. This method can only be called
  38543. * if the renderer has been initialized.
  38544. *
  38545. * The target of the method is the default framebuffer (meaning the canvas)
  38546. * or alternatively a render target when specified via `setRenderTarget()`.
  38547. *
  38548. * @param {Object3D} scene - The scene or 3D object to render.
  38549. * @param {Camera} camera - The camera to render the scene with.
  38550. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  38551. * Only returned when the renderer has not been initialized.
  38552. */
  38553. render( scene, camera ) {
  38554. if ( this._initialized === false ) {
  38555. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  38556. return this.renderAsync( scene, camera );
  38557. }
  38558. this._renderScene( scene, camera );
  38559. }
  38560. /**
  38561. * Returns an internal render target which is used when computing the output tone mapping
  38562. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  38563. * pass and not inline to achieve more correct results.
  38564. *
  38565. * @private
  38566. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  38567. */
  38568. _getFrameBufferTarget() {
  38569. const { currentToneMapping, currentColorSpace } = this;
  38570. const useToneMapping = currentToneMapping !== NoToneMapping;
  38571. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  38572. if ( useToneMapping === false && useColorSpace === false ) return null;
  38573. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  38574. const { depth, stencil } = this;
  38575. let frameBufferTarget = this._frameBufferTarget;
  38576. if ( frameBufferTarget === null ) {
  38577. frameBufferTarget = new RenderTarget( width, height, {
  38578. depthBuffer: depth,
  38579. stencilBuffer: stencil,
  38580. type: this._colorBufferType,
  38581. format: RGBAFormat,
  38582. colorSpace: ColorManagement.workingColorSpace,
  38583. generateMipmaps: false,
  38584. minFilter: LinearFilter,
  38585. magFilter: LinearFilter,
  38586. samples: this.samples
  38587. } );
  38588. frameBufferTarget.isPostProcessingRenderTarget = true;
  38589. this._frameBufferTarget = frameBufferTarget;
  38590. }
  38591. const outputRenderTarget = this.getOutputRenderTarget();
  38592. frameBufferTarget.depthBuffer = depth;
  38593. frameBufferTarget.stencilBuffer = stencil;
  38594. if ( outputRenderTarget !== null ) {
  38595. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  38596. } else {
  38597. frameBufferTarget.setSize( width, height, 1 );
  38598. }
  38599. frameBufferTarget.viewport.copy( this._viewport );
  38600. frameBufferTarget.scissor.copy( this._scissor );
  38601. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  38602. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  38603. frameBufferTarget.scissorTest = this._scissorTest;
  38604. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  38605. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  38606. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  38607. return frameBufferTarget;
  38608. }
  38609. /**
  38610. * Renders the scene or 3D object with the given camera.
  38611. *
  38612. * @private
  38613. * @param {Object3D} scene - The scene or 3D object to render.
  38614. * @param {Camera} camera - The camera to render the scene with.
  38615. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  38616. * @return {RenderContext} The current render context.
  38617. */
  38618. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  38619. if ( this._isDeviceLost === true ) return;
  38620. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  38621. // preserve render tree
  38622. const nodeFrame = this._nodes.nodeFrame;
  38623. const previousRenderId = nodeFrame.renderId;
  38624. const previousRenderContext = this._currentRenderContext;
  38625. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  38626. //
  38627. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  38628. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  38629. const activeCubeFace = this._activeCubeFace;
  38630. const activeMipmapLevel = this._activeMipmapLevel;
  38631. //
  38632. let renderTarget;
  38633. if ( frameBufferTarget !== null ) {
  38634. renderTarget = frameBufferTarget;
  38635. this.setRenderTarget( renderTarget );
  38636. } else {
  38637. renderTarget = outputRenderTarget;
  38638. }
  38639. //
  38640. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  38641. this._currentRenderContext = renderContext;
  38642. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  38643. //
  38644. this.info.calls ++;
  38645. this.info.render.calls ++;
  38646. this.info.render.frameCalls ++;
  38647. nodeFrame.renderId = this.info.calls;
  38648. //
  38649. const coordinateSystem = this.coordinateSystem;
  38650. const xr = this.xr;
  38651. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  38652. camera.coordinateSystem = coordinateSystem;
  38653. camera.updateProjectionMatrix();
  38654. if ( camera.isArrayCamera ) {
  38655. for ( const subCamera of camera.cameras ) {
  38656. subCamera.coordinateSystem = coordinateSystem;
  38657. subCamera.updateProjectionMatrix();
  38658. }
  38659. }
  38660. }
  38661. //
  38662. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  38663. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  38664. if ( xr.enabled === true && xr.isPresenting === true ) {
  38665. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  38666. camera = xr.getCamera(); // use XR camera for rendering
  38667. }
  38668. //
  38669. let viewport = this._viewport;
  38670. let scissor = this._scissor;
  38671. let pixelRatio = this._pixelRatio;
  38672. if ( renderTarget !== null ) {
  38673. viewport = renderTarget.viewport;
  38674. scissor = renderTarget.scissor;
  38675. pixelRatio = 1;
  38676. }
  38677. this.getDrawingBufferSize( _drawingBufferSize );
  38678. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  38679. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  38680. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  38681. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  38682. renderContext.viewportValue.width >>= activeMipmapLevel;
  38683. renderContext.viewportValue.height >>= activeMipmapLevel;
  38684. renderContext.viewportValue.minDepth = minDepth;
  38685. renderContext.viewportValue.maxDepth = maxDepth;
  38686. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  38687. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  38688. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  38689. renderContext.scissorValue.width >>= activeMipmapLevel;
  38690. renderContext.scissorValue.height >>= activeMipmapLevel;
  38691. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  38692. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  38693. //
  38694. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  38695. //
  38696. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  38697. if ( ! camera.isArrayCamera ) {
  38698. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  38699. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  38700. }
  38701. const renderList = this._renderLists.get( scene, camera );
  38702. renderList.begin();
  38703. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  38704. renderList.finish();
  38705. if ( this.sortObjects === true ) {
  38706. renderList.sort( this._opaqueSort, this._transparentSort );
  38707. }
  38708. //
  38709. if ( renderTarget !== null ) {
  38710. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  38711. const renderTargetData = this._textures.get( renderTarget );
  38712. renderContext.textures = renderTargetData.textures;
  38713. renderContext.depthTexture = renderTargetData.depthTexture;
  38714. renderContext.width = renderTargetData.width;
  38715. renderContext.height = renderTargetData.height;
  38716. renderContext.renderTarget = renderTarget;
  38717. renderContext.depth = renderTarget.depthBuffer;
  38718. renderContext.stencil = renderTarget.stencilBuffer;
  38719. } else {
  38720. renderContext.textures = null;
  38721. renderContext.depthTexture = null;
  38722. renderContext.width = this.domElement.width;
  38723. renderContext.height = this.domElement.height;
  38724. renderContext.depth = this.depth;
  38725. renderContext.stencil = this.stencil;
  38726. }
  38727. renderContext.width >>= activeMipmapLevel;
  38728. renderContext.height >>= activeMipmapLevel;
  38729. renderContext.activeCubeFace = activeCubeFace;
  38730. renderContext.activeMipmapLevel = activeMipmapLevel;
  38731. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  38732. //
  38733. this._background.update( sceneRef, renderList, renderContext );
  38734. //
  38735. renderContext.camera = camera;
  38736. this.backend.beginRender( renderContext );
  38737. // process render lists
  38738. const {
  38739. bundles,
  38740. lightsNode,
  38741. transparentDoublePass: transparentDoublePassObjects,
  38742. transparent: transparentObjects,
  38743. opaque: opaqueObjects
  38744. } = renderList;
  38745. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  38746. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  38747. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  38748. // finish render pass
  38749. this.backend.finishRender( renderContext );
  38750. // restore render tree
  38751. nodeFrame.renderId = previousRenderId;
  38752. this._currentRenderContext = previousRenderContext;
  38753. this._currentRenderObjectFunction = previousRenderObjectFunction;
  38754. //
  38755. if ( frameBufferTarget !== null ) {
  38756. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  38757. this._renderOutput( renderTarget );
  38758. }
  38759. //
  38760. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  38761. //
  38762. return renderContext;
  38763. }
  38764. _setXRLayerSize( width, height ) {
  38765. this._width = width;
  38766. this._height = height;
  38767. this.setViewport( 0, 0, width, height );
  38768. }
  38769. /**
  38770. * The output pass performs tone mapping and color space conversion.
  38771. *
  38772. * @private
  38773. * @param {RenderTarget} renderTarget - The current render target.
  38774. */
  38775. _renderOutput( renderTarget ) {
  38776. const quad = this._quad;
  38777. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  38778. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  38779. quad.material.needsUpdate = true;
  38780. }
  38781. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  38782. const currentAutoClear = this.autoClear;
  38783. const currentXR = this.xr.enabled;
  38784. this.autoClear = false;
  38785. this.xr.enabled = false;
  38786. this._renderScene( quad, quad.camera, false );
  38787. this.autoClear = currentAutoClear;
  38788. this.xr.enabled = currentXR;
  38789. }
  38790. /**
  38791. * Returns the maximum available anisotropy for texture filtering.
  38792. *
  38793. * @return {number} The maximum available anisotropy.
  38794. */
  38795. getMaxAnisotropy() {
  38796. return this.backend.getMaxAnisotropy();
  38797. }
  38798. /**
  38799. * Returns the active cube face.
  38800. *
  38801. * @return {number} The active cube face.
  38802. */
  38803. getActiveCubeFace() {
  38804. return this._activeCubeFace;
  38805. }
  38806. /**
  38807. * Returns the active mipmap level.
  38808. *
  38809. * @return {number} The active mipmap level.
  38810. */
  38811. getActiveMipmapLevel() {
  38812. return this._activeMipmapLevel;
  38813. }
  38814. /**
  38815. * Applications are advised to always define the animation loop
  38816. * with this method and not manually with `requestAnimationFrame()`
  38817. * for best compatibility.
  38818. *
  38819. * @async
  38820. * @param {?Function} callback - The application's animation loop.
  38821. * @return {Promise} A Promise that resolves when the set has been executed.
  38822. */
  38823. async setAnimationLoop( callback ) {
  38824. if ( this._initialized === false ) await this.init();
  38825. this._animation.setAnimationLoop( callback );
  38826. }
  38827. /**
  38828. * Can be used to transfer buffer data from a storage buffer attribute
  38829. * from the GPU to the CPU in context of compute shaders.
  38830. *
  38831. * @async
  38832. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  38833. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  38834. */
  38835. async getArrayBufferAsync( attribute ) {
  38836. return await this.backend.getArrayBufferAsync( attribute );
  38837. }
  38838. /**
  38839. * Returns the rendering context.
  38840. *
  38841. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  38842. */
  38843. getContext() {
  38844. return this.backend.getContext();
  38845. }
  38846. /**
  38847. * Returns the pixel ratio.
  38848. *
  38849. * @return {number} The pixel ratio.
  38850. */
  38851. getPixelRatio() {
  38852. return this._pixelRatio;
  38853. }
  38854. /**
  38855. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  38856. *
  38857. * @param {Vector2} target - The method writes the result in this target object.
  38858. * @return {Vector2} The drawing buffer size.
  38859. */
  38860. getDrawingBufferSize( target ) {
  38861. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  38862. }
  38863. /**
  38864. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  38865. *
  38866. * @param {Vector2} target - The method writes the result in this target object.
  38867. * @return {Vector2} The renderer's size in logical pixels.
  38868. */
  38869. getSize( target ) {
  38870. return target.set( this._width, this._height );
  38871. }
  38872. /**
  38873. * Sets the given pixel ratio and resizes the canvas if necessary.
  38874. *
  38875. * @param {number} [value=1] - The pixel ratio.
  38876. */
  38877. setPixelRatio( value = 1 ) {
  38878. if ( this._pixelRatio === value ) return;
  38879. this._pixelRatio = value;
  38880. this.setSize( this._width, this._height, false );
  38881. }
  38882. /**
  38883. * This method allows to define the drawing buffer size by specifying
  38884. * width, height and pixel ratio all at once. The size of the drawing
  38885. * buffer is computed with this formula:
  38886. * ```js
  38887. * size.x = width * pixelRatio;
  38888. * size.y = height * pixelRatio;
  38889. * ```
  38890. *
  38891. * @param {number} width - The width in logical pixels.
  38892. * @param {number} height - The height in logical pixels.
  38893. * @param {number} pixelRatio - The pixel ratio.
  38894. */
  38895. setDrawingBufferSize( width, height, pixelRatio ) {
  38896. // Renderer can't be resized while presenting in XR.
  38897. if ( this.xr && this.xr.isPresenting ) return;
  38898. this._width = width;
  38899. this._height = height;
  38900. this._pixelRatio = pixelRatio;
  38901. this.domElement.width = Math.floor( width * pixelRatio );
  38902. this.domElement.height = Math.floor( height * pixelRatio );
  38903. this.setViewport( 0, 0, width, height );
  38904. if ( this._initialized ) this.backend.updateSize();
  38905. }
  38906. /**
  38907. * Sets the size of the renderer.
  38908. *
  38909. * @param {number} width - The width in logical pixels.
  38910. * @param {number} height - The height in logical pixels.
  38911. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  38912. */
  38913. setSize( width, height, updateStyle = true ) {
  38914. // Renderer can't be resized while presenting in XR.
  38915. if ( this.xr && this.xr.isPresenting ) return;
  38916. this._width = width;
  38917. this._height = height;
  38918. this.domElement.width = Math.floor( width * this._pixelRatio );
  38919. this.domElement.height = Math.floor( height * this._pixelRatio );
  38920. if ( updateStyle === true ) {
  38921. this.domElement.style.width = width + 'px';
  38922. this.domElement.style.height = height + 'px';
  38923. }
  38924. this.setViewport( 0, 0, width, height );
  38925. if ( this._initialized ) this.backend.updateSize();
  38926. }
  38927. /**
  38928. * Defines a manual sort function for the opaque render list.
  38929. * Pass `null` to use the default sort.
  38930. *
  38931. * @param {Function} method - The sort function.
  38932. */
  38933. setOpaqueSort( method ) {
  38934. this._opaqueSort = method;
  38935. }
  38936. /**
  38937. * Defines a manual sort function for the transparent render list.
  38938. * Pass `null` to use the default sort.
  38939. *
  38940. * @param {Function} method - The sort function.
  38941. */
  38942. setTransparentSort( method ) {
  38943. this._transparentSort = method;
  38944. }
  38945. /**
  38946. * Returns the scissor rectangle.
  38947. *
  38948. * @param {Vector4} target - The method writes the result in this target object.
  38949. * @return {Vector4} The scissor rectangle.
  38950. */
  38951. getScissor( target ) {
  38952. const scissor = this._scissor;
  38953. target.x = scissor.x;
  38954. target.y = scissor.y;
  38955. target.width = scissor.width;
  38956. target.height = scissor.height;
  38957. return target;
  38958. }
  38959. /**
  38960. * Defines the scissor rectangle.
  38961. *
  38962. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  38963. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  38964. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  38965. * @param {number} width - The width of the scissor box in logical pixel unit.
  38966. * @param {number} height - The height of the scissor box in logical pixel unit.
  38967. */
  38968. setScissor( x, y, width, height ) {
  38969. const scissor = this._scissor;
  38970. if ( x.isVector4 ) {
  38971. scissor.copy( x );
  38972. } else {
  38973. scissor.set( x, y, width, height );
  38974. }
  38975. }
  38976. /**
  38977. * Returns the scissor test value.
  38978. *
  38979. * @return {boolean} Whether the scissor test should be enabled or not.
  38980. */
  38981. getScissorTest() {
  38982. return this._scissorTest;
  38983. }
  38984. /**
  38985. * Defines the scissor test.
  38986. *
  38987. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  38988. */
  38989. setScissorTest( boolean ) {
  38990. this._scissorTest = boolean;
  38991. this.backend.setScissorTest( boolean );
  38992. }
  38993. /**
  38994. * Returns the viewport definition.
  38995. *
  38996. * @param {Vector4} target - The method writes the result in this target object.
  38997. * @return {Vector4} The viewport definition.
  38998. */
  38999. getViewport( target ) {
  39000. return target.copy( this._viewport );
  39001. }
  39002. /**
  39003. * Defines the viewport.
  39004. *
  39005. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39006. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39007. * @param {number} width - The width of the viewport in logical pixel unit.
  39008. * @param {number} height - The height of the viewport in logical pixel unit.
  39009. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  39010. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  39011. */
  39012. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  39013. const viewport = this._viewport;
  39014. if ( x.isVector4 ) {
  39015. viewport.copy( x );
  39016. } else {
  39017. viewport.set( x, y, width, height );
  39018. }
  39019. viewport.minDepth = minDepth;
  39020. viewport.maxDepth = maxDepth;
  39021. }
  39022. /**
  39023. * Returns the clear color.
  39024. *
  39025. * @param {Color} target - The method writes the result in this target object.
  39026. * @return {Color} The clear color.
  39027. */
  39028. getClearColor( target ) {
  39029. return target.copy( this._clearColor );
  39030. }
  39031. /**
  39032. * Defines the clear color and optionally the clear alpha.
  39033. *
  39034. * @param {Color} color - The clear color.
  39035. * @param {number} [alpha=1] - The clear alpha.
  39036. */
  39037. setClearColor( color, alpha = 1 ) {
  39038. this._clearColor.set( color );
  39039. this._clearColor.a = alpha;
  39040. }
  39041. /**
  39042. * Returns the clear alpha.
  39043. *
  39044. * @return {number} The clear alpha.
  39045. */
  39046. getClearAlpha() {
  39047. return this._clearColor.a;
  39048. }
  39049. /**
  39050. * Defines the clear alpha.
  39051. *
  39052. * @param {number} alpha - The clear alpha.
  39053. */
  39054. setClearAlpha( alpha ) {
  39055. this._clearColor.a = alpha;
  39056. }
  39057. /**
  39058. * Returns the clear depth.
  39059. *
  39060. * @return {number} The clear depth.
  39061. */
  39062. getClearDepth() {
  39063. return this._clearDepth;
  39064. }
  39065. /**
  39066. * Defines the clear depth.
  39067. *
  39068. * @param {number} depth - The clear depth.
  39069. */
  39070. setClearDepth( depth ) {
  39071. this._clearDepth = depth;
  39072. }
  39073. /**
  39074. * Returns the clear stencil.
  39075. *
  39076. * @return {number} The clear stencil.
  39077. */
  39078. getClearStencil() {
  39079. return this._clearStencil;
  39080. }
  39081. /**
  39082. * Defines the clear stencil.
  39083. *
  39084. * @param {number} stencil - The clear stencil.
  39085. */
  39086. setClearStencil( stencil ) {
  39087. this._clearStencil = stencil;
  39088. }
  39089. /**
  39090. * This method performs an occlusion query for the given 3D object.
  39091. * It returns `true` if the given 3D object is fully occluded by other
  39092. * 3D objects in the scene.
  39093. *
  39094. * @param {Object3D} object - The 3D object to test.
  39095. * @return {boolean} Whether the 3D object is fully occluded or not.
  39096. */
  39097. isOccluded( object ) {
  39098. const renderContext = this._currentRenderContext;
  39099. return renderContext && this.backend.isOccluded( renderContext, object );
  39100. }
  39101. /**
  39102. * Performs a manual clear operation. This method ignores `autoClear` properties.
  39103. *
  39104. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  39105. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  39106. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  39107. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39108. * Only returned when the renderer has not been initialized.
  39109. */
  39110. clear( color = true, depth = true, stencil = true ) {
  39111. if ( this._initialized === false ) {
  39112. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  39113. return this.clearAsync( color, depth, stencil );
  39114. }
  39115. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  39116. let renderContext = null;
  39117. if ( renderTarget !== null ) {
  39118. this._textures.updateRenderTarget( renderTarget );
  39119. const renderTargetData = this._textures.get( renderTarget );
  39120. renderContext = this._renderContexts.getForClear( renderTarget );
  39121. renderContext.textures = renderTargetData.textures;
  39122. renderContext.depthTexture = renderTargetData.depthTexture;
  39123. renderContext.width = renderTargetData.width;
  39124. renderContext.height = renderTargetData.height;
  39125. renderContext.renderTarget = renderTarget;
  39126. renderContext.depth = renderTarget.depthBuffer;
  39127. renderContext.stencil = renderTarget.stencilBuffer;
  39128. // #30329
  39129. renderContext.clearColorValue = this.backend.getClearColor();
  39130. renderContext.activeCubeFace = this.getActiveCubeFace();
  39131. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  39132. }
  39133. this.backend.clear( color, depth, stencil, renderContext );
  39134. if ( renderTarget !== null && this._renderTarget === null ) {
  39135. this._renderOutput( renderTarget );
  39136. }
  39137. }
  39138. /**
  39139. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  39140. *
  39141. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39142. * Only returned when the renderer has not been initialized.
  39143. */
  39144. clearColor() {
  39145. return this.clear( true, false, false );
  39146. }
  39147. /**
  39148. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  39149. *
  39150. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39151. * Only returned when the renderer has not been initialized.
  39152. */
  39153. clearDepth() {
  39154. return this.clear( false, true, false );
  39155. }
  39156. /**
  39157. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  39158. *
  39159. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39160. * Only returned when the renderer has not been initialized.
  39161. */
  39162. clearStencil() {
  39163. return this.clear( false, false, true );
  39164. }
  39165. /**
  39166. * Async version of {@link Renderer#clear}.
  39167. *
  39168. * @async
  39169. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  39170. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  39171. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  39172. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39173. */
  39174. async clearAsync( color = true, depth = true, stencil = true ) {
  39175. if ( this._initialized === false ) await this.init();
  39176. this.clear( color, depth, stencil );
  39177. }
  39178. /**
  39179. * Async version of {@link Renderer#clearColor}.
  39180. *
  39181. * @async
  39182. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39183. */
  39184. async clearColorAsync() {
  39185. this.clearAsync( true, false, false );
  39186. }
  39187. /**
  39188. * Async version of {@link Renderer#clearDepth}.
  39189. *
  39190. * @async
  39191. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39192. */
  39193. async clearDepthAsync() {
  39194. this.clearAsync( false, true, false );
  39195. }
  39196. /**
  39197. * Async version of {@link Renderer#clearStencil}.
  39198. *
  39199. * @async
  39200. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  39201. */
  39202. async clearStencilAsync() {
  39203. this.clearAsync( false, false, true );
  39204. }
  39205. /**
  39206. * The current tone mapping of the renderer. When not producing screen output,
  39207. * the tone mapping is always `NoToneMapping`.
  39208. *
  39209. * @type {number}
  39210. */
  39211. get currentToneMapping() {
  39212. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  39213. }
  39214. /**
  39215. * The current color space of the renderer. When not producing screen output,
  39216. * the color space is always the working color space.
  39217. *
  39218. * @type {string}
  39219. */
  39220. get currentColorSpace() {
  39221. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  39222. }
  39223. /**
  39224. * Returns `true` if the rendering settings are set to screen output.
  39225. *
  39226. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  39227. */
  39228. get isOutputTarget() {
  39229. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  39230. }
  39231. /**
  39232. * Frees all internal resources of the renderer. Call this method if the renderer
  39233. * is no longer in use by your app.
  39234. */
  39235. dispose() {
  39236. this.info.dispose();
  39237. this.backend.dispose();
  39238. this._animation.dispose();
  39239. this._objects.dispose();
  39240. this._pipelines.dispose();
  39241. this._nodes.dispose();
  39242. this._bindings.dispose();
  39243. this._renderLists.dispose();
  39244. this._renderContexts.dispose();
  39245. this._textures.dispose();
  39246. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  39247. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  39248. if ( queryPool !== null ) queryPool.dispose();
  39249. } );
  39250. this.setRenderTarget( null );
  39251. this.setAnimationLoop( null );
  39252. }
  39253. /**
  39254. * Sets the given render target. Calling this method means the renderer does not
  39255. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  39256. * Use `null` as the first argument to reset the state.
  39257. *
  39258. * @param {?RenderTarget} renderTarget - The render target to set.
  39259. * @param {number} [activeCubeFace=0] - The active cube face.
  39260. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  39261. */
  39262. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  39263. this._renderTarget = renderTarget;
  39264. this._activeCubeFace = activeCubeFace;
  39265. this._activeMipmapLevel = activeMipmapLevel;
  39266. }
  39267. /**
  39268. * Returns the current render target.
  39269. *
  39270. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  39271. */
  39272. getRenderTarget() {
  39273. return this._renderTarget;
  39274. }
  39275. /**
  39276. * Sets the output render target for the renderer.
  39277. *
  39278. * @param {Object} renderTarget - The render target to set as the output target.
  39279. */
  39280. setOutputRenderTarget( renderTarget ) {
  39281. this._outputRenderTarget = renderTarget;
  39282. }
  39283. /**
  39284. * Returns the current output target.
  39285. *
  39286. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  39287. */
  39288. getOutputRenderTarget() {
  39289. return this._outputRenderTarget;
  39290. }
  39291. /**
  39292. * Resets the renderer to the initial state before WebXR started.
  39293. *
  39294. */
  39295. _resetXRState() {
  39296. this.backend.setXRTarget( null );
  39297. this.setOutputRenderTarget( null );
  39298. this.setRenderTarget( null );
  39299. this._frameBufferTarget.dispose();
  39300. this._frameBufferTarget = null;
  39301. }
  39302. /**
  39303. * Callback for {@link Renderer#setRenderObjectFunction}.
  39304. *
  39305. * @callback renderObjectFunction
  39306. * @param {Object3D} object - The 3D object.
  39307. * @param {Scene} scene - The scene the 3D object belongs to.
  39308. * @param {Camera} camera - The camera the object should be rendered with.
  39309. * @param {BufferGeometry} geometry - The object's geometry.
  39310. * @param {Material} material - The object's material.
  39311. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  39312. * @param {LightsNode} lightsNode - The current lights node.
  39313. * @param {ClippingContext} clippingContext - The clipping context.
  39314. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  39315. */
  39316. /**
  39317. * Sets the given render object function. Calling this method overwrites the default implementation
  39318. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  39319. * if you want to modify the way objects are rendered. For example you can define things like "every
  39320. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  39321. * The custom function must always call `renderObject()` in its implementation.
  39322. *
  39323. * Use `null` as the first argument to reset the state.
  39324. *
  39325. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  39326. */
  39327. setRenderObjectFunction( renderObjectFunction ) {
  39328. this._renderObjectFunction = renderObjectFunction;
  39329. }
  39330. /**
  39331. * Returns the current render object function.
  39332. *
  39333. * @return {?Function} The current render object function. Returns `null` if no function is set.
  39334. */
  39335. getRenderObjectFunction() {
  39336. return this._renderObjectFunction;
  39337. }
  39338. /**
  39339. * Execute a single or an array of compute nodes. This method can only be called
  39340. * if the renderer has been initialized.
  39341. *
  39342. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  39343. * @param {Array<number>|number} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  39344. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  39345. */
  39346. compute( computeNodes, dispatchSizeOrCount = null ) {
  39347. if ( this._isDeviceLost === true ) return;
  39348. if ( this._initialized === false ) {
  39349. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  39350. return this.computeAsync( computeNodes );
  39351. }
  39352. //
  39353. const nodeFrame = this._nodes.nodeFrame;
  39354. const previousRenderId = nodeFrame.renderId;
  39355. //
  39356. this.info.calls ++;
  39357. this.info.compute.calls ++;
  39358. this.info.compute.frameCalls ++;
  39359. nodeFrame.renderId = this.info.calls;
  39360. //
  39361. const backend = this.backend;
  39362. const pipelines = this._pipelines;
  39363. const bindings = this._bindings;
  39364. const nodes = this._nodes;
  39365. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  39366. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  39367. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  39368. }
  39369. backend.beginCompute( computeNodes );
  39370. for ( const computeNode of computeList ) {
  39371. // onInit
  39372. if ( pipelines.has( computeNode ) === false ) {
  39373. const dispose = () => {
  39374. computeNode.removeEventListener( 'dispose', dispose );
  39375. pipelines.delete( computeNode );
  39376. bindings.delete( computeNode );
  39377. nodes.delete( computeNode );
  39378. };
  39379. computeNode.addEventListener( 'dispose', dispose );
  39380. //
  39381. const onInitFn = computeNode.onInitFunction;
  39382. if ( onInitFn !== null ) {
  39383. onInitFn.call( computeNode, { renderer: this } );
  39384. }
  39385. }
  39386. nodes.updateForCompute( computeNode );
  39387. bindings.updateForCompute( computeNode );
  39388. const computeBindings = bindings.getForCompute( computeNode );
  39389. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  39390. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSizeOrCount );
  39391. }
  39392. backend.finishCompute( computeNodes );
  39393. //
  39394. nodeFrame.renderId = previousRenderId;
  39395. }
  39396. /**
  39397. * Execute a single or an array of compute nodes.
  39398. *
  39399. * @async
  39400. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  39401. * @param {Array<number>|number} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  39402. * @return {Promise} A Promise that resolve when the compute has finished.
  39403. */
  39404. async computeAsync( computeNodes, dispatchSizeOrCount = null ) {
  39405. if ( this._initialized === false ) await this.init();
  39406. this.compute( computeNodes, dispatchSizeOrCount );
  39407. }
  39408. /**
  39409. * Checks if the given feature is supported by the selected backend.
  39410. *
  39411. * @async
  39412. * @param {string} name - The feature's name.
  39413. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  39414. */
  39415. async hasFeatureAsync( name ) {
  39416. if ( this._initialized === false ) await this.init();
  39417. return this.backend.hasFeature( name );
  39418. }
  39419. async resolveTimestampsAsync( type = 'render' ) {
  39420. if ( this._initialized === false ) await this.init();
  39421. return this.backend.resolveTimestampsAsync( type );
  39422. }
  39423. /**
  39424. * Checks if the given feature is supported by the selected backend. If the
  39425. * renderer has not been initialized, this method always returns `false`.
  39426. *
  39427. * @param {string} name - The feature's name.
  39428. * @return {boolean} Whether the feature is supported or not.
  39429. */
  39430. hasFeature( name ) {
  39431. if ( this._initialized === false ) {
  39432. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  39433. return false;
  39434. }
  39435. return this.backend.hasFeature( name );
  39436. }
  39437. /**
  39438. * Returns `true` when the renderer has been initialized.
  39439. *
  39440. * @return {boolean} Whether the renderer has been initialized or not.
  39441. */
  39442. hasInitialized() {
  39443. return this._initialized;
  39444. }
  39445. /**
  39446. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  39447. * (which can cause noticeable lags due to decode and GPU upload overhead).
  39448. *
  39449. * @async
  39450. * @param {Texture} texture - The texture.
  39451. * @return {Promise} A Promise that resolves when the texture has been initialized.
  39452. */
  39453. async initTextureAsync( texture ) {
  39454. if ( this._initialized === false ) await this.init();
  39455. this._textures.updateTexture( texture );
  39456. }
  39457. /**
  39458. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  39459. * (which can cause noticeable lags due to decode and GPU upload overhead).
  39460. *
  39461. * This method can only be used if the renderer has been initialized.
  39462. *
  39463. * @param {Texture} texture - The texture.
  39464. */
  39465. initTexture( texture ) {
  39466. if ( this._initialized === false ) {
  39467. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  39468. }
  39469. this._textures.updateTexture( texture );
  39470. }
  39471. /**
  39472. * Copies the current bound framebuffer into the given texture.
  39473. *
  39474. * @param {FramebufferTexture} framebufferTexture - The texture.
  39475. * @param {?Vector2|Vector4} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  39476. */
  39477. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  39478. if ( rectangle !== null ) {
  39479. if ( rectangle.isVector2 ) {
  39480. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  39481. } else if ( rectangle.isVector4 ) {
  39482. rectangle = _vector4.copy( rectangle ).floor();
  39483. } else {
  39484. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  39485. return;
  39486. }
  39487. } else {
  39488. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  39489. }
  39490. //
  39491. let renderContext = this._currentRenderContext;
  39492. let renderTarget;
  39493. if ( renderContext !== null ) {
  39494. renderTarget = renderContext.renderTarget;
  39495. } else {
  39496. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  39497. if ( renderTarget !== null ) {
  39498. this._textures.updateRenderTarget( renderTarget );
  39499. renderContext = this._textures.get( renderTarget );
  39500. }
  39501. }
  39502. //
  39503. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  39504. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  39505. }
  39506. /**
  39507. * Copies data of the given source texture into a destination texture.
  39508. *
  39509. * @param {Texture} srcTexture - The source texture.
  39510. * @param {Texture} dstTexture - The destination texture.
  39511. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  39512. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  39513. * @param {number} [srcLevel=0] - The source mip level to copy from.
  39514. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  39515. */
  39516. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  39517. this._textures.updateTexture( srcTexture );
  39518. this._textures.updateTexture( dstTexture );
  39519. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  39520. }
  39521. /**
  39522. * Reads pixel data from the given render target.
  39523. *
  39524. * @async
  39525. * @param {RenderTarget} renderTarget - The render target to read from.
  39526. * @param {number} x - The `x` coordinate of the copy region's origin.
  39527. * @param {number} y - The `y` coordinate of the copy region's origin.
  39528. * @param {number} width - The width of the copy region.
  39529. * @param {number} height - The height of the copy region.
  39530. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  39531. * @param {number} [faceIndex=0] - The active cube face index.
  39532. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  39533. */
  39534. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  39535. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  39536. }
  39537. /**
  39538. * Analyzes the given 3D object's hierarchy and builds render lists from the
  39539. * processed hierarchy.
  39540. *
  39541. * @param {Object3D} object - The 3D object to process (usually a scene).
  39542. * @param {Camera} camera - The camera the object is rendered with.
  39543. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  39544. * @param {RenderList} renderList - The current render list.
  39545. * @param {ClippingContext} clippingContext - The current clipping context.
  39546. */
  39547. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  39548. if ( object.visible === false ) return;
  39549. const visible = object.layers.test( camera.layers );
  39550. if ( visible ) {
  39551. if ( object.isGroup ) {
  39552. groupOrder = object.renderOrder;
  39553. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  39554. } else if ( object.isLOD ) {
  39555. if ( object.autoUpdate === true ) object.update( camera );
  39556. } else if ( object.isLight ) {
  39557. renderList.pushLight( object );
  39558. } else if ( object.isSprite ) {
  39559. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  39560. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  39561. if ( this.sortObjects === true ) {
  39562. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  39563. }
  39564. const { geometry, material } = object;
  39565. if ( material.visible ) {
  39566. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  39567. }
  39568. }
  39569. } else if ( object.isLineLoop ) {
  39570. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  39571. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  39572. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  39573. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  39574. const { geometry, material } = object;
  39575. if ( this.sortObjects === true ) {
  39576. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  39577. _vector4
  39578. .copy( geometry.boundingSphere.center )
  39579. .applyMatrix4( object.matrixWorld )
  39580. .applyMatrix4( _projScreenMatrix );
  39581. }
  39582. if ( Array.isArray( material ) ) {
  39583. const groups = geometry.groups;
  39584. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  39585. const group = groups[ i ];
  39586. const groupMaterial = material[ group.materialIndex ];
  39587. if ( groupMaterial && groupMaterial.visible ) {
  39588. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  39589. }
  39590. }
  39591. } else if ( material.visible ) {
  39592. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  39593. }
  39594. }
  39595. }
  39596. }
  39597. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  39598. const baseRenderList = renderList;
  39599. // replace render list
  39600. renderList = this._renderLists.get( object, camera );
  39601. renderList.begin();
  39602. baseRenderList.pushBundle( {
  39603. bundleGroup: object,
  39604. camera,
  39605. renderList,
  39606. } );
  39607. renderList.finish();
  39608. }
  39609. const children = object.children;
  39610. for ( let i = 0, l = children.length; i < l; i ++ ) {
  39611. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  39612. }
  39613. }
  39614. /**
  39615. * Renders the given render bundles.
  39616. *
  39617. * @private
  39618. * @param {Array<Object>} bundles - Array with render bundle data.
  39619. * @param {Scene} sceneRef - The scene the render bundles belong to.
  39620. * @param {LightsNode} lightsNode - The current lights node.
  39621. */
  39622. _renderBundles( bundles, sceneRef, lightsNode ) {
  39623. for ( const bundle of bundles ) {
  39624. this._renderBundle( bundle, sceneRef, lightsNode );
  39625. }
  39626. }
  39627. /**
  39628. * Renders the transparent objects from the given render lists.
  39629. *
  39630. * @private
  39631. * @param {Array<Object>} renderList - The transparent render list.
  39632. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  39633. * @param {Camera} camera - The camera the render list should be rendered with.
  39634. * @param {Scene} scene - The scene the render list belongs to.
  39635. * @param {LightsNode} lightsNode - The current lights node.
  39636. */
  39637. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  39638. if ( doublePassList.length > 0 ) {
  39639. // render back side
  39640. for ( const { material } of doublePassList ) {
  39641. material.side = BackSide;
  39642. }
  39643. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  39644. // render front side
  39645. for ( const { material } of doublePassList ) {
  39646. material.side = FrontSide;
  39647. }
  39648. this._renderObjects( renderList, camera, scene, lightsNode );
  39649. // restore
  39650. for ( const { material } of doublePassList ) {
  39651. material.side = DoubleSide;
  39652. }
  39653. } else {
  39654. this._renderObjects( renderList, camera, scene, lightsNode );
  39655. }
  39656. }
  39657. /**
  39658. * Renders the objects from the given render list.
  39659. *
  39660. * @private
  39661. * @param {Array<Object>} renderList - The render list.
  39662. * @param {Camera} camera - The camera the render list should be rendered with.
  39663. * @param {Scene} scene - The scene the render list belongs to.
  39664. * @param {LightsNode} lightsNode - The current lights node.
  39665. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  39666. */
  39667. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  39668. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  39669. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  39670. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  39671. }
  39672. }
  39673. /**
  39674. * This method represents the default render object function that manages the render lifecycle
  39675. * of the object.
  39676. *
  39677. * @param {Object3D} object - The 3D object.
  39678. * @param {Scene} scene - The scene the 3D object belongs to.
  39679. * @param {Camera} camera - The camera the object should be rendered with.
  39680. * @param {BufferGeometry} geometry - The object's geometry.
  39681. * @param {Material} material - The object's material.
  39682. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  39683. * @param {LightsNode} lightsNode - The current lights node.
  39684. * @param {?ClippingContext} clippingContext - The clipping context.
  39685. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  39686. */
  39687. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  39688. let overridePositionNode;
  39689. let overrideColorNode;
  39690. let overrideDepthNode;
  39691. //
  39692. object.onBeforeRender( this, scene, camera, geometry, material, group );
  39693. //
  39694. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  39695. const overrideMaterial = scene.overrideMaterial;
  39696. if ( material.positionNode && material.positionNode.isNode ) {
  39697. overridePositionNode = overrideMaterial.positionNode;
  39698. overrideMaterial.positionNode = material.positionNode;
  39699. }
  39700. overrideMaterial.alphaTest = material.alphaTest;
  39701. overrideMaterial.alphaMap = material.alphaMap;
  39702. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  39703. if ( overrideMaterial.isShadowPassMaterial ) {
  39704. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  39705. if ( material.depthNode && material.depthNode.isNode ) {
  39706. overrideDepthNode = overrideMaterial.depthNode;
  39707. overrideMaterial.depthNode = material.depthNode;
  39708. }
  39709. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  39710. overrideColorNode = overrideMaterial.colorNode;
  39711. overrideMaterial.colorNode = material.castShadowNode;
  39712. }
  39713. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  39714. overridePositionNode = overrideMaterial.positionNode;
  39715. overrideMaterial.positionNode = material.castShadowPositionNode;
  39716. }
  39717. }
  39718. material = overrideMaterial;
  39719. }
  39720. //
  39721. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  39722. material.side = BackSide;
  39723. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  39724. material.side = FrontSide;
  39725. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  39726. material.side = DoubleSide;
  39727. } else {
  39728. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  39729. }
  39730. //
  39731. if ( overridePositionNode !== undefined ) {
  39732. scene.overrideMaterial.positionNode = overridePositionNode;
  39733. }
  39734. if ( overrideDepthNode !== undefined ) {
  39735. scene.overrideMaterial.depthNode = overrideDepthNode;
  39736. }
  39737. if ( overrideColorNode !== undefined ) {
  39738. scene.overrideMaterial.colorNode = overrideColorNode;
  39739. }
  39740. //
  39741. object.onAfterRender( this, scene, camera, geometry, material, group );
  39742. }
  39743. /**
  39744. * This method represents the default `_handleObjectFunction` implementation which creates
  39745. * a render object from the given data and performs the draw command with the selected backend.
  39746. *
  39747. * @private
  39748. * @param {Object3D} object - The 3D object.
  39749. * @param {Material} material - The object's material.
  39750. * @param {Scene} scene - The scene the 3D object belongs to.
  39751. * @param {Camera} camera - The camera the object should be rendered with.
  39752. * @param {LightsNode} lightsNode - The current lights node.
  39753. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  39754. * @param {ClippingContext} clippingContext - The clipping context.
  39755. * @param {string} [passId] - An optional ID for identifying the pass.
  39756. */
  39757. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  39758. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  39759. renderObject.drawRange = object.geometry.drawRange;
  39760. renderObject.group = group;
  39761. //
  39762. const needsRefresh = this._nodes.needsRefresh( renderObject );
  39763. if ( needsRefresh ) {
  39764. this._nodes.updateBefore( renderObject );
  39765. this._geometries.updateForRender( renderObject );
  39766. this._nodes.updateForRender( renderObject );
  39767. this._bindings.updateForRender( renderObject );
  39768. }
  39769. this._pipelines.updateForRender( renderObject );
  39770. //
  39771. if ( this._currentRenderBundle !== null ) {
  39772. const renderBundleData = this.backend.get( this._currentRenderBundle );
  39773. renderBundleData.renderObjects.push( renderObject );
  39774. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  39775. }
  39776. this.backend.draw( renderObject, this.info );
  39777. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  39778. }
  39779. /**
  39780. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  39781. * Used in `compileAsync()`.
  39782. *
  39783. * @private
  39784. * @param {Object3D} object - The 3D object.
  39785. * @param {Material} material - The object's material.
  39786. * @param {Scene} scene - The scene the 3D object belongs to.
  39787. * @param {Camera} camera - The camera the object should be rendered with.
  39788. * @param {LightsNode} lightsNode - The current lights node.
  39789. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  39790. * @param {ClippingContext} clippingContext - The clipping context.
  39791. * @param {string} [passId] - An optional ID for identifying the pass.
  39792. */
  39793. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  39794. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  39795. renderObject.drawRange = object.geometry.drawRange;
  39796. renderObject.group = group;
  39797. //
  39798. this._nodes.updateBefore( renderObject );
  39799. this._geometries.updateForRender( renderObject );
  39800. this._nodes.updateForRender( renderObject );
  39801. this._bindings.updateForRender( renderObject );
  39802. this._pipelines.getForRender( renderObject, this._compilationPromises );
  39803. this._nodes.updateAfter( renderObject );
  39804. }
  39805. /**
  39806. * Alias for `compileAsync()`.
  39807. *
  39808. * @method
  39809. * @param {Object3D} scene - The scene or 3D object to precompile.
  39810. * @param {Camera} camera - The camera that is used to render the scene.
  39811. * @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.
  39812. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  39813. */
  39814. get compile() {
  39815. return this.compileAsync;
  39816. }
  39817. }
  39818. /**
  39819. * A binding represents the connection between a resource (like a texture, sampler
  39820. * or uniform buffer) and the resource definition in a shader stage.
  39821. *
  39822. * This module is an abstract base class for all concrete bindings types.
  39823. *
  39824. * @abstract
  39825. * @private
  39826. */
  39827. class Binding {
  39828. /**
  39829. * Constructs a new binding.
  39830. *
  39831. * @param {string} [name=''] - The binding's name.
  39832. */
  39833. constructor( name = '' ) {
  39834. /**
  39835. * The binding's name.
  39836. *
  39837. * @type {string}
  39838. */
  39839. this.name = name;
  39840. /**
  39841. * A bitmask that defines in what shader stages the
  39842. * binding's resource is accessible.
  39843. *
  39844. * @type {number}
  39845. */
  39846. this.visibility = 0;
  39847. }
  39848. /**
  39849. * Makes sure binding's resource is visible for the given shader stage.
  39850. *
  39851. * @param {number} visibility - The shader stage.
  39852. */
  39853. setVisibility( visibility ) {
  39854. this.visibility |= visibility;
  39855. }
  39856. /**
  39857. * Clones the binding.
  39858. *
  39859. * @return {Binding} The cloned binding.
  39860. */
  39861. clone() {
  39862. return Object.assign( new this.constructor(), this );
  39863. }
  39864. }
  39865. /**
  39866. * This function is usually called with the length in bytes of an array buffer.
  39867. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  39868. *
  39869. * @function
  39870. * @param {number} floatLength - The buffer length.
  39871. * @return {number} The padded length.
  39872. */
  39873. function getFloatLength( floatLength ) {
  39874. // ensure chunk size alignment (STD140 layout)
  39875. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  39876. }
  39877. /**
  39878. * Represents a buffer binding type.
  39879. *
  39880. * @private
  39881. * @abstract
  39882. * @augments Binding
  39883. */
  39884. class Buffer extends Binding {
  39885. /**
  39886. * Constructs a new buffer.
  39887. *
  39888. * @param {string} name - The buffer's name.
  39889. * @param {TypedArray} [buffer=null] - The buffer.
  39890. */
  39891. constructor( name, buffer = null ) {
  39892. super( name );
  39893. /**
  39894. * This flag can be used for type testing.
  39895. *
  39896. * @type {boolean}
  39897. * @readonly
  39898. * @default true
  39899. */
  39900. this.isBuffer = true;
  39901. /**
  39902. * The bytes per element.
  39903. *
  39904. * @type {number}
  39905. */
  39906. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  39907. /**
  39908. * A reference to the internal buffer.
  39909. *
  39910. * @private
  39911. * @type {TypedArray}
  39912. */
  39913. this._buffer = buffer;
  39914. }
  39915. /**
  39916. * The buffer's byte length.
  39917. *
  39918. * @type {number}
  39919. * @readonly
  39920. */
  39921. get byteLength() {
  39922. return getFloatLength( this._buffer.byteLength );
  39923. }
  39924. /**
  39925. * A reference to the internal buffer.
  39926. *
  39927. * @type {Float32Array}
  39928. * @readonly
  39929. */
  39930. get buffer() {
  39931. return this._buffer;
  39932. }
  39933. /**
  39934. * Updates the binding.
  39935. *
  39936. * @return {boolean} Whether the buffer has been updated and must be
  39937. * uploaded to the GPU.
  39938. */
  39939. update() {
  39940. return true;
  39941. }
  39942. }
  39943. /**
  39944. * Represents a uniform buffer binding type.
  39945. *
  39946. * @private
  39947. * @augments Buffer
  39948. */
  39949. class UniformBuffer extends Buffer {
  39950. /**
  39951. * Constructs a new uniform buffer.
  39952. *
  39953. * @param {string} name - The buffer's name.
  39954. * @param {TypedArray} [buffer=null] - The buffer.
  39955. */
  39956. constructor( name, buffer = null ) {
  39957. super( name, buffer );
  39958. /**
  39959. * This flag can be used for type testing.
  39960. *
  39961. * @type {boolean}
  39962. * @readonly
  39963. * @default true
  39964. */
  39965. this.isUniformBuffer = true;
  39966. }
  39967. }
  39968. let _id$4 = 0;
  39969. /**
  39970. * A special form of uniform buffer binding type.
  39971. * It's buffer value is managed by a node object.
  39972. *
  39973. * @private
  39974. * @augments UniformBuffer
  39975. */
  39976. class NodeUniformBuffer extends UniformBuffer {
  39977. /**
  39978. * Constructs a new node-based uniform buffer.
  39979. *
  39980. * @param {BufferNode} nodeUniform - The uniform buffer node.
  39981. * @param {UniformGroupNode} groupNode - The uniform group node.
  39982. */
  39983. constructor( nodeUniform, groupNode ) {
  39984. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  39985. /**
  39986. * The uniform buffer node.
  39987. *
  39988. * @type {BufferNode}
  39989. */
  39990. this.nodeUniform = nodeUniform;
  39991. /**
  39992. * The uniform group node.
  39993. *
  39994. * @type {UniformGroupNode}
  39995. */
  39996. this.groupNode = groupNode;
  39997. }
  39998. /**
  39999. * The uniform buffer.
  40000. *
  40001. * @type {Float32Array}
  40002. */
  40003. get buffer() {
  40004. return this.nodeUniform.value;
  40005. }
  40006. }
  40007. /**
  40008. * This class represents a uniform buffer binding but with
  40009. * an API that allows to maintain individual uniform objects.
  40010. *
  40011. * @private
  40012. * @augments UniformBuffer
  40013. */
  40014. class UniformsGroup extends UniformBuffer {
  40015. /**
  40016. * Constructs a new uniforms group.
  40017. *
  40018. * @param {string} name - The group's name.
  40019. */
  40020. constructor( name ) {
  40021. super( name );
  40022. /**
  40023. * This flag can be used for type testing.
  40024. *
  40025. * @type {boolean}
  40026. * @readonly
  40027. * @default true
  40028. */
  40029. this.isUniformsGroup = true;
  40030. /**
  40031. * An array with the raw uniform values.
  40032. *
  40033. * @private
  40034. * @type {?Array<number>}
  40035. * @default null
  40036. */
  40037. this._values = null;
  40038. /**
  40039. * An array of uniform objects.
  40040. *
  40041. * The order of uniforms in this array must match the order of uniforms in the shader.
  40042. *
  40043. * @type {Array<Uniform>}
  40044. */
  40045. this.uniforms = [];
  40046. }
  40047. /**
  40048. * Adds a uniform to this group.
  40049. *
  40050. * @param {Uniform} uniform - The uniform to add.
  40051. * @return {UniformsGroup} A reference to this group.
  40052. */
  40053. addUniform( uniform ) {
  40054. this.uniforms.push( uniform );
  40055. return this;
  40056. }
  40057. /**
  40058. * Removes a uniform from this group.
  40059. *
  40060. * @param {Uniform} uniform - The uniform to remove.
  40061. * @return {UniformsGroup} A reference to this group.
  40062. */
  40063. removeUniform( uniform ) {
  40064. const index = this.uniforms.indexOf( uniform );
  40065. if ( index !== -1 ) {
  40066. this.uniforms.splice( index, 1 );
  40067. }
  40068. return this;
  40069. }
  40070. /**
  40071. * An array with the raw uniform values.
  40072. *
  40073. * @type {Array<number>}
  40074. */
  40075. get values() {
  40076. if ( this._values === null ) {
  40077. this._values = Array.from( this.buffer );
  40078. }
  40079. return this._values;
  40080. }
  40081. /**
  40082. * A Float32 array buffer with the uniform values.
  40083. *
  40084. * @type {Float32Array}
  40085. */
  40086. get buffer() {
  40087. let buffer = this._buffer;
  40088. if ( buffer === null ) {
  40089. const byteLength = this.byteLength;
  40090. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  40091. this._buffer = buffer;
  40092. }
  40093. return buffer;
  40094. }
  40095. /**
  40096. * The byte length of the buffer with correct buffer alignment.
  40097. *
  40098. * @type {number}
  40099. */
  40100. get byteLength() {
  40101. const bytesPerElement = this.bytesPerElement;
  40102. let offset = 0; // global buffer offset in bytes
  40103. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  40104. const uniform = this.uniforms[ i ];
  40105. const boundary = uniform.boundary;
  40106. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  40107. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  40108. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  40109. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  40110. offset += chunkPadding;
  40111. // Check for chunk overflow
  40112. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  40113. // Add padding to the end of the chunk
  40114. offset += ( GPU_CHUNK_BYTES - chunkStart );
  40115. }
  40116. uniform.offset = offset / bytesPerElement;
  40117. offset += itemSize;
  40118. }
  40119. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  40120. }
  40121. /**
  40122. * Updates this group by updating each uniform object of
  40123. * the internal uniform list. The uniform objects check if their
  40124. * values has actually changed so this method only returns
  40125. * `true` if there is a real value change.
  40126. *
  40127. * @return {boolean} Whether the uniforms have been updated and
  40128. * must be uploaded to the GPU.
  40129. */
  40130. update() {
  40131. let updated = false;
  40132. for ( const uniform of this.uniforms ) {
  40133. if ( this.updateByType( uniform ) === true ) {
  40134. updated = true;
  40135. }
  40136. }
  40137. return updated;
  40138. }
  40139. /**
  40140. * Updates a given uniform by calling an update method matching
  40141. * the uniforms type.
  40142. *
  40143. * @param {Uniform} uniform - The uniform to update.
  40144. * @return {boolean} Whether the uniform has been updated or not.
  40145. */
  40146. updateByType( uniform ) {
  40147. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  40148. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  40149. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  40150. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  40151. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  40152. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  40153. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  40154. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  40155. }
  40156. /**
  40157. * Updates a given Number uniform.
  40158. *
  40159. * @param {NumberUniform} uniform - The Number uniform.
  40160. * @return {boolean} Whether the uniform has been updated or not.
  40161. */
  40162. updateNumber( uniform ) {
  40163. let updated = false;
  40164. const a = this.values;
  40165. const v = uniform.getValue();
  40166. const offset = uniform.offset;
  40167. const type = uniform.getType();
  40168. if ( a[ offset ] !== v ) {
  40169. const b = this._getBufferForType( type );
  40170. b[ offset ] = a[ offset ] = v;
  40171. updated = true;
  40172. }
  40173. return updated;
  40174. }
  40175. /**
  40176. * Updates a given Vector2 uniform.
  40177. *
  40178. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  40179. * @return {boolean} Whether the uniform has been updated or not.
  40180. */
  40181. updateVector2( uniform ) {
  40182. let updated = false;
  40183. const a = this.values;
  40184. const v = uniform.getValue();
  40185. const offset = uniform.offset;
  40186. const type = uniform.getType();
  40187. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  40188. const b = this._getBufferForType( type );
  40189. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  40190. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  40191. updated = true;
  40192. }
  40193. return updated;
  40194. }
  40195. /**
  40196. * Updates a given Vector3 uniform.
  40197. *
  40198. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  40199. * @return {boolean} Whether the uniform has been updated or not.
  40200. */
  40201. updateVector3( uniform ) {
  40202. let updated = false;
  40203. const a = this.values;
  40204. const v = uniform.getValue();
  40205. const offset = uniform.offset;
  40206. const type = uniform.getType();
  40207. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  40208. const b = this._getBufferForType( type );
  40209. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  40210. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  40211. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  40212. updated = true;
  40213. }
  40214. return updated;
  40215. }
  40216. /**
  40217. * Updates a given Vector4 uniform.
  40218. *
  40219. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  40220. * @return {boolean} Whether the uniform has been updated or not.
  40221. */
  40222. updateVector4( uniform ) {
  40223. let updated = false;
  40224. const a = this.values;
  40225. const v = uniform.getValue();
  40226. const offset = uniform.offset;
  40227. const type = uniform.getType();
  40228. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  40229. const b = this._getBufferForType( type );
  40230. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  40231. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  40232. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  40233. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  40234. updated = true;
  40235. }
  40236. return updated;
  40237. }
  40238. /**
  40239. * Updates a given Color uniform.
  40240. *
  40241. * @param {ColorUniform} uniform - The Color uniform.
  40242. * @return {boolean} Whether the uniform has been updated or not.
  40243. */
  40244. updateColor( uniform ) {
  40245. let updated = false;
  40246. const a = this.values;
  40247. const c = uniform.getValue();
  40248. const offset = uniform.offset;
  40249. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  40250. const b = this.buffer;
  40251. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  40252. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  40253. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  40254. updated = true;
  40255. }
  40256. return updated;
  40257. }
  40258. /**
  40259. * Updates a given Matrix3 uniform.
  40260. *
  40261. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  40262. * @return {boolean} Whether the uniform has been updated or not.
  40263. */
  40264. updateMatrix3( uniform ) {
  40265. let updated = false;
  40266. const a = this.values;
  40267. const e = uniform.getValue().elements;
  40268. const offset = uniform.offset;
  40269. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  40270. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  40271. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  40272. const b = this.buffer;
  40273. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  40274. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  40275. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  40276. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  40277. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  40278. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  40279. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  40280. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  40281. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  40282. updated = true;
  40283. }
  40284. return updated;
  40285. }
  40286. /**
  40287. * Updates a given Matrix4 uniform.
  40288. *
  40289. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  40290. * @return {boolean} Whether the uniform has been updated or not.
  40291. */
  40292. updateMatrix4( uniform ) {
  40293. let updated = false;
  40294. const a = this.values;
  40295. const e = uniform.getValue().elements;
  40296. const offset = uniform.offset;
  40297. if ( arraysEqual( a, e, offset ) === false ) {
  40298. const b = this.buffer;
  40299. b.set( e, offset );
  40300. setArray( a, e, offset );
  40301. updated = true;
  40302. }
  40303. return updated;
  40304. }
  40305. /**
  40306. * Returns a typed array that matches the given data type.
  40307. *
  40308. * @param {string} type - The data type.
  40309. * @return {TypedArray} The typed array.
  40310. */
  40311. _getBufferForType( type ) {
  40312. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  40313. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  40314. return this.buffer;
  40315. }
  40316. }
  40317. /**
  40318. * Sets the values of the second array to the first array.
  40319. *
  40320. * @private
  40321. * @param {TypedArray} a - The first array.
  40322. * @param {TypedArray} b - The second array.
  40323. * @param {number} offset - An index offset for the first array.
  40324. */
  40325. function setArray( a, b, offset ) {
  40326. for ( let i = 0, l = b.length; i < l; i ++ ) {
  40327. a[ offset + i ] = b[ i ];
  40328. }
  40329. }
  40330. /**
  40331. * Returns `true` if the given arrays are equal.
  40332. *
  40333. * @private
  40334. * @param {TypedArray} a - The first array.
  40335. * @param {TypedArray} b - The second array.
  40336. * @param {number} offset - An index offset for the first array.
  40337. * @return {boolean} Whether the given arrays are equal or not.
  40338. */
  40339. function arraysEqual( a, b, offset ) {
  40340. for ( let i = 0, l = b.length; i < l; i ++ ) {
  40341. if ( a[ offset + i ] !== b[ i ] ) return false;
  40342. }
  40343. return true;
  40344. }
  40345. let _id$3 = 0;
  40346. /**
  40347. * A special form of uniforms group that represents
  40348. * the individual uniforms as node-based uniforms.
  40349. *
  40350. * @private
  40351. * @augments UniformsGroup
  40352. */
  40353. class NodeUniformsGroup extends UniformsGroup {
  40354. /**
  40355. * Constructs a new node-based uniforms group.
  40356. *
  40357. * @param {string} name - The group's name.
  40358. * @param {UniformGroupNode} groupNode - The uniform group node.
  40359. */
  40360. constructor( name, groupNode ) {
  40361. super( name );
  40362. /**
  40363. * The group's ID.
  40364. *
  40365. * @type {number}
  40366. */
  40367. this.id = _id$3 ++;
  40368. /**
  40369. * The uniform group node.
  40370. *
  40371. * @type {UniformGroupNode}
  40372. */
  40373. this.groupNode = groupNode;
  40374. /**
  40375. * This flag can be used for type testing.
  40376. *
  40377. * @type {boolean}
  40378. * @readonly
  40379. * @default true
  40380. */
  40381. this.isNodeUniformsGroup = true;
  40382. }
  40383. }
  40384. /**
  40385. * Represents a sampler binding type.
  40386. *
  40387. * @private
  40388. * @augments Binding
  40389. */
  40390. class Sampler extends Binding {
  40391. /**
  40392. * Constructs a new sampler.
  40393. *
  40394. * @param {string} name - The samplers's name.
  40395. * @param {?Texture} texture - The texture this binding is referring to.
  40396. */
  40397. constructor( name, texture ) {
  40398. super( name );
  40399. /**
  40400. * This function is called when the texture is disposed.
  40401. * @type {function}
  40402. * @private
  40403. */
  40404. this._onDisposeTexture = () => {
  40405. this.texture = null;
  40406. };
  40407. /**
  40408. * The texture the sampler is referring to.
  40409. *
  40410. * @type {?Texture}
  40411. */
  40412. this.texture = texture;
  40413. /**
  40414. * The binding's version.
  40415. *
  40416. * @type {number}
  40417. */
  40418. this.version = texture ? texture.version : 0;
  40419. /**
  40420. * The binding's generation which is an additional version
  40421. * qualifier.
  40422. *
  40423. * @type {?number}
  40424. * @default null
  40425. */
  40426. this.generation = null;
  40427. /**
  40428. * This flag can be used for type testing.
  40429. *
  40430. * @type {boolean}
  40431. * @readonly
  40432. * @default true
  40433. */
  40434. this.isSampler = true;
  40435. }
  40436. /**
  40437. * Sets the texture of this sampler.
  40438. * @param {?Texture} value - The texture to set.
  40439. */
  40440. set texture( value ) {
  40441. if ( this._texture === value ) return;
  40442. if ( this._texture ) {
  40443. this._texture.removeEventListener( 'dispose', this._onDisposeTexture );
  40444. }
  40445. this._texture = value;
  40446. this.generation = null;
  40447. this.version = 0;
  40448. if ( this._texture ) {
  40449. this._texture.addEventListener( 'dispose', this._onDisposeTexture );
  40450. }
  40451. }
  40452. /**
  40453. * Gets the texture of this sampler.
  40454. * @return {?Texture} The texture.
  40455. */
  40456. get texture() {
  40457. return this._texture;
  40458. }
  40459. /**
  40460. * Updates the binding.
  40461. *
  40462. * @return {boolean} Whether the texture has been updated and must be
  40463. * uploaded to the GPU.
  40464. */
  40465. update() {
  40466. const { texture, version } = this;
  40467. if ( version !== texture.version ) {
  40468. this.version = texture.version;
  40469. return true;
  40470. }
  40471. return false;
  40472. }
  40473. }
  40474. let _id$2 = 0;
  40475. /**
  40476. * Represents a sampled texture binding type.
  40477. *
  40478. * @private
  40479. * @augments Binding
  40480. */
  40481. class SampledTexture extends Sampler {
  40482. /**
  40483. * Constructs a new sampled texture.
  40484. *
  40485. * @param {string} name - The sampled texture's name.
  40486. * @param {?Texture} texture - The texture this binding is referring to.
  40487. */
  40488. constructor( name, texture ) {
  40489. super( name, texture );
  40490. /**
  40491. * This identifier.
  40492. *
  40493. * @type {number}
  40494. */
  40495. this.id = _id$2 ++;
  40496. /**
  40497. * Whether the texture is a storage texture or not.
  40498. *
  40499. * @type {boolean}
  40500. * @default false
  40501. */
  40502. this.store = false;
  40503. /**
  40504. * This flag can be used for type testing.
  40505. *
  40506. * @type {boolean}
  40507. * @readonly
  40508. * @default true
  40509. */
  40510. this.isSampledTexture = true;
  40511. }
  40512. }
  40513. /**
  40514. * A special form of sampled texture binding type.
  40515. * It's texture value is managed by a node object.
  40516. *
  40517. * @private
  40518. * @augments SampledTexture
  40519. */
  40520. class NodeSampledTexture extends SampledTexture {
  40521. /**
  40522. * Constructs a new node-based sampled texture.
  40523. *
  40524. * @param {string} name - The textures's name.
  40525. * @param {TextureNode} textureNode - The texture node.
  40526. * @param {UniformGroupNode} groupNode - The uniform group node.
  40527. * @param {?string} [access=null] - The access type.
  40528. */
  40529. constructor( name, textureNode, groupNode, access = null ) {
  40530. super( name, textureNode ? textureNode.value : null );
  40531. /**
  40532. * The texture node.
  40533. *
  40534. * @type {TextureNode}
  40535. */
  40536. this.textureNode = textureNode;
  40537. /**
  40538. * The uniform group node.
  40539. *
  40540. * @type {UniformGroupNode}
  40541. */
  40542. this.groupNode = groupNode;
  40543. /**
  40544. * The access type.
  40545. *
  40546. * @type {?string}
  40547. * @default null
  40548. */
  40549. this.access = access;
  40550. }
  40551. /**
  40552. * Updates the binding.
  40553. *
  40554. * @return {boolean} Whether the texture has been updated and must be
  40555. * uploaded to the GPU.
  40556. */
  40557. update() {
  40558. const { textureNode } = this;
  40559. if ( this.texture !== textureNode.value ) {
  40560. this.texture = textureNode.value;
  40561. return true;
  40562. }
  40563. return super.update();
  40564. }
  40565. }
  40566. /**
  40567. * A special form of sampled cube texture binding type.
  40568. * It's texture value is managed by a node object.
  40569. *
  40570. * @private
  40571. * @augments NodeSampledTexture
  40572. */
  40573. class NodeSampledCubeTexture extends NodeSampledTexture {
  40574. /**
  40575. * Constructs a new node-based sampled cube texture.
  40576. *
  40577. * @param {string} name - The textures's name.
  40578. * @param {TextureNode} textureNode - The texture node.
  40579. * @param {UniformGroupNode} groupNode - The uniform group node.
  40580. * @param {?string} [access=null] - The access type.
  40581. */
  40582. constructor( name, textureNode, groupNode, access = null ) {
  40583. super( name, textureNode, groupNode, access );
  40584. /**
  40585. * This flag can be used for type testing.
  40586. *
  40587. * @type {boolean}
  40588. * @readonly
  40589. * @default true
  40590. */
  40591. this.isSampledCubeTexture = true;
  40592. }
  40593. }
  40594. /**
  40595. * A special form of sampled 3D texture binding type.
  40596. * It's texture value is managed by a node object.
  40597. *
  40598. * @private
  40599. * @augments NodeSampledTexture
  40600. */
  40601. class NodeSampledTexture3D extends NodeSampledTexture {
  40602. /**
  40603. * Constructs a new node-based sampled 3D texture.
  40604. *
  40605. * @param {string} name - The textures's name.
  40606. * @param {TextureNode} textureNode - The texture node.
  40607. * @param {UniformGroupNode} groupNode - The uniform group node.
  40608. * @param {?string} [access=null] - The access type.
  40609. */
  40610. constructor( name, textureNode, groupNode, access = null ) {
  40611. super( name, textureNode, groupNode, access );
  40612. /**
  40613. * This flag can be used for type testing.
  40614. *
  40615. * @type {boolean}
  40616. * @readonly
  40617. * @default true
  40618. */
  40619. this.isSampledTexture3D = true;
  40620. }
  40621. }
  40622. const glslMethods = {
  40623. textureDimensions: 'textureSize',
  40624. equals: 'equal'
  40625. };
  40626. const precisionLib = {
  40627. low: 'lowp',
  40628. medium: 'mediump',
  40629. high: 'highp'
  40630. };
  40631. const supports$1 = {
  40632. swizzleAssign: true,
  40633. storageBuffer: false
  40634. };
  40635. const interpolationTypeMap = {
  40636. perspective: 'smooth',
  40637. linear: 'noperspective'
  40638. };
  40639. const interpolationModeMap = {
  40640. 'centroid': 'centroid'
  40641. };
  40642. const defaultPrecisions = `
  40643. precision highp float;
  40644. precision highp int;
  40645. precision highp sampler2D;
  40646. precision highp sampler3D;
  40647. precision highp samplerCube;
  40648. precision highp sampler2DArray;
  40649. precision highp usampler2D;
  40650. precision highp usampler3D;
  40651. precision highp usamplerCube;
  40652. precision highp usampler2DArray;
  40653. precision highp isampler2D;
  40654. precision highp isampler3D;
  40655. precision highp isamplerCube;
  40656. precision highp isampler2DArray;
  40657. precision lowp sampler2DShadow;
  40658. precision lowp sampler2DArrayShadow;
  40659. precision lowp samplerCubeShadow;
  40660. `;
  40661. /**
  40662. * A node builder targeting GLSL.
  40663. *
  40664. * This module generates GLSL shader code from node materials and also
  40665. * generates the respective bindings and vertex buffer definitions. These
  40666. * data are later used by the renderer to create render and compute pipelines
  40667. * for render objects.
  40668. *
  40669. * @augments NodeBuilder
  40670. */
  40671. class GLSLNodeBuilder extends NodeBuilder {
  40672. /**
  40673. * Constructs a new GLSL node builder renderer.
  40674. *
  40675. * @param {Object3D} object - The 3D object.
  40676. * @param {Renderer} renderer - The renderer.
  40677. */
  40678. constructor( object, renderer ) {
  40679. super( object, renderer, new GLSLNodeParser() );
  40680. /**
  40681. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  40682. * another dictionary which manages UBOs per group ('render','frame','object').
  40683. *
  40684. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  40685. */
  40686. this.uniformGroups = {};
  40687. /**
  40688. * An array that holds objects defining the varying and attribute data in
  40689. * context of Transform Feedback.
  40690. *
  40691. * @type {Array<Object<string,AttributeNode|string>>}
  40692. */
  40693. this.transforms = [];
  40694. /**
  40695. * A dictionary that holds for each shader stage a Map of used extensions.
  40696. *
  40697. * @type {Object<string,Map<string,Object>>}
  40698. */
  40699. this.extensions = {};
  40700. /**
  40701. * A dictionary that holds for each shader stage an Array of used builtins.
  40702. *
  40703. * @type {Object<string,Array<string>>}
  40704. */
  40705. this.builtins = { vertex: [], fragment: [], compute: [] };
  40706. }
  40707. /**
  40708. * Checks if the given texture requires a manual conversion to the working color space.
  40709. *
  40710. * @param {Texture} texture - The texture to check.
  40711. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  40712. */
  40713. needsToWorkingColorSpace( texture ) {
  40714. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  40715. }
  40716. /**
  40717. * Returns the native shader method name for a given generic name.
  40718. *
  40719. * @param {string} method - The method name to resolve.
  40720. * @return {string} The resolved GLSL method name.
  40721. */
  40722. getMethod( method ) {
  40723. return glslMethods[ method ] || method;
  40724. }
  40725. /**
  40726. * Returns the native snippet for a ternary operation.
  40727. *
  40728. * @param {string} condSnippet - The condition determining which expression gets resolved.
  40729. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  40730. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  40731. * @return {string} The resolved method name.
  40732. */
  40733. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  40734. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  40735. }
  40736. /**
  40737. * Returns the output struct name. Not relevant for GLSL.
  40738. *
  40739. * @return {string}
  40740. */
  40741. getOutputStructName() {
  40742. return '';
  40743. }
  40744. /**
  40745. * Builds the given shader node.
  40746. *
  40747. * @param {ShaderNodeInternal} shaderNode - The shader node.
  40748. * @return {string} The GLSL function code.
  40749. */
  40750. buildFunctionCode( shaderNode ) {
  40751. const layout = shaderNode.layout;
  40752. const flowData = this.flowShaderNode( shaderNode );
  40753. const parameters = [];
  40754. for ( const input of layout.inputs ) {
  40755. parameters.push( this.getType( input.type ) + ' ' + input.name );
  40756. }
  40757. //
  40758. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  40759. ${ flowData.vars }
  40760. ${ flowData.code }
  40761. return ${ flowData.result };
  40762. }`;
  40763. //
  40764. return code;
  40765. }
  40766. /**
  40767. * Setups the Pixel Buffer Object (PBO) for the given storage
  40768. * buffer node.
  40769. *
  40770. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  40771. */
  40772. setupPBO( storageBufferNode ) {
  40773. const attribute = storageBufferNode.value;
  40774. if ( attribute.pbo === undefined ) {
  40775. const originalArray = attribute.array;
  40776. const numElements = attribute.count * attribute.itemSize;
  40777. const { itemSize } = attribute;
  40778. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  40779. let format = isInteger ? RedIntegerFormat : RedFormat;
  40780. if ( itemSize === 2 ) {
  40781. format = isInteger ? RGIntegerFormat : RGFormat;
  40782. } else if ( itemSize === 3 ) {
  40783. format = isInteger ? RGBIntegerFormat : RGBFormat;
  40784. } else if ( itemSize === 4 ) {
  40785. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  40786. }
  40787. const typeMap = {
  40788. Float32Array: FloatType,
  40789. Uint8Array: UnsignedByteType,
  40790. Uint16Array: UnsignedShortType,
  40791. Uint32Array: UnsignedIntType,
  40792. Int8Array: ByteType,
  40793. Int16Array: ShortType,
  40794. Int32Array: IntType,
  40795. Uint8ClampedArray: UnsignedByteType,
  40796. };
  40797. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  40798. let height = Math.ceil( ( numElements / itemSize ) / width );
  40799. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  40800. const newSize = width * height * itemSize;
  40801. const newArray = new originalArray.constructor( newSize );
  40802. newArray.set( originalArray, 0 );
  40803. attribute.array = newArray;
  40804. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  40805. pboTexture.needsUpdate = true;
  40806. pboTexture.isPBOTexture = true;
  40807. const pbo = new TextureNode( pboTexture, null, null );
  40808. pbo.setPrecision( 'high' );
  40809. attribute.pboNode = pbo;
  40810. attribute.pbo = pbo.value;
  40811. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  40812. }
  40813. }
  40814. /**
  40815. * Returns a GLSL snippet that represents the property name of the given node.
  40816. *
  40817. * @param {Node} node - The node.
  40818. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  40819. * @return {string} The property name.
  40820. */
  40821. getPropertyName( node, shaderStage = this.shaderStage ) {
  40822. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  40823. return shaderStage.charAt( 0 ) + '_' + node.name;
  40824. }
  40825. return super.getPropertyName( node, shaderStage );
  40826. }
  40827. /**
  40828. * Setups the Pixel Buffer Object (PBO) for the given storage
  40829. * buffer node.
  40830. *
  40831. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  40832. * @return {string} The property name.
  40833. */
  40834. generatePBO( storageArrayElementNode ) {
  40835. const { node, indexNode } = storageArrayElementNode;
  40836. const attribute = node.value;
  40837. if ( this.renderer.backend.has( attribute ) ) {
  40838. const attributeData = this.renderer.backend.get( attribute );
  40839. attributeData.pbo = attribute.pbo;
  40840. }
  40841. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  40842. const textureName = this.getPropertyName( nodeUniform );
  40843. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  40844. const indexSnippet = indexNode.build( this, 'uint' );
  40845. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  40846. let propertyName = elementNodeData.propertyName;
  40847. if ( propertyName === undefined ) {
  40848. // property element
  40849. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  40850. propertyName = this.getPropertyName( nodeVar );
  40851. // property size
  40852. const bufferNodeData = this.getDataFromNode( node );
  40853. let propertySizeName = bufferNodeData.propertySizeName;
  40854. if ( propertySizeName === undefined ) {
  40855. propertySizeName = propertyName + 'Size';
  40856. this.getVarFromNode( node, propertySizeName, 'uint' );
  40857. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  40858. bufferNodeData.propertySizeName = propertySizeName;
  40859. }
  40860. //
  40861. const { itemSize } = attribute;
  40862. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  40863. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  40864. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  40865. //
  40866. let prefix = 'vec4';
  40867. if ( attribute.pbo.type === UnsignedIntType ) {
  40868. prefix = 'uvec4';
  40869. } else if ( attribute.pbo.type === IntType ) {
  40870. prefix = 'ivec4';
  40871. }
  40872. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  40873. elementNodeData.propertyName = propertyName;
  40874. }
  40875. return propertyName;
  40876. }
  40877. /**
  40878. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  40879. *
  40880. * @param {Texture} texture - The texture.
  40881. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40882. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40883. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  40884. * @param {string} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  40885. * @return {string} The GLSL snippet.
  40886. */
  40887. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  40888. if ( depthSnippet ) {
  40889. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  40890. } else {
  40891. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  40892. }
  40893. }
  40894. /**
  40895. * Generates the GLSL snippet for sampling/loading the given texture.
  40896. *
  40897. * @param {Texture} texture - The texture.
  40898. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40899. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40900. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  40901. * @return {string} The GLSL snippet.
  40902. */
  40903. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  40904. if ( texture.isDepthTexture ) {
  40905. if ( depthSnippet ) uvSnippet = `vec4( ${ uvSnippet }, ${ depthSnippet } )`;
  40906. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  40907. } else {
  40908. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  40909. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  40910. }
  40911. }
  40912. /**
  40913. * Generates the GLSL snippet when sampling textures with explicit mip level.
  40914. *
  40915. * @param {Texture} texture - The texture.
  40916. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40917. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40918. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  40919. * @return {string} The GLSL snippet.
  40920. */
  40921. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  40922. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  40923. }
  40924. /**
  40925. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  40926. *
  40927. * @param {Texture} texture - The texture.
  40928. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40929. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40930. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  40931. * @return {string} The GLSL snippet.
  40932. */
  40933. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  40934. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  40935. }
  40936. /**
  40937. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  40938. *
  40939. * @param {Texture} texture - The texture.
  40940. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40941. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40942. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  40943. * @return {string} The GLSL snippet.
  40944. */
  40945. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  40946. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  40947. }
  40948. /**
  40949. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  40950. * against a reference value.
  40951. *
  40952. * @param {Texture} texture - The texture.
  40953. * @param {string} textureProperty - The name of the texture uniform in the shader.
  40954. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  40955. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  40956. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  40957. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  40958. * @return {string} The GLSL snippet.
  40959. */
  40960. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  40961. if ( shaderStage === 'fragment' ) {
  40962. if ( depthSnippet ) {
  40963. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  40964. }
  40965. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  40966. } else {
  40967. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  40968. }
  40969. }
  40970. /**
  40971. * Returns the variables of the given shader stage as a GLSL string.
  40972. *
  40973. * @param {string} shaderStage - The shader stage.
  40974. * @return {string} The GLSL snippet that defines the variables.
  40975. */
  40976. getVars( shaderStage ) {
  40977. const snippets = [];
  40978. const vars = this.vars[ shaderStage ];
  40979. if ( vars !== undefined ) {
  40980. for ( const variable of vars ) {
  40981. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  40982. }
  40983. }
  40984. return snippets.join( '\n\t' );
  40985. }
  40986. /**
  40987. * Returns the uniforms of the given shader stage as a GLSL string.
  40988. *
  40989. * @param {string} shaderStage - The shader stage.
  40990. * @return {string} The GLSL snippet that defines the uniforms.
  40991. */
  40992. getUniforms( shaderStage ) {
  40993. const uniforms = this.uniforms[ shaderStage ];
  40994. const bindingSnippets = [];
  40995. const uniformGroups = {};
  40996. for ( const uniform of uniforms ) {
  40997. let snippet = null;
  40998. let group = false;
  40999. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  41000. const texture = uniform.node.value;
  41001. let typePrefix = '';
  41002. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  41003. if ( texture.type === UnsignedIntType ) {
  41004. typePrefix = 'u';
  41005. } else if ( texture.type === IntType ) {
  41006. typePrefix = 'i';
  41007. }
  41008. }
  41009. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  41010. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  41011. } else if ( texture.compareFunction ) {
  41012. if ( texture.isArrayTexture === true ) {
  41013. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  41014. } else {
  41015. snippet = `sampler2DShadow ${ uniform.name };`;
  41016. }
  41017. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  41018. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  41019. } else {
  41020. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  41021. }
  41022. } else if ( uniform.type === 'cubeTexture' ) {
  41023. snippet = `samplerCube ${ uniform.name };`;
  41024. } else if ( uniform.type === 'buffer' ) {
  41025. const bufferNode = uniform.node;
  41026. const bufferType = this.getType( bufferNode.bufferType );
  41027. const bufferCount = bufferNode.bufferCount;
  41028. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  41029. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  41030. } else {
  41031. const vectorType = this.getVectorType( uniform.type );
  41032. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  41033. group = true;
  41034. }
  41035. const precision = uniform.node.precision;
  41036. if ( precision !== null ) {
  41037. snippet = precisionLib[ precision ] + ' ' + snippet;
  41038. }
  41039. if ( group ) {
  41040. snippet = '\t' + snippet;
  41041. const groupName = uniform.groupNode.name;
  41042. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  41043. groupSnippets.push( snippet );
  41044. } else {
  41045. snippet = 'uniform ' + snippet;
  41046. bindingSnippets.push( snippet );
  41047. }
  41048. }
  41049. let output = '';
  41050. for ( const name in uniformGroups ) {
  41051. const groupSnippets = uniformGroups[ name ];
  41052. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  41053. }
  41054. output += bindingSnippets.join( '\n' );
  41055. return output;
  41056. }
  41057. /**
  41058. * Returns the type for a given buffer attribute.
  41059. *
  41060. * @param {BufferAttribute} attribute - The buffer attribute.
  41061. * @return {string} The type.
  41062. */
  41063. getTypeFromAttribute( attribute ) {
  41064. let nodeType = super.getTypeFromAttribute( attribute );
  41065. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  41066. let dataAttribute = attribute;
  41067. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  41068. const array = dataAttribute.array;
  41069. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  41070. nodeType = nodeType.slice( 1 );
  41071. }
  41072. }
  41073. return nodeType;
  41074. }
  41075. /**
  41076. * Returns the shader attributes of the given shader stage as a GLSL string.
  41077. *
  41078. * @param {string} shaderStage - The shader stage.
  41079. * @return {string} The GLSL snippet that defines the shader attributes.
  41080. */
  41081. getAttributes( shaderStage ) {
  41082. let snippet = '';
  41083. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  41084. const attributes = this.getAttributesArray();
  41085. let location = 0;
  41086. for ( const attribute of attributes ) {
  41087. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  41088. }
  41089. }
  41090. return snippet;
  41091. }
  41092. /**
  41093. * Returns the members of the given struct type node as a GLSL string.
  41094. *
  41095. * @param {StructTypeNode} struct - The struct type node.
  41096. * @return {string} The GLSL snippet that defines the struct members.
  41097. */
  41098. getStructMembers( struct ) {
  41099. const snippets = [];
  41100. for ( const member of struct.members ) {
  41101. snippets.push( `\t${ member.type } ${ member.name };` );
  41102. }
  41103. return snippets.join( '\n' );
  41104. }
  41105. /**
  41106. * Returns the structs of the given shader stage as a GLSL string.
  41107. *
  41108. * @param {string} shaderStage - The shader stage.
  41109. * @return {string} The GLSL snippet that defines the structs.
  41110. */
  41111. getStructs( shaderStage ) {
  41112. const snippets = [];
  41113. const structs = this.structs[ shaderStage ];
  41114. const outputSnippet = [];
  41115. for ( const struct of structs ) {
  41116. if ( struct.output ) {
  41117. for ( const member of struct.members ) {
  41118. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  41119. }
  41120. } else {
  41121. let snippet = 'struct ' + struct.name + ' {\n';
  41122. snippet += this.getStructMembers( struct );
  41123. snippet += '\n};\n';
  41124. snippets.push( snippet );
  41125. }
  41126. }
  41127. if ( outputSnippet.length === 0 ) {
  41128. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  41129. }
  41130. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  41131. }
  41132. /**
  41133. * Returns the varyings of the given shader stage as a GLSL string.
  41134. *
  41135. * @param {string} shaderStage - The shader stage.
  41136. * @return {string} The GLSL snippet that defines the varyings.
  41137. */
  41138. getVaryings( shaderStage ) {
  41139. let snippet = '';
  41140. const varyings = this.varyings;
  41141. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  41142. for ( const varying of varyings ) {
  41143. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  41144. const type = this.getType( varying.type );
  41145. if ( varying.needsInterpolation ) {
  41146. if ( varying.interpolationType ) {
  41147. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  41148. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  41149. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  41150. } else {
  41151. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  41152. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  41153. }
  41154. } else {
  41155. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  41156. }
  41157. }
  41158. } else if ( shaderStage === 'fragment' ) {
  41159. for ( const varying of varyings ) {
  41160. if ( varying.needsInterpolation ) {
  41161. const type = this.getType( varying.type );
  41162. if ( varying.interpolationType ) {
  41163. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  41164. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  41165. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  41166. } else {
  41167. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  41168. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  41169. }
  41170. }
  41171. }
  41172. }
  41173. for ( const builtin of this.builtins[ shaderStage ] ) {
  41174. snippet += `${builtin};\n`;
  41175. }
  41176. return snippet;
  41177. }
  41178. /**
  41179. * Returns the vertex index builtin.
  41180. *
  41181. * @return {string} The vertex index.
  41182. */
  41183. getVertexIndex() {
  41184. return 'uint( gl_VertexID )';
  41185. }
  41186. /**
  41187. * Returns the instance index builtin.
  41188. *
  41189. * @return {string} The instance index.
  41190. */
  41191. getInstanceIndex() {
  41192. return 'uint( gl_InstanceID )';
  41193. }
  41194. /**
  41195. * Returns the invocation local index builtin.
  41196. *
  41197. * @return {string} The invocation local index.
  41198. */
  41199. getInvocationLocalIndex() {
  41200. const workgroupSize = this.object.workgroupSize;
  41201. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  41202. return `uint( gl_InstanceID ) % ${size}u`;
  41203. }
  41204. /**
  41205. * Returns the draw index builtin.
  41206. *
  41207. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  41208. */
  41209. getDrawIndex() {
  41210. const extensions = this.renderer.backend.extensions;
  41211. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  41212. return 'uint( gl_DrawID )';
  41213. }
  41214. return null;
  41215. }
  41216. /**
  41217. * Returns the front facing builtin.
  41218. *
  41219. * @return {string} The front facing builtin.
  41220. */
  41221. getFrontFacing() {
  41222. return 'gl_FrontFacing';
  41223. }
  41224. /**
  41225. * Returns the frag coord builtin.
  41226. *
  41227. * @return {string} The frag coord builtin.
  41228. */
  41229. getFragCoord() {
  41230. return 'gl_FragCoord.xy';
  41231. }
  41232. /**
  41233. * Returns the frag depth builtin.
  41234. *
  41235. * @return {string} The frag depth builtin.
  41236. */
  41237. getFragDepth() {
  41238. return 'gl_FragDepth';
  41239. }
  41240. /**
  41241. * Enables the given extension.
  41242. *
  41243. * @param {string} name - The extension name.
  41244. * @param {string} behavior - The extension behavior.
  41245. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  41246. */
  41247. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  41248. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  41249. if ( map.has( name ) === false ) {
  41250. map.set( name, {
  41251. name,
  41252. behavior
  41253. } );
  41254. }
  41255. }
  41256. /**
  41257. * Returns the enabled extensions of the given shader stage as a GLSL string.
  41258. *
  41259. * @param {string} shaderStage - The shader stage.
  41260. * @return {string} The GLSL snippet that defines the enabled extensions.
  41261. */
  41262. getExtensions( shaderStage ) {
  41263. const snippets = [];
  41264. if ( shaderStage === 'vertex' ) {
  41265. const ext = this.renderer.backend.extensions;
  41266. const isBatchedMesh = this.object.isBatchedMesh;
  41267. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  41268. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  41269. }
  41270. }
  41271. const extensions = this.extensions[ shaderStage ];
  41272. if ( extensions !== undefined ) {
  41273. for ( const { name, behavior } of extensions.values() ) {
  41274. snippets.push( `#extension ${name} : ${behavior}` );
  41275. }
  41276. }
  41277. return snippets.join( '\n' );
  41278. }
  41279. /**
  41280. * Returns the clip distances builtin.
  41281. *
  41282. * @return {string} The clip distances builtin.
  41283. */
  41284. getClipDistance() {
  41285. return 'gl_ClipDistance';
  41286. }
  41287. /**
  41288. * Whether the requested feature is available or not.
  41289. *
  41290. * @param {string} name - The requested feature.
  41291. * @return {boolean} Whether the requested feature is supported or not.
  41292. */
  41293. isAvailable( name ) {
  41294. let result = supports$1[ name ];
  41295. if ( result === undefined ) {
  41296. let extensionName;
  41297. result = false;
  41298. switch ( name ) {
  41299. case 'float32Filterable':
  41300. extensionName = 'OES_texture_float_linear';
  41301. break;
  41302. case 'clipDistance':
  41303. extensionName = 'WEBGL_clip_cull_distance';
  41304. break;
  41305. }
  41306. if ( extensionName !== undefined ) {
  41307. const extensions = this.renderer.backend.extensions;
  41308. if ( extensions.has( extensionName ) ) {
  41309. extensions.get( extensionName );
  41310. result = true;
  41311. }
  41312. }
  41313. supports$1[ name ] = result;
  41314. }
  41315. return result;
  41316. }
  41317. /**
  41318. * Whether to flip texture data along its vertical axis or not.
  41319. *
  41320. * @return {boolean} Returns always `true` in context of GLSL.
  41321. */
  41322. isFlipY() {
  41323. return true;
  41324. }
  41325. /**
  41326. * Enables hardware clipping.
  41327. *
  41328. * @param {string} planeCount - The clipping plane count.
  41329. */
  41330. enableHardwareClipping( planeCount ) {
  41331. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  41332. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  41333. }
  41334. /**
  41335. * Enables multiview.
  41336. */
  41337. enableMultiview() {
  41338. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  41339. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  41340. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  41341. }
  41342. /**
  41343. * Registers a transform in context of Transform Feedback.
  41344. *
  41345. * @param {string} varyingName - The varying name.
  41346. * @param {AttributeNode} attributeNode - The attribute node.
  41347. */
  41348. registerTransform( varyingName, attributeNode ) {
  41349. this.transforms.push( { varyingName, attributeNode } );
  41350. }
  41351. /**
  41352. * Returns the transforms of the given shader stage as a GLSL string.
  41353. *
  41354. * @param {string} shaderStage - The shader stage.
  41355. * @return {string} The GLSL snippet that defines the transforms.
  41356. */
  41357. getTransforms( /* shaderStage */ ) {
  41358. const transforms = this.transforms;
  41359. let snippet = '';
  41360. for ( let i = 0; i < transforms.length; i ++ ) {
  41361. const transform = transforms[ i ];
  41362. const attributeName = this.getPropertyName( transform.attributeNode );
  41363. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  41364. }
  41365. return snippet;
  41366. }
  41367. /**
  41368. * Returns a GLSL struct based on the given name and variables.
  41369. *
  41370. * @private
  41371. * @param {string} name - The struct name.
  41372. * @param {string} vars - The struct variables.
  41373. * @return {string} The GLSL snippet representing a struct.
  41374. */
  41375. _getGLSLUniformStruct( name, vars ) {
  41376. return `
  41377. layout( std140 ) uniform ${name} {
  41378. ${vars}
  41379. };`;
  41380. }
  41381. /**
  41382. * Returns a GLSL vertex shader based on the given shader data.
  41383. *
  41384. * @private
  41385. * @param {Object} shaderData - The shader data.
  41386. * @return {string} The vertex shader.
  41387. */
  41388. _getGLSLVertexCode( shaderData ) {
  41389. return `#version 300 es
  41390. ${ this.getSignature() }
  41391. // extensions
  41392. ${shaderData.extensions}
  41393. // precision
  41394. ${ defaultPrecisions }
  41395. // uniforms
  41396. ${shaderData.uniforms}
  41397. // varyings
  41398. ${shaderData.varyings}
  41399. // attributes
  41400. ${shaderData.attributes}
  41401. // codes
  41402. ${shaderData.codes}
  41403. void main() {
  41404. // vars
  41405. ${shaderData.vars}
  41406. // transforms
  41407. ${shaderData.transforms}
  41408. // flow
  41409. ${shaderData.flow}
  41410. gl_PointSize = 1.0;
  41411. }
  41412. `;
  41413. }
  41414. /**
  41415. * Returns a GLSL fragment shader based on the given shader data.
  41416. *
  41417. * @private
  41418. * @param {Object} shaderData - The shader data.
  41419. * @return {string} The vertex shader.
  41420. */
  41421. _getGLSLFragmentCode( shaderData ) {
  41422. return `#version 300 es
  41423. ${ this.getSignature() }
  41424. // extensions
  41425. ${shaderData.extensions}
  41426. // precision
  41427. ${ defaultPrecisions }
  41428. // uniforms
  41429. ${shaderData.uniforms}
  41430. // varyings
  41431. ${shaderData.varyings}
  41432. // codes
  41433. ${shaderData.codes}
  41434. // structs
  41435. ${shaderData.structs}
  41436. void main() {
  41437. // vars
  41438. ${shaderData.vars}
  41439. // flow
  41440. ${shaderData.flow}
  41441. }
  41442. `;
  41443. }
  41444. /**
  41445. * Controls the code build of the shader stages.
  41446. */
  41447. buildCode() {
  41448. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  41449. this.sortBindingGroups();
  41450. for ( const shaderStage in shadersData ) {
  41451. let flow = '// code\n\n';
  41452. flow += this.flowCode[ shaderStage ];
  41453. const flowNodes = this.flowNodes[ shaderStage ];
  41454. const mainNode = flowNodes[ flowNodes.length - 1 ];
  41455. for ( const node of flowNodes ) {
  41456. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  41457. const slotName = node.name;
  41458. if ( slotName ) {
  41459. if ( flow.length > 0 ) flow += '\n';
  41460. flow += `\t// flow -> ${ slotName }\n\t`;
  41461. }
  41462. flow += `${ flowSlotData.code }\n\t`;
  41463. if ( node === mainNode && shaderStage !== 'compute' ) {
  41464. flow += '// result\n\t';
  41465. if ( shaderStage === 'vertex' ) {
  41466. flow += 'gl_Position = ';
  41467. flow += `${ flowSlotData.result };`;
  41468. } else if ( shaderStage === 'fragment' ) {
  41469. if ( ! node.outputNode.isOutputStructNode ) {
  41470. flow += 'fragColor = ';
  41471. flow += `${ flowSlotData.result };`;
  41472. }
  41473. }
  41474. }
  41475. }
  41476. const stageData = shadersData[ shaderStage ];
  41477. stageData.extensions = this.getExtensions( shaderStage );
  41478. stageData.uniforms = this.getUniforms( shaderStage );
  41479. stageData.attributes = this.getAttributes( shaderStage );
  41480. stageData.varyings = this.getVaryings( shaderStage );
  41481. stageData.vars = this.getVars( shaderStage );
  41482. stageData.structs = this.getStructs( shaderStage );
  41483. stageData.codes = this.getCodes( shaderStage );
  41484. stageData.transforms = this.getTransforms( shaderStage );
  41485. stageData.flow = flow;
  41486. }
  41487. if ( this.material !== null ) {
  41488. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  41489. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  41490. } else {
  41491. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  41492. }
  41493. }
  41494. /**
  41495. * This method is one of the more important ones since it's responsible
  41496. * for generating a matching binding instance for the given uniform node.
  41497. *
  41498. * These bindings are later used in the renderer to create bind groups
  41499. * and layouts.
  41500. *
  41501. * @param {UniformNode} node - The uniform node.
  41502. * @param {string} type - The node data type.
  41503. * @param {string} shaderStage - The shader stage.
  41504. * @param {?string} [name=null] - An optional uniform name.
  41505. * @return {NodeUniform} The node uniform object.
  41506. */
  41507. getUniformFromNode( node, type, shaderStage, name = null ) {
  41508. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  41509. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  41510. let uniformGPU = nodeData.uniformGPU;
  41511. if ( uniformGPU === undefined ) {
  41512. const group = node.groupNode;
  41513. const groupName = group.name;
  41514. const bindings = this.getBindGroupArray( groupName, shaderStage );
  41515. if ( type === 'texture' ) {
  41516. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  41517. bindings.push( uniformGPU );
  41518. } else if ( type === 'cubeTexture' ) {
  41519. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  41520. bindings.push( uniformGPU );
  41521. } else if ( type === 'texture3D' ) {
  41522. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  41523. bindings.push( uniformGPU );
  41524. } else if ( type === 'buffer' ) {
  41525. node.name = `NodeBuffer_${ node.id }`;
  41526. uniformNode.name = `buffer${ node.id }`;
  41527. const buffer = new NodeUniformBuffer( node, group );
  41528. buffer.name = node.name;
  41529. bindings.push( buffer );
  41530. uniformGPU = buffer;
  41531. } else {
  41532. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  41533. let uniformsGroup = uniformsStage[ groupName ];
  41534. if ( uniformsGroup === undefined ) {
  41535. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  41536. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  41537. uniformsStage[ groupName ] = uniformsGroup;
  41538. bindings.push( uniformsGroup );
  41539. }
  41540. uniformGPU = this.getNodeUniform( uniformNode, type );
  41541. uniformsGroup.addUniform( uniformGPU );
  41542. }
  41543. nodeData.uniformGPU = uniformGPU;
  41544. }
  41545. return uniformNode;
  41546. }
  41547. }
  41548. let _vector2 = null;
  41549. let _color4 = null;
  41550. /**
  41551. * Most of the rendering related logic is implemented in the
  41552. * {@link Renderer} module and related management components.
  41553. * Sometimes it is required though to execute commands which are
  41554. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  41555. * This abstract base class defines an interface that encapsulates
  41556. * all backend-related logic. Derived classes for each backend must
  41557. * implement the interface.
  41558. *
  41559. * @abstract
  41560. * @private
  41561. */
  41562. class Backend {
  41563. /**
  41564. * Constructs a new backend.
  41565. *
  41566. * @param {Object} parameters - An object holding parameters for the backend.
  41567. */
  41568. constructor( parameters = {} ) {
  41569. /**
  41570. * The parameters of the backend.
  41571. *
  41572. * @type {Object}
  41573. */
  41574. this.parameters = Object.assign( {}, parameters );
  41575. /**
  41576. * This weak map holds backend-specific data of objects
  41577. * like textures, attributes or render targets.
  41578. *
  41579. * @type {WeakMap}
  41580. */
  41581. this.data = new WeakMap();
  41582. /**
  41583. * A reference to the renderer.
  41584. *
  41585. * @type {?Renderer}
  41586. * @default null
  41587. */
  41588. this.renderer = null;
  41589. /**
  41590. * A reference to the canvas element the renderer is drawing to.
  41591. *
  41592. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  41593. * @default null
  41594. */
  41595. this.domElement = null;
  41596. /**
  41597. * A reference to the timestamp query pool.
  41598. *
  41599. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  41600. */
  41601. this.timestampQueryPool = {
  41602. 'render': null,
  41603. 'compute': null
  41604. };
  41605. /**
  41606. * Whether to track timestamps with a Timestamp Query API or not.
  41607. *
  41608. * @type {boolean}
  41609. * @default false
  41610. */
  41611. this.trackTimestamp = ( parameters.trackTimestamp === true );
  41612. }
  41613. /**
  41614. * Initializes the backend so it is ready for usage. Concrete backends
  41615. * are supposed to implement their rendering context creation and related
  41616. * operations in this method.
  41617. *
  41618. * @async
  41619. * @param {Renderer} renderer - The renderer.
  41620. * @return {Promise} A Promise that resolves when the backend has been initialized.
  41621. */
  41622. async init( renderer ) {
  41623. this.renderer = renderer;
  41624. }
  41625. /**
  41626. * The coordinate system of the backend.
  41627. *
  41628. * @abstract
  41629. * @type {number}
  41630. * @readonly
  41631. */
  41632. get coordinateSystem() {}
  41633. // render context
  41634. /**
  41635. * This method is executed at the beginning of a render call and
  41636. * can be used by the backend to prepare the state for upcoming
  41637. * draw calls.
  41638. *
  41639. * @abstract
  41640. * @param {RenderContext} renderContext - The render context.
  41641. */
  41642. beginRender( /*renderContext*/ ) {}
  41643. /**
  41644. * This method is executed at the end of a render call and
  41645. * can be used by the backend to finalize work after draw
  41646. * calls.
  41647. *
  41648. * @abstract
  41649. * @param {RenderContext} renderContext - The render context.
  41650. */
  41651. finishRender( /*renderContext*/ ) {}
  41652. /**
  41653. * This method is executed at the beginning of a compute call and
  41654. * can be used by the backend to prepare the state for upcoming
  41655. * compute tasks.
  41656. *
  41657. * @abstract
  41658. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  41659. */
  41660. beginCompute( /*computeGroup*/ ) {}
  41661. /**
  41662. * This method is executed at the end of a compute call and
  41663. * can be used by the backend to finalize work after compute
  41664. * tasks.
  41665. *
  41666. * @abstract
  41667. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  41668. */
  41669. finishCompute( /*computeGroup*/ ) {}
  41670. // render object
  41671. /**
  41672. * Executes a draw command for the given render object.
  41673. *
  41674. * @abstract
  41675. * @param {RenderObject} renderObject - The render object to draw.
  41676. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  41677. */
  41678. draw( /*renderObject, info*/ ) { }
  41679. // compute node
  41680. /**
  41681. * Executes a compute command for the given compute node.
  41682. *
  41683. * @abstract
  41684. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  41685. * @param {Node} computeNode - The compute node.
  41686. * @param {Array<BindGroup>} bindings - The bindings.
  41687. * @param {ComputePipeline} computePipeline - The compute pipeline.
  41688. */
  41689. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  41690. // program
  41691. /**
  41692. * Creates a shader program from the given programmable stage.
  41693. *
  41694. * @abstract
  41695. * @param {ProgrammableStage} program - The programmable stage.
  41696. */
  41697. createProgram( /*program*/ ) { }
  41698. /**
  41699. * Destroys the shader program of the given programmable stage.
  41700. *
  41701. * @abstract
  41702. * @param {ProgrammableStage} program - The programmable stage.
  41703. */
  41704. destroyProgram( /*program*/ ) { }
  41705. // bindings
  41706. /**
  41707. * Creates bindings from the given bind group definition.
  41708. *
  41709. * @abstract
  41710. * @param {BindGroup} bindGroup - The bind group.
  41711. * @param {Array<BindGroup>} bindings - Array of bind groups.
  41712. * @param {number} cacheIndex - The cache index.
  41713. * @param {number} version - The version.
  41714. */
  41715. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  41716. /**
  41717. * Updates the given bind group definition.
  41718. *
  41719. * @abstract
  41720. * @param {BindGroup} bindGroup - The bind group.
  41721. * @param {Array<BindGroup>} bindings - Array of bind groups.
  41722. * @param {number} cacheIndex - The cache index.
  41723. * @param {number} version - The version.
  41724. */
  41725. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  41726. /**
  41727. * Updates a buffer binding.
  41728. *
  41729. * @abstract
  41730. * @param {Buffer} binding - The buffer binding to update.
  41731. */
  41732. updateBinding( /*binding*/ ) { }
  41733. // pipeline
  41734. /**
  41735. * Creates a render pipeline for the given render object.
  41736. *
  41737. * @abstract
  41738. * @param {RenderObject} renderObject - The render object.
  41739. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  41740. */
  41741. createRenderPipeline( /*renderObject, promises*/ ) { }
  41742. /**
  41743. * Creates a compute pipeline for the given compute node.
  41744. *
  41745. * @abstract
  41746. * @param {ComputePipeline} computePipeline - The compute pipeline.
  41747. * @param {Array<BindGroup>} bindings - The bindings.
  41748. */
  41749. createComputePipeline( /*computePipeline, bindings*/ ) { }
  41750. // cache key
  41751. /**
  41752. * Returns `true` if the render pipeline requires an update.
  41753. *
  41754. * @abstract
  41755. * @param {RenderObject} renderObject - The render object.
  41756. * @return {boolean} Whether the render pipeline requires an update or not.
  41757. */
  41758. needsRenderUpdate( /*renderObject*/ ) { }
  41759. /**
  41760. * Returns a cache key that is used to identify render pipelines.
  41761. *
  41762. * @abstract
  41763. * @param {RenderObject} renderObject - The render object.
  41764. * @return {string} The cache key.
  41765. */
  41766. getRenderCacheKey( /*renderObject*/ ) { }
  41767. // node builder
  41768. /**
  41769. * Returns a node builder for the given render object.
  41770. *
  41771. * @abstract
  41772. * @param {RenderObject} renderObject - The render object.
  41773. * @param {Renderer} renderer - The renderer.
  41774. * @return {NodeBuilder} The node builder.
  41775. */
  41776. createNodeBuilder( /*renderObject, renderer*/ ) { }
  41777. // textures
  41778. /**
  41779. * Creates a GPU sampler for the given texture.
  41780. *
  41781. * @abstract
  41782. * @param {Texture} texture - The texture to create the sampler for.
  41783. */
  41784. createSampler( /*texture*/ ) { }
  41785. /**
  41786. * Destroys the GPU sampler for the given texture.
  41787. *
  41788. * @abstract
  41789. * @param {Texture} texture - The texture to destroy the sampler for.
  41790. */
  41791. destroySampler( /*texture*/ ) {}
  41792. /**
  41793. * Creates a default texture for the given texture that can be used
  41794. * as a placeholder until the actual texture is ready for usage.
  41795. *
  41796. * @abstract
  41797. * @param {Texture} texture - The texture to create a default texture for.
  41798. */
  41799. createDefaultTexture( /*texture*/ ) { }
  41800. /**
  41801. * Defines a texture on the GPU for the given texture object.
  41802. *
  41803. * @abstract
  41804. * @param {Texture} texture - The texture.
  41805. * @param {Object} [options={}] - Optional configuration parameter.
  41806. */
  41807. createTexture( /*texture, options={}*/ ) { }
  41808. /**
  41809. * Uploads the updated texture data to the GPU.
  41810. *
  41811. * @abstract
  41812. * @param {Texture} texture - The texture.
  41813. * @param {Object} [options={}] - Optional configuration parameter.
  41814. */
  41815. updateTexture( /*texture, options = {}*/ ) { }
  41816. /**
  41817. * Generates mipmaps for the given texture.
  41818. *
  41819. * @abstract
  41820. * @param {Texture} texture - The texture.
  41821. */
  41822. generateMipmaps( /*texture*/ ) { }
  41823. /**
  41824. * Destroys the GPU data for the given texture object.
  41825. *
  41826. * @abstract
  41827. * @param {Texture} texture - The texture.
  41828. */
  41829. destroyTexture( /*texture*/ ) { }
  41830. /**
  41831. * Returns texture data as a typed array.
  41832. *
  41833. * @abstract
  41834. * @async
  41835. * @param {Texture} texture - The texture to copy.
  41836. * @param {number} x - The x coordinate of the copy origin.
  41837. * @param {number} y - The y coordinate of the copy origin.
  41838. * @param {number} width - The width of the copy.
  41839. * @param {number} height - The height of the copy.
  41840. * @param {number} faceIndex - The face index.
  41841. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  41842. */
  41843. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  41844. /**
  41845. * Copies data of the given source texture to the given destination texture.
  41846. *
  41847. * @abstract
  41848. * @param {Texture} srcTexture - The source texture.
  41849. * @param {Texture} dstTexture - The destination texture.
  41850. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  41851. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  41852. * @param {number} [srcLevel=0] - The source mip level to copy from.
  41853. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  41854. */
  41855. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  41856. /**
  41857. * Copies the current bound framebuffer to the given texture.
  41858. *
  41859. * @abstract
  41860. * @param {Texture} texture - The destination texture.
  41861. * @param {RenderContext} renderContext - The render context.
  41862. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  41863. */
  41864. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  41865. // attributes
  41866. /**
  41867. * Creates the GPU buffer of a shader attribute.
  41868. *
  41869. * @abstract
  41870. * @param {BufferAttribute} attribute - The buffer attribute.
  41871. */
  41872. createAttribute( /*attribute*/ ) { }
  41873. /**
  41874. * Creates the GPU buffer of an indexed shader attribute.
  41875. *
  41876. * @abstract
  41877. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  41878. */
  41879. createIndexAttribute( /*attribute*/ ) { }
  41880. /**
  41881. * Creates the GPU buffer of a storage attribute.
  41882. *
  41883. * @abstract
  41884. * @param {BufferAttribute} attribute - The buffer attribute.
  41885. */
  41886. createStorageAttribute( /*attribute*/ ) { }
  41887. /**
  41888. * Updates the GPU buffer of a shader attribute.
  41889. *
  41890. * @abstract
  41891. * @param {BufferAttribute} attribute - The buffer attribute to update.
  41892. */
  41893. updateAttribute( /*attribute*/ ) { }
  41894. /**
  41895. * Destroys the GPU buffer of a shader attribute.
  41896. *
  41897. * @abstract
  41898. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  41899. */
  41900. destroyAttribute( /*attribute*/ ) { }
  41901. // canvas
  41902. /**
  41903. * Returns the backend's rendering context.
  41904. *
  41905. * @abstract
  41906. * @return {Object} The rendering context.
  41907. */
  41908. getContext() { }
  41909. /**
  41910. * Backends can use this method if they have to run
  41911. * logic when the renderer gets resized.
  41912. *
  41913. * @abstract
  41914. */
  41915. updateSize() { }
  41916. /**
  41917. * Updates the viewport with the values from the given render context.
  41918. *
  41919. * @abstract
  41920. * @param {RenderContext} renderContext - The render context.
  41921. */
  41922. updateViewport( /*renderContext*/ ) {}
  41923. // utils
  41924. /**
  41925. * Returns `true` if the given 3D object is fully occluded by other
  41926. * 3D objects in the scene. Backends must implement this method by using
  41927. * a Occlusion Query API.
  41928. *
  41929. * @abstract
  41930. * @param {RenderContext} renderContext - The render context.
  41931. * @param {Object3D} object - The 3D object to test.
  41932. * @return {boolean} Whether the 3D object is fully occluded or not.
  41933. */
  41934. isOccluded( /*renderContext, object*/ ) {}
  41935. /**
  41936. * Resolves the time stamp for the given render context and type.
  41937. *
  41938. * @async
  41939. * @abstract
  41940. * @param {string} [type='render'] - The type of the time stamp.
  41941. * @return {Promise<number>} A Promise that resolves with the time stamp.
  41942. */
  41943. async resolveTimestampsAsync( type = 'render' ) {
  41944. if ( ! this.trackTimestamp ) {
  41945. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  41946. return;
  41947. }
  41948. const queryPool = this.timestampQueryPool[ type ];
  41949. if ( ! queryPool ) {
  41950. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  41951. return;
  41952. }
  41953. const duration = await queryPool.resolveQueriesAsync();
  41954. this.renderer.info[ type ].timestamp = duration;
  41955. return duration;
  41956. }
  41957. /**
  41958. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  41959. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  41960. *
  41961. * @async
  41962. * @abstract
  41963. * @return {Promise} A Promise that resolves when synchronization has been finished.
  41964. */
  41965. async waitForGPU() {}
  41966. /**
  41967. * This method performs a readback operation by moving buffer data from
  41968. * a storage buffer attribute from the GPU to the CPU.
  41969. *
  41970. * @async
  41971. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  41972. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  41973. */
  41974. async getArrayBufferAsync( /* attribute */ ) {}
  41975. /**
  41976. * Checks if the given feature is supported by the backend.
  41977. *
  41978. * @async
  41979. * @abstract
  41980. * @param {string} name - The feature's name.
  41981. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  41982. */
  41983. async hasFeatureAsync( /*name*/ ) { }
  41984. /**
  41985. * Checks if the given feature is supported by the backend.
  41986. *
  41987. * @abstract
  41988. * @param {string} name - The feature's name.
  41989. * @return {boolean} Whether the feature is supported or not.
  41990. */
  41991. hasFeature( /*name*/ ) {}
  41992. /**
  41993. * Returns the maximum anisotropy texture filtering value.
  41994. *
  41995. * @abstract
  41996. * @return {number} The maximum anisotropy texture filtering value.
  41997. */
  41998. getMaxAnisotropy() {}
  41999. /**
  42000. * Returns the drawing buffer size.
  42001. *
  42002. * @return {Vector2} The drawing buffer size.
  42003. */
  42004. getDrawingBufferSize() {
  42005. _vector2 = _vector2 || new Vector2();
  42006. return this.renderer.getDrawingBufferSize( _vector2 );
  42007. }
  42008. /**
  42009. * Defines the scissor test.
  42010. *
  42011. * @abstract
  42012. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42013. */
  42014. setScissorTest( /*boolean*/ ) { }
  42015. /**
  42016. * Returns the clear color and alpha into a single
  42017. * color object.
  42018. *
  42019. * @return {Color4} The clear color.
  42020. */
  42021. getClearColor() {
  42022. const renderer = this.renderer;
  42023. _color4 = _color4 || new Color4();
  42024. renderer.getClearColor( _color4 );
  42025. _color4.getRGB( _color4 );
  42026. return _color4;
  42027. }
  42028. /**
  42029. * Returns the DOM element. If no DOM element exists, the backend
  42030. * creates a new one.
  42031. *
  42032. * @return {HTMLCanvasElement} The DOM element.
  42033. */
  42034. getDomElement() {
  42035. let domElement = this.domElement;
  42036. if ( domElement === null ) {
  42037. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  42038. // OffscreenCanvas does not have setAttribute, see #22811
  42039. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  42040. this.domElement = domElement;
  42041. }
  42042. return domElement;
  42043. }
  42044. /**
  42045. * Sets a dictionary for the given object into the
  42046. * internal data structure.
  42047. *
  42048. * @param {Object} object - The object.
  42049. * @param {Object} value - The dictionary to set.
  42050. */
  42051. set( object, value ) {
  42052. this.data.set( object, value );
  42053. }
  42054. /**
  42055. * Returns the dictionary for the given object.
  42056. *
  42057. * @param {Object} object - The object.
  42058. * @return {Object} The object's dictionary.
  42059. */
  42060. get( object ) {
  42061. let map = this.data.get( object );
  42062. if ( map === undefined ) {
  42063. map = {};
  42064. this.data.set( object, map );
  42065. }
  42066. return map;
  42067. }
  42068. /**
  42069. * Checks if the given object has a dictionary
  42070. * with data defined.
  42071. *
  42072. * @param {Object} object - The object.
  42073. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  42074. */
  42075. has( object ) {
  42076. return this.data.has( object );
  42077. }
  42078. /**
  42079. * Deletes an object from the internal data structure.
  42080. *
  42081. * @param {Object} object - The object to delete.
  42082. */
  42083. delete( object ) {
  42084. this.data.delete( object );
  42085. }
  42086. /**
  42087. * Frees internal resources.
  42088. *
  42089. * @abstract
  42090. */
  42091. dispose() { }
  42092. }
  42093. let _id$1 = 0;
  42094. /**
  42095. * This module is internally used in context of compute shaders.
  42096. * This type of shader is not natively supported in WebGL 2 and
  42097. * thus implemented via Transform Feedback. `DualAttributeData`
  42098. * manages the related data.
  42099. *
  42100. * @private
  42101. */
  42102. class DualAttributeData {
  42103. constructor( attributeData, dualBuffer ) {
  42104. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  42105. this.type = attributeData.type;
  42106. this.bufferType = attributeData.bufferType;
  42107. this.pbo = attributeData.pbo;
  42108. this.byteLength = attributeData.byteLength;
  42109. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  42110. this.version = attributeData.version;
  42111. this.isInteger = attributeData.isInteger;
  42112. this.activeBufferIndex = 0;
  42113. this.baseId = attributeData.id;
  42114. }
  42115. get id() {
  42116. return `${ this.baseId }|${ this.activeBufferIndex }`;
  42117. }
  42118. get bufferGPU() {
  42119. return this.buffers[ this.activeBufferIndex ];
  42120. }
  42121. get transformBuffer() {
  42122. return this.buffers[ this.activeBufferIndex ^ 1 ];
  42123. }
  42124. switchBuffers() {
  42125. this.activeBufferIndex ^= 1;
  42126. }
  42127. }
  42128. /**
  42129. * A WebGL 2 backend utility module for managing shader attributes.
  42130. *
  42131. * @private
  42132. */
  42133. class WebGLAttributeUtils {
  42134. /**
  42135. * Constructs a new utility object.
  42136. *
  42137. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42138. */
  42139. constructor( backend ) {
  42140. /**
  42141. * A reference to the WebGL 2 backend.
  42142. *
  42143. * @type {WebGLBackend}
  42144. */
  42145. this.backend = backend;
  42146. }
  42147. /**
  42148. * Creates the GPU buffer for the given buffer attribute.
  42149. *
  42150. * @param {BufferAttribute} attribute - The buffer attribute.
  42151. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  42152. */
  42153. createAttribute( attribute, bufferType ) {
  42154. const backend = this.backend;
  42155. const { gl } = backend;
  42156. const array = attribute.array;
  42157. const usage = attribute.usage || gl.STATIC_DRAW;
  42158. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  42159. const bufferData = backend.get( bufferAttribute );
  42160. let bufferGPU = bufferData.bufferGPU;
  42161. if ( bufferGPU === undefined ) {
  42162. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  42163. bufferData.bufferGPU = bufferGPU;
  42164. bufferData.bufferType = bufferType;
  42165. bufferData.version = bufferAttribute.version;
  42166. }
  42167. //attribute.onUploadCallback();
  42168. let type;
  42169. if ( array instanceof Float32Array ) {
  42170. type = gl.FLOAT;
  42171. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  42172. type = gl.HALF_FLOAT;
  42173. } else if ( array instanceof Uint16Array ) {
  42174. if ( attribute.isFloat16BufferAttribute ) {
  42175. type = gl.HALF_FLOAT;
  42176. } else {
  42177. type = gl.UNSIGNED_SHORT;
  42178. }
  42179. } else if ( array instanceof Int16Array ) {
  42180. type = gl.SHORT;
  42181. } else if ( array instanceof Uint32Array ) {
  42182. type = gl.UNSIGNED_INT;
  42183. } else if ( array instanceof Int32Array ) {
  42184. type = gl.INT;
  42185. } else if ( array instanceof Int8Array ) {
  42186. type = gl.BYTE;
  42187. } else if ( array instanceof Uint8Array ) {
  42188. type = gl.UNSIGNED_BYTE;
  42189. } else if ( array instanceof Uint8ClampedArray ) {
  42190. type = gl.UNSIGNED_BYTE;
  42191. } else {
  42192. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  42193. }
  42194. let attributeData = {
  42195. bufferGPU,
  42196. bufferType,
  42197. type,
  42198. byteLength: array.byteLength,
  42199. bytesPerElement: array.BYTES_PER_ELEMENT,
  42200. version: attribute.version,
  42201. pbo: attribute.pbo,
  42202. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  42203. id: _id$1 ++
  42204. };
  42205. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  42206. // create buffer for transform feedback use
  42207. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  42208. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  42209. }
  42210. backend.set( attribute, attributeData );
  42211. }
  42212. /**
  42213. * Updates the GPU buffer of the given buffer attribute.
  42214. *
  42215. * @param {BufferAttribute} attribute - The buffer attribute.
  42216. */
  42217. updateAttribute( attribute ) {
  42218. const backend = this.backend;
  42219. const { gl } = backend;
  42220. const array = attribute.array;
  42221. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  42222. const bufferData = backend.get( bufferAttribute );
  42223. const bufferType = bufferData.bufferType;
  42224. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  42225. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  42226. if ( updateRanges.length === 0 ) {
  42227. // Not using update ranges
  42228. gl.bufferSubData( bufferType, 0, array );
  42229. } else {
  42230. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  42231. const range = updateRanges[ i ];
  42232. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  42233. array, range.start, range.count );
  42234. }
  42235. bufferAttribute.clearUpdateRanges();
  42236. }
  42237. gl.bindBuffer( bufferType, null );
  42238. bufferData.version = bufferAttribute.version;
  42239. }
  42240. /**
  42241. * Destroys the GPU buffer of the given buffer attribute.
  42242. *
  42243. * @param {BufferAttribute} attribute - The buffer attribute.
  42244. */
  42245. destroyAttribute( attribute ) {
  42246. const backend = this.backend;
  42247. const { gl } = backend;
  42248. if ( attribute.isInterleavedBufferAttribute ) {
  42249. backend.delete( attribute.data );
  42250. }
  42251. const attributeData = backend.get( attribute );
  42252. gl.deleteBuffer( attributeData.bufferGPU );
  42253. backend.delete( attribute );
  42254. }
  42255. /**
  42256. * This method performs a readback operation by moving buffer data from
  42257. * a storage buffer attribute from the GPU to the CPU.
  42258. *
  42259. * @async
  42260. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42261. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42262. */
  42263. async getArrayBufferAsync( attribute ) {
  42264. const backend = this.backend;
  42265. const { gl } = backend;
  42266. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  42267. const { bufferGPU } = backend.get( bufferAttribute );
  42268. const array = attribute.array;
  42269. const byteLength = array.byteLength;
  42270. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  42271. const writeBuffer = gl.createBuffer();
  42272. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  42273. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  42274. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  42275. await backend.utils._clientWaitAsync();
  42276. const dstBuffer = new attribute.array.constructor( array.length );
  42277. // Ensure the buffer is bound before reading
  42278. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  42279. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  42280. gl.deleteBuffer( writeBuffer );
  42281. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  42282. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  42283. return dstBuffer.buffer;
  42284. }
  42285. /**
  42286. * Creates a WebGL buffer with the given data.
  42287. *
  42288. * @private
  42289. * @param {WebGL2RenderingContext} gl - The rendering context.
  42290. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  42291. * @param {TypedArray} array - The array of the buffer attribute.
  42292. * @param {GLenum} usage - The usage.
  42293. * @return {WebGLBuffer} The WebGL buffer.
  42294. */
  42295. _createBuffer( gl, bufferType, array, usage ) {
  42296. const bufferGPU = gl.createBuffer();
  42297. gl.bindBuffer( bufferType, bufferGPU );
  42298. gl.bufferData( bufferType, array, usage );
  42299. gl.bindBuffer( bufferType, null );
  42300. return bufferGPU;
  42301. }
  42302. }
  42303. let equationToGL, factorToGL;
  42304. /**
  42305. * A WebGL 2 backend utility module for managing the WebGL state.
  42306. *
  42307. * The major goal of this module is to reduce the number of state changes
  42308. * by caching the WEbGL state with a series of variables. In this way, the
  42309. * renderer only executes state change commands when necessary which
  42310. * improves the overall performance.
  42311. *
  42312. * @private
  42313. */
  42314. class WebGLState {
  42315. /**
  42316. * Constructs a new utility object.
  42317. *
  42318. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42319. */
  42320. constructor( backend ) {
  42321. /**
  42322. * A reference to the WebGL 2 backend.
  42323. *
  42324. * @type {WebGLBackend}
  42325. */
  42326. this.backend = backend;
  42327. /**
  42328. * A reference to the rendering context.
  42329. *
  42330. * @type {WebGL2RenderingContext}
  42331. */
  42332. this.gl = this.backend.gl;
  42333. // Below properties are intended to cache
  42334. // the WebGL state and are not explicitly
  42335. // documented for convenience reasons.
  42336. this.enabled = {};
  42337. this.currentFlipSided = null;
  42338. this.currentCullFace = null;
  42339. this.currentProgram = null;
  42340. this.currentBlendingEnabled = false;
  42341. this.currentBlending = null;
  42342. this.currentBlendSrc = null;
  42343. this.currentBlendDst = null;
  42344. this.currentBlendSrcAlpha = null;
  42345. this.currentBlendDstAlpha = null;
  42346. this.currentPremultipledAlpha = null;
  42347. this.currentPolygonOffsetFactor = null;
  42348. this.currentPolygonOffsetUnits = null;
  42349. this.currentColorMask = null;
  42350. this.currentDepthFunc = null;
  42351. this.currentDepthMask = null;
  42352. this.currentStencilFunc = null;
  42353. this.currentStencilRef = null;
  42354. this.currentStencilFuncMask = null;
  42355. this.currentStencilFail = null;
  42356. this.currentStencilZFail = null;
  42357. this.currentStencilZPass = null;
  42358. this.currentStencilMask = null;
  42359. this.currentLineWidth = null;
  42360. this.currentClippingPlanes = 0;
  42361. this.currentVAO = null;
  42362. this.currentIndex = null;
  42363. this.currentBoundFramebuffers = {};
  42364. this.currentDrawbuffers = new WeakMap();
  42365. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  42366. this.currentTextureSlot = null;
  42367. this.currentBoundTextures = {};
  42368. this.currentBoundBufferBases = {};
  42369. this._init();
  42370. }
  42371. /**
  42372. * Inits the state of the utility.
  42373. *
  42374. * @private
  42375. */
  42376. _init() {
  42377. const gl = this.gl;
  42378. // Store only WebGL constants here.
  42379. equationToGL = {
  42380. [ AddEquation ]: gl.FUNC_ADD,
  42381. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  42382. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  42383. };
  42384. factorToGL = {
  42385. [ ZeroFactor ]: gl.ZERO,
  42386. [ OneFactor ]: gl.ONE,
  42387. [ SrcColorFactor ]: gl.SRC_COLOR,
  42388. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  42389. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  42390. [ DstColorFactor ]: gl.DST_COLOR,
  42391. [ DstAlphaFactor ]: gl.DST_ALPHA,
  42392. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  42393. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  42394. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  42395. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  42396. };
  42397. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  42398. const viewportParam = gl.getParameter( gl.VIEWPORT );
  42399. this.currentScissor = new Vector4().fromArray( scissorParam );
  42400. this.currentViewport = new Vector4().fromArray( viewportParam );
  42401. this._tempVec4 = new Vector4();
  42402. }
  42403. /**
  42404. * Enables the given WebGL capability.
  42405. *
  42406. * This method caches the capability state so
  42407. * `gl.enable()` is only called when necessary.
  42408. *
  42409. * @param {GLenum} id - The capability to enable.
  42410. */
  42411. enable( id ) {
  42412. const { enabled } = this;
  42413. if ( enabled[ id ] !== true ) {
  42414. this.gl.enable( id );
  42415. enabled[ id ] = true;
  42416. }
  42417. }
  42418. /**
  42419. * Disables the given WebGL capability.
  42420. *
  42421. * This method caches the capability state so
  42422. * `gl.disable()` is only called when necessary.
  42423. *
  42424. * @param {GLenum} id - The capability to enable.
  42425. */
  42426. disable( id ) {
  42427. const { enabled } = this;
  42428. if ( enabled[ id ] !== false ) {
  42429. this.gl.disable( id );
  42430. enabled[ id ] = false;
  42431. }
  42432. }
  42433. /**
  42434. * Specifies whether polygons are front- or back-facing
  42435. * by setting the winding orientation.
  42436. *
  42437. * This method caches the state so `gl.frontFace()` is only
  42438. * called when necessary.
  42439. *
  42440. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  42441. */
  42442. setFlipSided( flipSided ) {
  42443. if ( this.currentFlipSided !== flipSided ) {
  42444. const { gl } = this;
  42445. if ( flipSided ) {
  42446. gl.frontFace( gl.CW );
  42447. } else {
  42448. gl.frontFace( gl.CCW );
  42449. }
  42450. this.currentFlipSided = flipSided;
  42451. }
  42452. }
  42453. /**
  42454. * Specifies whether or not front- and/or back-facing
  42455. * polygons can be culled.
  42456. *
  42457. * This method caches the state so `gl.cullFace()` is only
  42458. * called when necessary.
  42459. *
  42460. * @param {number} cullFace - Defines which polygons are candidates for culling.
  42461. */
  42462. setCullFace( cullFace ) {
  42463. const { gl } = this;
  42464. if ( cullFace !== CullFaceNone ) {
  42465. this.enable( gl.CULL_FACE );
  42466. if ( cullFace !== this.currentCullFace ) {
  42467. if ( cullFace === CullFaceBack ) {
  42468. gl.cullFace( gl.BACK );
  42469. } else if ( cullFace === CullFaceFront ) {
  42470. gl.cullFace( gl.FRONT );
  42471. } else {
  42472. gl.cullFace( gl.FRONT_AND_BACK );
  42473. }
  42474. }
  42475. } else {
  42476. this.disable( gl.CULL_FACE );
  42477. }
  42478. this.currentCullFace = cullFace;
  42479. }
  42480. /**
  42481. * Specifies the width of line primitives.
  42482. *
  42483. * This method caches the state so `gl.lineWidth()` is only
  42484. * called when necessary.
  42485. *
  42486. * @param {number} width - The line width.
  42487. */
  42488. setLineWidth( width ) {
  42489. const { currentLineWidth, gl } = this;
  42490. if ( width !== currentLineWidth ) {
  42491. gl.lineWidth( width );
  42492. this.currentLineWidth = width;
  42493. }
  42494. }
  42495. /**
  42496. * Defines the blending.
  42497. *
  42498. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  42499. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  42500. *
  42501. * @param {number} blending - The blending type.
  42502. * @param {number} blendEquation - The blending equation.
  42503. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  42504. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  42505. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  42506. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  42507. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  42508. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  42509. */
  42510. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  42511. const { gl } = this;
  42512. if ( blending === NoBlending ) {
  42513. if ( this.currentBlendingEnabled === true ) {
  42514. this.disable( gl.BLEND );
  42515. this.currentBlendingEnabled = false;
  42516. }
  42517. return;
  42518. }
  42519. if ( this.currentBlendingEnabled === false ) {
  42520. this.enable( gl.BLEND );
  42521. this.currentBlendingEnabled = true;
  42522. }
  42523. if ( blending !== CustomBlending ) {
  42524. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  42525. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  42526. gl.blendEquation( gl.FUNC_ADD );
  42527. this.currentBlendEquation = AddEquation;
  42528. this.currentBlendEquationAlpha = AddEquation;
  42529. }
  42530. if ( premultipliedAlpha ) {
  42531. switch ( blending ) {
  42532. case NormalBlending:
  42533. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  42534. break;
  42535. case AdditiveBlending:
  42536. gl.blendFunc( gl.ONE, gl.ONE );
  42537. break;
  42538. case SubtractiveBlending:
  42539. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  42540. break;
  42541. case MultiplyBlending:
  42542. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  42543. break;
  42544. default:
  42545. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  42546. break;
  42547. }
  42548. } else {
  42549. switch ( blending ) {
  42550. case NormalBlending:
  42551. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  42552. break;
  42553. case AdditiveBlending:
  42554. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  42555. break;
  42556. case SubtractiveBlending:
  42557. console.error( 'THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  42558. break;
  42559. case MultiplyBlending:
  42560. console.error( 'THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  42561. break;
  42562. default:
  42563. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  42564. break;
  42565. }
  42566. }
  42567. this.currentBlendSrc = null;
  42568. this.currentBlendDst = null;
  42569. this.currentBlendSrcAlpha = null;
  42570. this.currentBlendDstAlpha = null;
  42571. this.currentBlending = blending;
  42572. this.currentPremultipledAlpha = premultipliedAlpha;
  42573. }
  42574. return;
  42575. }
  42576. // custom blending
  42577. blendEquationAlpha = blendEquationAlpha || blendEquation;
  42578. blendSrcAlpha = blendSrcAlpha || blendSrc;
  42579. blendDstAlpha = blendDstAlpha || blendDst;
  42580. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  42581. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  42582. this.currentBlendEquation = blendEquation;
  42583. this.currentBlendEquationAlpha = blendEquationAlpha;
  42584. }
  42585. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  42586. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  42587. this.currentBlendSrc = blendSrc;
  42588. this.currentBlendDst = blendDst;
  42589. this.currentBlendSrcAlpha = blendSrcAlpha;
  42590. this.currentBlendDstAlpha = blendDstAlpha;
  42591. }
  42592. this.currentBlending = blending;
  42593. this.currentPremultipledAlpha = false;
  42594. }
  42595. /**
  42596. * Specifies whether colors can be written when rendering
  42597. * into a framebuffer or not.
  42598. *
  42599. * This method caches the state so `gl.colorMask()` is only
  42600. * called when necessary.
  42601. *
  42602. * @param {boolean} colorMask - The color mask.
  42603. */
  42604. setColorMask( colorMask ) {
  42605. if ( this.currentColorMask !== colorMask ) {
  42606. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  42607. this.currentColorMask = colorMask;
  42608. }
  42609. }
  42610. /**
  42611. * Specifies whether the depth test is enabled or not.
  42612. *
  42613. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  42614. */
  42615. setDepthTest( depthTest ) {
  42616. const { gl } = this;
  42617. if ( depthTest ) {
  42618. this.enable( gl.DEPTH_TEST );
  42619. } else {
  42620. this.disable( gl.DEPTH_TEST );
  42621. }
  42622. }
  42623. /**
  42624. * Specifies whether depth values can be written when rendering
  42625. * into a framebuffer or not.
  42626. *
  42627. * This method caches the state so `gl.depthMask()` is only
  42628. * called when necessary.
  42629. *
  42630. * @param {boolean} depthMask - The depth mask.
  42631. */
  42632. setDepthMask( depthMask ) {
  42633. if ( this.currentDepthMask !== depthMask ) {
  42634. this.gl.depthMask( depthMask );
  42635. this.currentDepthMask = depthMask;
  42636. }
  42637. }
  42638. /**
  42639. * Specifies the depth compare function.
  42640. *
  42641. * This method caches the state so `gl.depthFunc()` is only
  42642. * called when necessary.
  42643. *
  42644. * @param {number} depthFunc - The depth compare function.
  42645. */
  42646. setDepthFunc( depthFunc ) {
  42647. if ( this.currentDepthFunc !== depthFunc ) {
  42648. const { gl } = this;
  42649. switch ( depthFunc ) {
  42650. case NeverDepth:
  42651. gl.depthFunc( gl.NEVER );
  42652. break;
  42653. case AlwaysDepth:
  42654. gl.depthFunc( gl.ALWAYS );
  42655. break;
  42656. case LessDepth:
  42657. gl.depthFunc( gl.LESS );
  42658. break;
  42659. case LessEqualDepth:
  42660. gl.depthFunc( gl.LEQUAL );
  42661. break;
  42662. case EqualDepth:
  42663. gl.depthFunc( gl.EQUAL );
  42664. break;
  42665. case GreaterEqualDepth:
  42666. gl.depthFunc( gl.GEQUAL );
  42667. break;
  42668. case GreaterDepth:
  42669. gl.depthFunc( gl.GREATER );
  42670. break;
  42671. case NotEqualDepth:
  42672. gl.depthFunc( gl.NOTEQUAL );
  42673. break;
  42674. default:
  42675. gl.depthFunc( gl.LEQUAL );
  42676. }
  42677. this.currentDepthFunc = depthFunc;
  42678. }
  42679. }
  42680. /**
  42681. * Specifies the scissor box.
  42682. *
  42683. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  42684. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  42685. * @param {number} width - The width of the viewport.
  42686. * @param {number} height - The height of the viewport.
  42687. *
  42688. */
  42689. scissor( x, y, width, height ) {
  42690. const scissor = this._tempVec4.set( x, y, width, height );
  42691. if ( this.currentScissor.equals( scissor ) === false ) {
  42692. const { gl } = this;
  42693. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  42694. this.currentScissor.copy( scissor );
  42695. }
  42696. }
  42697. /**
  42698. * Specifies the viewport.
  42699. *
  42700. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  42701. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  42702. * @param {number} width - The width of the viewport.
  42703. * @param {number} height - The height of the viewport.
  42704. *
  42705. */
  42706. viewport( x, y, width, height ) {
  42707. const viewport = this._tempVec4.set( x, y, width, height );
  42708. if ( this.currentViewport.equals( viewport ) === false ) {
  42709. const { gl } = this;
  42710. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  42711. this.currentViewport.copy( viewport );
  42712. }
  42713. }
  42714. /**
  42715. * Defines the scissor test.
  42716. *
  42717. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  42718. */
  42719. setScissorTest( boolean ) {
  42720. const gl = this.gl;
  42721. if ( boolean ) {
  42722. gl.enable( gl.SCISSOR_TEST );
  42723. } else {
  42724. gl.disable( gl.SCISSOR_TEST );
  42725. }
  42726. }
  42727. /**
  42728. * Specifies whether the stencil test is enabled or not.
  42729. *
  42730. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  42731. */
  42732. setStencilTest( stencilTest ) {
  42733. const { gl } = this;
  42734. if ( stencilTest ) {
  42735. this.enable( gl.STENCIL_TEST );
  42736. } else {
  42737. this.disable( gl.STENCIL_TEST );
  42738. }
  42739. }
  42740. /**
  42741. * Specifies whether stencil values can be written when rendering
  42742. * into a framebuffer or not.
  42743. *
  42744. * This method caches the state so `gl.stencilMask()` is only
  42745. * called when necessary.
  42746. *
  42747. * @param {boolean} stencilMask - The stencil mask.
  42748. */
  42749. setStencilMask( stencilMask ) {
  42750. if ( this.currentStencilMask !== stencilMask ) {
  42751. this.gl.stencilMask( stencilMask );
  42752. this.currentStencilMask = stencilMask;
  42753. }
  42754. }
  42755. /**
  42756. * Specifies whether the stencil test functions.
  42757. *
  42758. * This method caches the state so `gl.stencilFunc()` is only
  42759. * called when necessary.
  42760. *
  42761. * @param {number} stencilFunc - The stencil compare function.
  42762. * @param {number} stencilRef - The reference value for the stencil test.
  42763. * @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.
  42764. */
  42765. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  42766. if ( this.currentStencilFunc !== stencilFunc ||
  42767. this.currentStencilRef !== stencilRef ||
  42768. this.currentStencilFuncMask !== stencilMask ) {
  42769. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  42770. this.currentStencilFunc = stencilFunc;
  42771. this.currentStencilRef = stencilRef;
  42772. this.currentStencilFuncMask = stencilMask;
  42773. }
  42774. }
  42775. /**
  42776. * Specifies whether the stencil test operation.
  42777. *
  42778. * This method caches the state so `gl.stencilOp()` is only
  42779. * called when necessary.
  42780. *
  42781. * @param {number} stencilFail - The function to use when the stencil test fails.
  42782. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  42783. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  42784. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  42785. */
  42786. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  42787. if ( this.currentStencilFail !== stencilFail ||
  42788. this.currentStencilZFail !== stencilZFail ||
  42789. this.currentStencilZPass !== stencilZPass ) {
  42790. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  42791. this.currentStencilFail = stencilFail;
  42792. this.currentStencilZFail = stencilZFail;
  42793. this.currentStencilZPass = stencilZPass;
  42794. }
  42795. }
  42796. /**
  42797. * Configures the WebGL state for the given material.
  42798. *
  42799. * @param {Material} material - The material to configure the state for.
  42800. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  42801. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  42802. */
  42803. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  42804. const { gl } = this;
  42805. material.side === DoubleSide
  42806. ? this.disable( gl.CULL_FACE )
  42807. : this.enable( gl.CULL_FACE );
  42808. let flipSided = ( material.side === BackSide );
  42809. if ( frontFaceCW ) flipSided = ! flipSided;
  42810. this.setFlipSided( flipSided );
  42811. ( material.blending === NormalBlending && material.transparent === false )
  42812. ? this.setBlending( NoBlending )
  42813. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  42814. this.setDepthFunc( material.depthFunc );
  42815. this.setDepthTest( material.depthTest );
  42816. this.setDepthMask( material.depthWrite );
  42817. this.setColorMask( material.colorWrite );
  42818. const stencilWrite = material.stencilWrite;
  42819. this.setStencilTest( stencilWrite );
  42820. if ( stencilWrite ) {
  42821. this.setStencilMask( material.stencilWriteMask );
  42822. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  42823. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  42824. }
  42825. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  42826. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  42827. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  42828. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  42829. if ( hardwareClippingPlanes > 0 ) {
  42830. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  42831. const CLIP_DISTANCE0_WEBGL = 0x3000;
  42832. for ( let i = 0; i < 8; i ++ ) {
  42833. if ( i < hardwareClippingPlanes ) {
  42834. this.enable( CLIP_DISTANCE0_WEBGL + i );
  42835. } else {
  42836. this.disable( CLIP_DISTANCE0_WEBGL + i );
  42837. }
  42838. }
  42839. }
  42840. }
  42841. }
  42842. /**
  42843. * Specifies the polygon offset.
  42844. *
  42845. * This method caches the state so `gl.polygonOffset()` is only
  42846. * called when necessary.
  42847. *
  42848. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  42849. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  42850. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  42851. */
  42852. setPolygonOffset( polygonOffset, factor, units ) {
  42853. const { gl } = this;
  42854. if ( polygonOffset ) {
  42855. this.enable( gl.POLYGON_OFFSET_FILL );
  42856. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  42857. gl.polygonOffset( factor, units );
  42858. this.currentPolygonOffsetFactor = factor;
  42859. this.currentPolygonOffsetUnits = units;
  42860. }
  42861. } else {
  42862. this.disable( gl.POLYGON_OFFSET_FILL );
  42863. }
  42864. }
  42865. /**
  42866. * Defines the usage of the given WebGL program.
  42867. *
  42868. * This method caches the state so `gl.useProgram()` is only
  42869. * called when necessary.
  42870. *
  42871. * @param {WebGLProgram} program - The WebGL program to use.
  42872. * @return {boolean} Whether a program change has been executed or not.
  42873. */
  42874. useProgram( program ) {
  42875. if ( this.currentProgram !== program ) {
  42876. this.gl.useProgram( program );
  42877. this.currentProgram = program;
  42878. return true;
  42879. }
  42880. return false;
  42881. }
  42882. /**
  42883. * Sets the vertex state by binding the given VAO and element buffer.
  42884. *
  42885. * @param {WebGLVertexArrayObject} vao - The VAO.
  42886. * @param {WebGLBuffer} indexBuffer - The index buffer.
  42887. * @return {boolean} Whether a vertex state has been changed or not.
  42888. */
  42889. setVertexState( vao, indexBuffer = null ) {
  42890. const gl = this.gl;
  42891. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  42892. gl.bindVertexArray( vao );
  42893. if ( indexBuffer !== null ) {
  42894. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  42895. }
  42896. this.currentVAO = vao;
  42897. this.currentIndex = indexBuffer;
  42898. return true;
  42899. }
  42900. return false;
  42901. }
  42902. /**
  42903. * Resets the vertex array state by resetting the VAO and element buffer.
  42904. */
  42905. resetVertexState() {
  42906. const gl = this.gl;
  42907. gl.bindVertexArray( null );
  42908. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  42909. this.currentVAO = null;
  42910. this.currentIndex = null;
  42911. }
  42912. // framebuffer
  42913. /**
  42914. * Binds the given framebuffer.
  42915. *
  42916. * This method caches the state so `gl.bindFramebuffer()` is only
  42917. * called when necessary.
  42918. *
  42919. * @param {number} target - The binding point (target).
  42920. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  42921. * @return {boolean} Whether a bind has been executed or not.
  42922. */
  42923. bindFramebuffer( target, framebuffer ) {
  42924. const { gl, currentBoundFramebuffers } = this;
  42925. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  42926. gl.bindFramebuffer( target, framebuffer );
  42927. currentBoundFramebuffers[ target ] = framebuffer;
  42928. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  42929. if ( target === gl.DRAW_FRAMEBUFFER ) {
  42930. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  42931. }
  42932. if ( target === gl.FRAMEBUFFER ) {
  42933. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  42934. }
  42935. return true;
  42936. }
  42937. return false;
  42938. }
  42939. /**
  42940. * Defines draw buffers to which fragment colors are written into.
  42941. * Configures the MRT setup of custom framebuffers.
  42942. *
  42943. * This method caches the state so `gl.drawBuffers()` is only
  42944. * called when necessary.
  42945. *
  42946. * @param {RenderContext} renderContext - The render context.
  42947. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  42948. */
  42949. drawBuffers( renderContext, framebuffer ) {
  42950. const { gl } = this;
  42951. let drawBuffers = [];
  42952. let needsUpdate = false;
  42953. if ( renderContext.textures !== null ) {
  42954. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  42955. if ( drawBuffers === undefined ) {
  42956. drawBuffers = [];
  42957. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  42958. }
  42959. const textures = renderContext.textures;
  42960. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  42961. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  42962. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  42963. }
  42964. drawBuffers.length = textures.length;
  42965. needsUpdate = true;
  42966. }
  42967. } else {
  42968. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  42969. drawBuffers[ 0 ] = gl.BACK;
  42970. needsUpdate = true;
  42971. }
  42972. }
  42973. if ( needsUpdate ) {
  42974. gl.drawBuffers( drawBuffers );
  42975. }
  42976. }
  42977. // texture
  42978. /**
  42979. * Makes the given texture unit active.
  42980. *
  42981. * This method caches the state so `gl.activeTexture()` is only
  42982. * called when necessary.
  42983. *
  42984. * @param {number} webglSlot - The texture unit to make active.
  42985. */
  42986. activeTexture( webglSlot ) {
  42987. const { gl, currentTextureSlot, maxTextures } = this;
  42988. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  42989. if ( currentTextureSlot !== webglSlot ) {
  42990. gl.activeTexture( webglSlot );
  42991. this.currentTextureSlot = webglSlot;
  42992. }
  42993. }
  42994. /**
  42995. * Binds the given WebGL texture to a target.
  42996. *
  42997. * This method caches the state so `gl.bindTexture()` is only
  42998. * called when necessary.
  42999. *
  43000. * @param {number} webglType - The binding point (target).
  43001. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  43002. * @param {number} webglSlot - The texture.
  43003. */
  43004. bindTexture( webglType, webglTexture, webglSlot ) {
  43005. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  43006. if ( webglSlot === undefined ) {
  43007. if ( currentTextureSlot === null ) {
  43008. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  43009. } else {
  43010. webglSlot = currentTextureSlot;
  43011. }
  43012. }
  43013. let boundTexture = currentBoundTextures[ webglSlot ];
  43014. if ( boundTexture === undefined ) {
  43015. boundTexture = { type: undefined, texture: undefined };
  43016. currentBoundTextures[ webglSlot ] = boundTexture;
  43017. }
  43018. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  43019. if ( currentTextureSlot !== webglSlot ) {
  43020. gl.activeTexture( webglSlot );
  43021. this.currentTextureSlot = webglSlot;
  43022. }
  43023. gl.bindTexture( webglType, webglTexture );
  43024. boundTexture.type = webglType;
  43025. boundTexture.texture = webglTexture;
  43026. }
  43027. }
  43028. /**
  43029. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  43030. *
  43031. * This method caches the state so `gl.bindBufferBase()` is only
  43032. * called when necessary.
  43033. *
  43034. * @param {number} target - The target for the bind operation.
  43035. * @param {number} index - The index of the target.
  43036. * @param {WebGLBuffer} buffer - The WebGL buffer.
  43037. * @return {boolean} Whether a bind has been executed or not.
  43038. */
  43039. bindBufferBase( target, index, buffer ) {
  43040. const { gl } = this;
  43041. const key = `${target}-${index}`;
  43042. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  43043. gl.bindBufferBase( target, index, buffer );
  43044. this.currentBoundBufferBases[ key ] = buffer;
  43045. return true;
  43046. }
  43047. return false;
  43048. }
  43049. /**
  43050. * Unbinds the current bound texture.
  43051. *
  43052. * This method caches the state so `gl.bindTexture()` is only
  43053. * called when necessary.
  43054. */
  43055. unbindTexture() {
  43056. const { gl, currentTextureSlot, currentBoundTextures } = this;
  43057. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  43058. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  43059. gl.bindTexture( boundTexture.type, null );
  43060. boundTexture.type = undefined;
  43061. boundTexture.texture = undefined;
  43062. }
  43063. }
  43064. }
  43065. /**
  43066. * A WebGL 2 backend utility module with common helpers.
  43067. *
  43068. * @private
  43069. */
  43070. class WebGLUtils {
  43071. /**
  43072. * Constructs a new utility object.
  43073. *
  43074. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43075. */
  43076. constructor( backend ) {
  43077. /**
  43078. * A reference to the WebGL 2 backend.
  43079. *
  43080. * @type {WebGLBackend}
  43081. */
  43082. this.backend = backend;
  43083. /**
  43084. * A reference to the rendering context.
  43085. *
  43086. * @type {WebGL2RenderingContext}
  43087. */
  43088. this.gl = this.backend.gl;
  43089. /**
  43090. * A reference to a backend module holding extension-related
  43091. * utility functions.
  43092. *
  43093. * @type {WebGLExtensions}
  43094. */
  43095. this.extensions = backend.extensions;
  43096. }
  43097. /**
  43098. * Converts the given three.js constant into a WebGL constant.
  43099. * The method currently supports the conversion of texture formats
  43100. * and types.
  43101. *
  43102. * @param {number} p - The three.js constant.
  43103. * @param {string} [colorSpace=NoColorSpace] - The color space.
  43104. * @return {?number} The corresponding WebGL constant.
  43105. */
  43106. convert( p, colorSpace = NoColorSpace ) {
  43107. const { gl, extensions } = this;
  43108. let extension;
  43109. const transfer = ColorManagement.getTransfer( colorSpace );
  43110. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  43111. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  43112. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  43113. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  43114. if ( p === ByteType ) return gl.BYTE;
  43115. if ( p === ShortType ) return gl.SHORT;
  43116. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  43117. if ( p === IntType ) return gl.INT;
  43118. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  43119. if ( p === FloatType ) return gl.FLOAT;
  43120. if ( p === HalfFloatType ) {
  43121. return gl.HALF_FLOAT;
  43122. }
  43123. if ( p === AlphaFormat ) return gl.ALPHA;
  43124. if ( p === RGBFormat ) return gl.RGB;
  43125. if ( p === RGBAFormat ) return gl.RGBA;
  43126. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  43127. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  43128. // WebGL2 formats.
  43129. if ( p === RedFormat ) return gl.RED;
  43130. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  43131. if ( p === RGFormat ) return gl.RG;
  43132. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  43133. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  43134. // S3TC
  43135. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  43136. if ( transfer === SRGBTransfer ) {
  43137. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  43138. if ( extension !== null ) {
  43139. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  43140. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  43141. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  43142. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  43143. } else {
  43144. return null;
  43145. }
  43146. } else {
  43147. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  43148. if ( extension !== null ) {
  43149. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  43150. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  43151. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  43152. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  43153. } else {
  43154. return null;
  43155. }
  43156. }
  43157. }
  43158. // PVRTC
  43159. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  43160. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  43161. if ( extension !== null ) {
  43162. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  43163. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  43164. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  43165. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  43166. } else {
  43167. return null;
  43168. }
  43169. }
  43170. // ETC
  43171. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  43172. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  43173. if ( extension !== null ) {
  43174. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  43175. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  43176. } else {
  43177. return null;
  43178. }
  43179. }
  43180. // ASTC
  43181. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  43182. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  43183. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  43184. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  43185. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  43186. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  43187. if ( extension !== null ) {
  43188. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  43189. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  43190. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  43191. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  43192. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  43193. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  43194. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  43195. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  43196. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  43197. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  43198. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  43199. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  43200. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  43201. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  43202. } else {
  43203. return null;
  43204. }
  43205. }
  43206. // BPTC
  43207. if ( p === RGBA_BPTC_Format ) {
  43208. extension = extensions.get( 'EXT_texture_compression_bptc' );
  43209. if ( extension !== null ) {
  43210. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  43211. } else {
  43212. return null;
  43213. }
  43214. }
  43215. // RGTC
  43216. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  43217. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  43218. if ( extension !== null ) {
  43219. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  43220. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  43221. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  43222. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  43223. } else {
  43224. return null;
  43225. }
  43226. }
  43227. //
  43228. if ( p === UnsignedInt248Type ) {
  43229. return gl.UNSIGNED_INT_24_8;
  43230. }
  43231. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  43232. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  43233. }
  43234. /**
  43235. * This method can be used to synchronize the CPU with the GPU by waiting until
  43236. * ongoing GPU commands have been completed.
  43237. *
  43238. * @private
  43239. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  43240. */
  43241. _clientWaitAsync() {
  43242. const { gl } = this;
  43243. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  43244. gl.flush();
  43245. return new Promise( ( resolve, reject ) => {
  43246. function test() {
  43247. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  43248. if ( res === gl.WAIT_FAILED ) {
  43249. gl.deleteSync( sync );
  43250. reject();
  43251. return;
  43252. }
  43253. if ( res === gl.TIMEOUT_EXPIRED ) {
  43254. requestAnimationFrame( test );
  43255. return;
  43256. }
  43257. gl.deleteSync( sync );
  43258. resolve();
  43259. }
  43260. test();
  43261. } );
  43262. }
  43263. }
  43264. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  43265. /**
  43266. * A WebGL 2 backend utility module for managing textures.
  43267. *
  43268. * @private
  43269. */
  43270. class WebGLTextureUtils {
  43271. /**
  43272. * Constructs a new utility object.
  43273. *
  43274. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43275. */
  43276. constructor( backend ) {
  43277. /**
  43278. * A reference to the WebGL 2 backend.
  43279. *
  43280. * @type {WebGLBackend}
  43281. */
  43282. this.backend = backend;
  43283. /**
  43284. * A reference to the rendering context.
  43285. *
  43286. * @type {WebGL2RenderingContext}
  43287. */
  43288. this.gl = backend.gl;
  43289. /**
  43290. * A reference to a backend module holding extension-related
  43291. * utility functions.
  43292. *
  43293. * @type {WebGLExtensions}
  43294. */
  43295. this.extensions = backend.extensions;
  43296. /**
  43297. * A dictionary for managing default textures. The key
  43298. * is the binding point (target), the value the WEbGL texture object.
  43299. *
  43300. * @type {Object<GLenum,WebGLTexture>}
  43301. */
  43302. this.defaultTextures = {};
  43303. if ( initialized === false ) {
  43304. this._init();
  43305. initialized = true;
  43306. }
  43307. }
  43308. /**
  43309. * Inits the state of the utility.
  43310. *
  43311. * @private
  43312. */
  43313. _init() {
  43314. const gl = this.gl;
  43315. // Store only WebGL constants here.
  43316. wrappingToGL = {
  43317. [ RepeatWrapping ]: gl.REPEAT,
  43318. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  43319. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  43320. };
  43321. filterToGL = {
  43322. [ NearestFilter ]: gl.NEAREST,
  43323. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  43324. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  43325. [ LinearFilter ]: gl.LINEAR,
  43326. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  43327. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  43328. };
  43329. compareToGL = {
  43330. [ NeverCompare ]: gl.NEVER,
  43331. [ AlwaysCompare ]: gl.ALWAYS,
  43332. [ LessCompare ]: gl.LESS,
  43333. [ LessEqualCompare ]: gl.LEQUAL,
  43334. [ EqualCompare ]: gl.EQUAL,
  43335. [ GreaterEqualCompare ]: gl.GEQUAL,
  43336. [ GreaterCompare ]: gl.GREATER,
  43337. [ NotEqualCompare ]: gl.NOTEQUAL
  43338. };
  43339. }
  43340. /**
  43341. * Returns the native texture type for the given texture.
  43342. *
  43343. * @param {Texture} texture - The texture.
  43344. * @return {GLenum} The native texture type.
  43345. */
  43346. getGLTextureType( texture ) {
  43347. const { gl } = this;
  43348. let glTextureType;
  43349. if ( texture.isCubeTexture === true ) {
  43350. glTextureType = gl.TEXTURE_CUBE_MAP;
  43351. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  43352. glTextureType = gl.TEXTURE_2D_ARRAY;
  43353. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  43354. glTextureType = gl.TEXTURE_3D;
  43355. } else {
  43356. glTextureType = gl.TEXTURE_2D;
  43357. }
  43358. return glTextureType;
  43359. }
  43360. /**
  43361. * Returns the native texture type for the given texture.
  43362. *
  43363. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  43364. * @param {GLenum} glFormat - The WebGL format.
  43365. * @param {GLenum} glType - The WebGL type.
  43366. * @param {string} colorSpace - The texture's color space.
  43367. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  43368. * @return {GLenum} The internal format.
  43369. */
  43370. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  43371. const { gl, extensions } = this;
  43372. if ( internalFormatName !== null ) {
  43373. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  43374. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  43375. }
  43376. let internalFormat = glFormat;
  43377. if ( glFormat === gl.RED ) {
  43378. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  43379. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  43380. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  43381. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  43382. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  43383. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  43384. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  43385. if ( glType === gl.INT ) internalFormat = gl.R32I;
  43386. }
  43387. if ( glFormat === gl.RED_INTEGER ) {
  43388. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  43389. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  43390. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  43391. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  43392. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  43393. if ( glType === gl.INT ) internalFormat = gl.R32I;
  43394. }
  43395. if ( glFormat === gl.RG ) {
  43396. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  43397. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  43398. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  43399. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  43400. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  43401. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  43402. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  43403. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  43404. }
  43405. if ( glFormat === gl.RG_INTEGER ) {
  43406. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  43407. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  43408. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  43409. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  43410. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  43411. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  43412. }
  43413. if ( glFormat === gl.RGB ) {
  43414. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  43415. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  43416. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  43417. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  43418. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  43419. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  43420. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  43421. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  43422. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  43423. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  43424. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  43425. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  43426. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  43427. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  43428. }
  43429. if ( glFormat === gl.RGB_INTEGER ) {
  43430. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  43431. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  43432. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  43433. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  43434. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  43435. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  43436. }
  43437. if ( glFormat === gl.RGBA ) {
  43438. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  43439. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  43440. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  43441. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  43442. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  43443. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  43444. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  43445. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  43446. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  43447. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  43448. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  43449. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  43450. }
  43451. if ( glFormat === gl.RGBA_INTEGER ) {
  43452. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  43453. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  43454. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  43455. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  43456. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  43457. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  43458. }
  43459. if ( glFormat === gl.DEPTH_COMPONENT ) {
  43460. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  43461. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  43462. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  43463. }
  43464. if ( glFormat === gl.DEPTH_STENCIL ) {
  43465. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  43466. }
  43467. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  43468. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  43469. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  43470. extensions.get( 'EXT_color_buffer_float' );
  43471. }
  43472. return internalFormat;
  43473. }
  43474. /**
  43475. * Sets the texture parameters for the given texture.
  43476. *
  43477. * @param {GLenum} textureType - The texture type.
  43478. * @param {Texture} texture - The texture.
  43479. */
  43480. setTextureParameters( textureType, texture ) {
  43481. const { gl, extensions, backend } = this;
  43482. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  43483. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  43484. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  43485. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  43486. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  43487. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  43488. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  43489. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  43490. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  43491. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  43492. // WebGL 2 does not support wrapping for depth 2D array textures
  43493. if ( ! texture.isArrayTexture ) {
  43494. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  43495. }
  43496. }
  43497. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  43498. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  43499. // follow WebGPU backend mapping for texture filtering
  43500. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  43501. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  43502. if ( texture.compareFunction ) {
  43503. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  43504. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  43505. }
  43506. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  43507. if ( texture.magFilter === NearestFilter ) return;
  43508. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  43509. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  43510. if ( texture.anisotropy > 1 ) {
  43511. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  43512. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  43513. }
  43514. }
  43515. }
  43516. /**
  43517. * Creates a default texture for the given texture that can be used
  43518. * as a placeholder until the actual texture is ready for usage.
  43519. *
  43520. * @param {Texture} texture - The texture to create a default texture for.
  43521. */
  43522. createDefaultTexture( texture ) {
  43523. const { gl, backend, defaultTextures } = this;
  43524. const glTextureType = this.getGLTextureType( texture );
  43525. let textureGPU = defaultTextures[ glTextureType ];
  43526. if ( textureGPU === undefined ) {
  43527. textureGPU = gl.createTexture();
  43528. backend.state.bindTexture( glTextureType, textureGPU );
  43529. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  43530. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  43531. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  43532. defaultTextures[ glTextureType ] = textureGPU;
  43533. }
  43534. backend.set( texture, {
  43535. textureGPU,
  43536. glTextureType,
  43537. isDefault: true
  43538. } );
  43539. }
  43540. /**
  43541. * Defines a texture on the GPU for the given texture object.
  43542. *
  43543. * @param {Texture} texture - The texture.
  43544. * @param {Object} [options={}] - Optional configuration parameter.
  43545. * @return {undefined}
  43546. */
  43547. createTexture( texture, options ) {
  43548. const { gl, backend } = this;
  43549. const { levels, width, height, depth } = options;
  43550. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  43551. const glType = backend.utils.convert( texture.type );
  43552. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  43553. const textureGPU = gl.createTexture();
  43554. const glTextureType = this.getGLTextureType( texture );
  43555. backend.state.bindTexture( glTextureType, textureGPU );
  43556. this.setTextureParameters( glTextureType, texture );
  43557. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  43558. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  43559. } else if ( texture.isData3DTexture ) {
  43560. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  43561. } else if ( ! texture.isVideoTexture ) {
  43562. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  43563. }
  43564. backend.set( texture, {
  43565. textureGPU,
  43566. glTextureType,
  43567. glFormat,
  43568. glType,
  43569. glInternalFormat
  43570. } );
  43571. }
  43572. /**
  43573. * Uploads texture buffer data to the GPU memory.
  43574. *
  43575. * @param {WebGLBuffer} buffer - The buffer data.
  43576. * @param {Texture} texture - The texture,
  43577. */
  43578. copyBufferToTexture( buffer, texture ) {
  43579. const { gl, backend } = this;
  43580. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  43581. const { width, height } = texture.source.data;
  43582. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  43583. backend.state.bindTexture( glTextureType, textureGPU );
  43584. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  43585. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  43586. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  43587. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  43588. backend.state.unbindTexture();
  43589. // debug
  43590. // const framebuffer = gl.createFramebuffer();
  43591. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  43592. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  43593. // const readout = new Float32Array( width * height * 4 );
  43594. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  43595. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  43596. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  43597. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  43598. // console.log( readout );
  43599. }
  43600. /**
  43601. * Uploads the updated texture data to the GPU.
  43602. *
  43603. * @param {Texture} texture - The texture.
  43604. * @param {Object} [options={}] - Optional configuration parameter.
  43605. */
  43606. updateTexture( texture, options ) {
  43607. const { gl } = this;
  43608. const { width, height } = options;
  43609. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  43610. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  43611. return;
  43612. this.backend.state.bindTexture( glTextureType, textureGPU );
  43613. this.setTextureParameters( glTextureType, texture );
  43614. if ( texture.isCompressedTexture ) {
  43615. const mipmaps = texture.mipmaps;
  43616. const image = options.image;
  43617. for ( let i = 0; i < mipmaps.length; i ++ ) {
  43618. const mipmap = mipmaps[ i ];
  43619. if ( texture.isCompressedArrayTexture ) {
  43620. if ( texture.format !== gl.RGBA ) {
  43621. if ( glFormat !== null ) {
  43622. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  43623. } else {
  43624. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  43625. }
  43626. } else {
  43627. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  43628. }
  43629. } else {
  43630. if ( glFormat !== null ) {
  43631. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  43632. } else {
  43633. console.warn( 'Unsupported compressed texture format' );
  43634. }
  43635. }
  43636. }
  43637. } else if ( texture.isCubeTexture ) {
  43638. const images = options.images;
  43639. for ( let i = 0; i < 6; i ++ ) {
  43640. const image = getImage( images[ i ] );
  43641. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  43642. }
  43643. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  43644. const image = options.image;
  43645. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  43646. } else if ( texture.isData3DTexture ) {
  43647. const image = options.image;
  43648. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  43649. } else if ( texture.isVideoTexture ) {
  43650. texture.update();
  43651. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  43652. } else {
  43653. const image = getImage( options.image );
  43654. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  43655. }
  43656. }
  43657. /**
  43658. * Generates mipmaps for the given texture.
  43659. *
  43660. * @param {Texture} texture - The texture.
  43661. */
  43662. generateMipmaps( texture ) {
  43663. const { gl, backend } = this;
  43664. const { textureGPU, glTextureType } = backend.get( texture );
  43665. backend.state.bindTexture( glTextureType, textureGPU );
  43666. gl.generateMipmap( glTextureType );
  43667. }
  43668. /**
  43669. * Deallocates the render buffers of the given render target.
  43670. *
  43671. * @param {RenderTarget} renderTarget - The render target.
  43672. */
  43673. deallocateRenderBuffers( renderTarget ) {
  43674. const { gl, backend } = this;
  43675. // remove framebuffer reference
  43676. if ( renderTarget ) {
  43677. const renderContextData = backend.get( renderTarget );
  43678. renderContextData.renderBufferStorageSetup = undefined;
  43679. if ( renderContextData.framebuffers ) {
  43680. for ( const cacheKey in renderContextData.framebuffers ) {
  43681. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  43682. }
  43683. delete renderContextData.framebuffers;
  43684. }
  43685. if ( renderContextData.depthRenderbuffer ) {
  43686. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  43687. delete renderContextData.depthRenderbuffer;
  43688. }
  43689. if ( renderContextData.stencilRenderbuffer ) {
  43690. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  43691. delete renderContextData.stencilRenderbuffer;
  43692. }
  43693. if ( renderContextData.msaaFrameBuffer ) {
  43694. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  43695. delete renderContextData.msaaFrameBuffer;
  43696. }
  43697. if ( renderContextData.msaaRenderbuffers ) {
  43698. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  43699. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  43700. }
  43701. delete renderContextData.msaaRenderbuffers;
  43702. }
  43703. }
  43704. }
  43705. /**
  43706. * Destroys the GPU data for the given texture object.
  43707. *
  43708. * @param {Texture} texture - The texture.
  43709. */
  43710. destroyTexture( texture ) {
  43711. const { gl, backend } = this;
  43712. const { textureGPU, renderTarget } = backend.get( texture );
  43713. this.deallocateRenderBuffers( renderTarget );
  43714. gl.deleteTexture( textureGPU );
  43715. backend.delete( texture );
  43716. }
  43717. /**
  43718. * Copies data of the given source texture to the given destination texture.
  43719. *
  43720. * @param {Texture} srcTexture - The source texture.
  43721. * @param {Texture} dstTexture - The destination texture.
  43722. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  43723. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  43724. * @param {number} [srcLevel=0] - The source mip level to copy from.
  43725. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  43726. */
  43727. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  43728. const { gl, backend } = this;
  43729. const { state } = this.backend;
  43730. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  43731. state.bindTexture( glTextureType, dstTextureGPU );
  43732. // gather the necessary dimensions to copy
  43733. let width, height, depth, minX, minY, minZ;
  43734. let dstX, dstY, dstZ;
  43735. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  43736. if ( srcRegion !== null ) {
  43737. width = srcRegion.max.x - srcRegion.min.x;
  43738. height = srcRegion.max.y - srcRegion.min.y;
  43739. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  43740. minX = srcRegion.min.x;
  43741. minY = srcRegion.min.y;
  43742. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  43743. } else {
  43744. const levelScale = Math.pow( 2, - srcLevel );
  43745. width = Math.floor( image.width * levelScale );
  43746. height = Math.floor( image.height * levelScale );
  43747. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  43748. depth = image.depth;
  43749. } else if ( srcTexture.isData3DTexture ) {
  43750. depth = Math.floor( image.depth * levelScale );
  43751. } else {
  43752. depth = 1;
  43753. }
  43754. minX = 0;
  43755. minY = 0;
  43756. minZ = 0;
  43757. }
  43758. if ( dstPosition !== null ) {
  43759. dstX = dstPosition.x;
  43760. dstY = dstPosition.y;
  43761. dstZ = dstPosition.z;
  43762. } else {
  43763. dstX = 0;
  43764. dstY = 0;
  43765. dstZ = 0;
  43766. }
  43767. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  43768. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  43769. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  43770. // used for copying data from cpu
  43771. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  43772. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  43773. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  43774. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  43775. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  43776. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  43777. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  43778. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  43779. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  43780. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  43781. // set up the src texture
  43782. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  43783. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  43784. const srcTextureData = backend.get( srcTexture );
  43785. const dstTextureData = backend.get( dstTexture );
  43786. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  43787. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  43788. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  43789. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  43790. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  43791. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  43792. let mask = gl.COLOR_BUFFER_BIT;
  43793. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  43794. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  43795. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  43796. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  43797. } else {
  43798. if ( isDst3D ) {
  43799. // copy data into the 3d texture
  43800. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  43801. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  43802. } else if ( dstTexture.isCompressedArrayTexture ) {
  43803. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  43804. } else {
  43805. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  43806. }
  43807. } else {
  43808. // copy data into the 2d texture
  43809. if ( srcTexture.isDataTexture ) {
  43810. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  43811. } else if ( srcTexture.isCompressedTexture ) {
  43812. gl.compressedTexSubImage2D( glTextureType, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  43813. } else {
  43814. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  43815. }
  43816. }
  43817. }
  43818. // reset values
  43819. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  43820. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  43821. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  43822. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  43823. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  43824. // Generate mipmaps only when copying level 0
  43825. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  43826. gl.generateMipmap( glTextureType );
  43827. }
  43828. state.unbindTexture();
  43829. }
  43830. /**
  43831. * Copies the current bound framebuffer to the given texture.
  43832. *
  43833. * @param {Texture} texture - The destination texture.
  43834. * @param {RenderContext} renderContext - The render context.
  43835. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  43836. */
  43837. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  43838. const { gl } = this;
  43839. const { state } = this.backend;
  43840. const { textureGPU } = this.backend.get( texture );
  43841. const { x, y, z: width, w: height } = rectangle;
  43842. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  43843. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  43844. if ( requireDrawFrameBuffer ) {
  43845. const partial = ( x !== 0 || y !== 0 );
  43846. let mask;
  43847. let attachment;
  43848. if ( texture.isDepthTexture === true ) {
  43849. mask = gl.DEPTH_BUFFER_BIT;
  43850. attachment = gl.DEPTH_ATTACHMENT;
  43851. if ( renderContext.stencil ) {
  43852. mask |= gl.STENCIL_BUFFER_BIT;
  43853. }
  43854. } else {
  43855. mask = gl.COLOR_BUFFER_BIT;
  43856. attachment = gl.COLOR_ATTACHMENT0;
  43857. }
  43858. if ( partial ) {
  43859. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  43860. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  43861. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  43862. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  43863. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  43864. const flippedY = srcHeight - y - height;
  43865. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  43866. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  43867. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  43868. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  43869. state.unbindTexture();
  43870. } else {
  43871. const fb = gl.createFramebuffer();
  43872. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  43873. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  43874. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  43875. gl.deleteFramebuffer( fb );
  43876. }
  43877. } else {
  43878. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  43879. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  43880. state.unbindTexture();
  43881. }
  43882. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  43883. this.backend._setFramebuffer( renderContext );
  43884. }
  43885. /**
  43886. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  43887. *
  43888. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  43889. * @param {RenderContext} renderContext - The render context.
  43890. * @param {number} samples - The MSAA sample count.
  43891. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  43892. */
  43893. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  43894. const { gl } = this;
  43895. const renderTarget = renderContext.renderTarget;
  43896. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  43897. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  43898. if ( depthBuffer && ! stencilBuffer ) {
  43899. let glInternalFormat = gl.DEPTH_COMPONENT24;
  43900. if ( useMultisampledRTT === true ) {
  43901. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  43902. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  43903. } else if ( samples > 0 ) {
  43904. if ( depthTexture && depthTexture.isDepthTexture ) {
  43905. if ( depthTexture.type === gl.FLOAT ) {
  43906. glInternalFormat = gl.DEPTH_COMPONENT32F;
  43907. }
  43908. }
  43909. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  43910. } else {
  43911. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  43912. }
  43913. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  43914. } else if ( depthBuffer && stencilBuffer ) {
  43915. if ( samples > 0 ) {
  43916. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  43917. } else {
  43918. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  43919. }
  43920. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  43921. }
  43922. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  43923. }
  43924. /**
  43925. * Returns texture data as a typed array.
  43926. *
  43927. * @async
  43928. * @param {Texture} texture - The texture to copy.
  43929. * @param {number} x - The x coordinate of the copy origin.
  43930. * @param {number} y - The y coordinate of the copy origin.
  43931. * @param {number} width - The width of the copy.
  43932. * @param {number} height - The height of the copy.
  43933. * @param {number} faceIndex - The face index.
  43934. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  43935. */
  43936. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  43937. const { backend, gl } = this;
  43938. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  43939. const fb = gl.createFramebuffer();
  43940. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  43941. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  43942. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  43943. const typedArrayType = this._getTypedArrayType( glType );
  43944. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  43945. const elementCount = width * height;
  43946. const byteLength = elementCount * bytesPerTexel;
  43947. const buffer = gl.createBuffer();
  43948. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  43949. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  43950. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  43951. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  43952. await backend.utils._clientWaitAsync();
  43953. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  43954. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  43955. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  43956. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  43957. gl.deleteFramebuffer( fb );
  43958. return dstBuffer;
  43959. }
  43960. /**
  43961. * Returns the corresponding typed array type for the given WebGL data type.
  43962. *
  43963. * @private
  43964. * @param {GLenum} glType - The WebGL data type.
  43965. * @return {TypedArray.constructor} The typed array type.
  43966. */
  43967. _getTypedArrayType( glType ) {
  43968. const { gl } = this;
  43969. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  43970. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  43971. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  43972. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  43973. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  43974. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  43975. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  43976. if ( glType === gl.FLOAT ) return Float32Array;
  43977. throw new Error( `Unsupported WebGL type: ${glType}` );
  43978. }
  43979. /**
  43980. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  43981. *
  43982. * @private
  43983. * @param {GLenum} glType - The WebGL data type.
  43984. * @param {GLenum} glFormat - The WebGL texture format.
  43985. * @return {number} The bytes-per-texel.
  43986. */
  43987. _getBytesPerTexel( glType, glFormat ) {
  43988. const { gl } = this;
  43989. let bytesPerComponent = 0;
  43990. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  43991. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  43992. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  43993. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  43994. glType === gl.UNSIGNED_SHORT ||
  43995. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  43996. if ( glType === gl.UNSIGNED_INT ||
  43997. glType === gl.FLOAT ) bytesPerComponent = 4;
  43998. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  43999. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  44000. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  44001. }
  44002. }
  44003. function getImage( source ) {
  44004. if ( source.isDataTexture ) {
  44005. return source.image.data;
  44006. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  44007. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  44008. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  44009. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  44010. return source;
  44011. }
  44012. return source.data;
  44013. }
  44014. /**
  44015. * A WebGL 2 backend utility module for managing extensions.
  44016. *
  44017. * @private
  44018. */
  44019. class WebGLExtensions {
  44020. /**
  44021. * Constructs a new utility object.
  44022. *
  44023. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44024. */
  44025. constructor( backend ) {
  44026. /**
  44027. * A reference to the WebGL 2 backend.
  44028. *
  44029. * @type {WebGLBackend}
  44030. */
  44031. this.backend = backend;
  44032. /**
  44033. * A reference to the rendering context.
  44034. *
  44035. * @type {WebGL2RenderingContext}
  44036. */
  44037. this.gl = this.backend.gl;
  44038. /**
  44039. * A list with all the supported WebGL extensions.
  44040. *
  44041. * @type {Array<string>}
  44042. */
  44043. this.availableExtensions = this.gl.getSupportedExtensions();
  44044. /**
  44045. * A dictionary with requested WebGL extensions.
  44046. * The key is the name of the extension, the value
  44047. * the requested extension object.
  44048. *
  44049. * @type {Object<string,Object>}
  44050. */
  44051. this.extensions = {};
  44052. }
  44053. /**
  44054. * Returns the extension object for the given extension name.
  44055. *
  44056. * @param {string} name - The extension name.
  44057. * @return {Object} The extension object.
  44058. */
  44059. get( name ) {
  44060. let extension = this.extensions[ name ];
  44061. if ( extension === undefined ) {
  44062. extension = this.gl.getExtension( name );
  44063. this.extensions[ name ] = extension;
  44064. }
  44065. return extension;
  44066. }
  44067. /**
  44068. * Returns `true` if the requested extension is available.
  44069. *
  44070. * @param {string} name - The extension name.
  44071. * @return {boolean} Whether the given extension is available or not.
  44072. */
  44073. has( name ) {
  44074. return this.availableExtensions.includes( name );
  44075. }
  44076. }
  44077. /**
  44078. * A WebGL 2 backend utility module for managing the device's capabilities.
  44079. *
  44080. * @private
  44081. */
  44082. class WebGLCapabilities {
  44083. /**
  44084. * Constructs a new utility object.
  44085. *
  44086. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44087. */
  44088. constructor( backend ) {
  44089. /**
  44090. * A reference to the WebGL 2 backend.
  44091. *
  44092. * @type {WebGLBackend}
  44093. */
  44094. this.backend = backend;
  44095. /**
  44096. * This value holds the cached max anisotropy value.
  44097. *
  44098. * @type {?number}
  44099. * @default null
  44100. */
  44101. this.maxAnisotropy = null;
  44102. }
  44103. /**
  44104. * Returns the maximum anisotropy texture filtering value. This value
  44105. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  44106. * WebGL extension.
  44107. *
  44108. * @return {number} The maximum anisotropy texture filtering value.
  44109. */
  44110. getMaxAnisotropy() {
  44111. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  44112. const gl = this.backend.gl;
  44113. const extensions = this.backend.extensions;
  44114. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44115. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44116. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  44117. } else {
  44118. this.maxAnisotropy = 0;
  44119. }
  44120. return this.maxAnisotropy;
  44121. }
  44122. }
  44123. const GLFeatureName = {
  44124. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  44125. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  44126. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  44127. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  44128. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  44129. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  44130. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  44131. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  44132. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  44133. 'OVR_multiview2': 'OVR_multiview2'
  44134. };
  44135. class WebGLBufferRenderer {
  44136. constructor( backend ) {
  44137. this.gl = backend.gl;
  44138. this.extensions = backend.extensions;
  44139. this.info = backend.renderer.info;
  44140. this.mode = null;
  44141. this.index = 0;
  44142. this.type = null;
  44143. this.object = null;
  44144. }
  44145. render( start, count ) {
  44146. const { gl, mode, object, type, info, index } = this;
  44147. if ( index !== 0 ) {
  44148. gl.drawElements( mode, count, type, start );
  44149. } else {
  44150. gl.drawArrays( mode, start, count );
  44151. }
  44152. info.update( object, count, 1 );
  44153. }
  44154. renderInstances( start, count, primcount ) {
  44155. const { gl, mode, type, index, object, info } = this;
  44156. if ( primcount === 0 ) return;
  44157. if ( index !== 0 ) {
  44158. gl.drawElementsInstanced( mode, count, type, start, primcount );
  44159. } else {
  44160. gl.drawArraysInstanced( mode, start, count, primcount );
  44161. }
  44162. info.update( object, count, primcount );
  44163. }
  44164. renderMultiDraw( starts, counts, drawCount ) {
  44165. const { extensions, mode, object, info } = this;
  44166. if ( drawCount === 0 ) return;
  44167. const extension = extensions.get( 'WEBGL_multi_draw' );
  44168. if ( extension === null ) {
  44169. for ( let i = 0; i < drawCount; i ++ ) {
  44170. this.render( starts[ i ], counts[ i ] );
  44171. }
  44172. } else {
  44173. if ( this.index !== 0 ) {
  44174. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  44175. } else {
  44176. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  44177. }
  44178. let elementCount = 0;
  44179. for ( let i = 0; i < drawCount; i ++ ) {
  44180. elementCount += counts[ i ];
  44181. }
  44182. info.update( object, elementCount, 1 );
  44183. }
  44184. }
  44185. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  44186. const { extensions, mode, object, info } = this;
  44187. if ( drawCount === 0 ) return;
  44188. const extension = extensions.get( 'WEBGL_multi_draw' );
  44189. if ( extension === null ) {
  44190. for ( let i = 0; i < drawCount; i ++ ) {
  44191. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  44192. }
  44193. } else {
  44194. if ( this.index !== 0 ) {
  44195. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  44196. } else {
  44197. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  44198. }
  44199. let elementCount = 0;
  44200. for ( let i = 0; i < drawCount; i ++ ) {
  44201. elementCount += counts[ i ] * primcount[ i ];
  44202. }
  44203. info.update( object, elementCount, 1 );
  44204. }
  44205. }
  44206. //
  44207. }
  44208. /**
  44209. * Abstract base class of a timestamp query pool.
  44210. *
  44211. * @abstract
  44212. */
  44213. class TimestampQueryPool {
  44214. /**
  44215. * Creates a new timestamp query pool.
  44216. *
  44217. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  44218. */
  44219. constructor( maxQueries = 256 ) {
  44220. /**
  44221. * Whether to track timestamps or not.
  44222. *
  44223. * @type {boolean}
  44224. * @default true
  44225. */
  44226. this.trackTimestamp = true;
  44227. /**
  44228. * Maximum number of queries this pool can hold.
  44229. *
  44230. * @type {number}
  44231. * @default 256
  44232. */
  44233. this.maxQueries = maxQueries;
  44234. /**
  44235. * How many queries allocated so far.
  44236. *
  44237. * @type {number}
  44238. * @default 0
  44239. */
  44240. this.currentQueryIndex = 0;
  44241. /**
  44242. * Tracks offsets for different contexts.
  44243. *
  44244. * @type {Map<string, number>}
  44245. */
  44246. this.queryOffsets = new Map();
  44247. /**
  44248. * Whether the pool has been disposed or not.
  44249. *
  44250. * @type {boolean}
  44251. * @default false
  44252. */
  44253. this.isDisposed = false;
  44254. /**
  44255. * TODO
  44256. *
  44257. * @type {number}
  44258. * @default 0
  44259. */
  44260. this.lastValue = 0;
  44261. /**
  44262. * TODO
  44263. *
  44264. * @type {boolean}
  44265. * @default false
  44266. */
  44267. this.pendingResolve = false;
  44268. }
  44269. /**
  44270. * Allocate queries for a specific renderContext.
  44271. *
  44272. * @abstract
  44273. * @param {Object} renderContext - The render context to allocate queries for.
  44274. * @returns {?number}
  44275. */
  44276. allocateQueriesForContext( /* renderContext */ ) {}
  44277. /**
  44278. * Resolve all timestamps and return data (or process them).
  44279. *
  44280. * @abstract
  44281. * @async
  44282. * @returns {Promise<number>|number} The resolved timestamp value.
  44283. */
  44284. async resolveQueriesAsync() {}
  44285. /**
  44286. * Dispose of the query pool.
  44287. *
  44288. * @abstract
  44289. */
  44290. dispose() {}
  44291. }
  44292. /**
  44293. * Manages a pool of WebGL timestamp queries for performance measurement.
  44294. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  44295. *
  44296. * @augments TimestampQueryPool
  44297. */
  44298. class WebGLTimestampQueryPool extends TimestampQueryPool {
  44299. /**
  44300. * Creates a new WebGL timestamp query pool.
  44301. *
  44302. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  44303. * @param {string} type - The type identifier for this query pool.
  44304. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  44305. */
  44306. constructor( gl, type, maxQueries = 2048 ) {
  44307. super( maxQueries );
  44308. this.gl = gl;
  44309. this.type = type;
  44310. // Check for timer query extensions
  44311. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  44312. gl.getExtension( 'EXT_disjoint_timer_query' );
  44313. if ( ! this.ext ) {
  44314. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  44315. this.trackTimestamp = false;
  44316. return;
  44317. }
  44318. // Create query objects
  44319. this.queries = [];
  44320. for ( let i = 0; i < this.maxQueries; i ++ ) {
  44321. this.queries.push( gl.createQuery() );
  44322. }
  44323. this.activeQuery = null;
  44324. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  44325. }
  44326. /**
  44327. * Allocates a pair of queries for a given render context.
  44328. *
  44329. * @param {Object} renderContext - The render context to allocate queries for.
  44330. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  44331. */
  44332. allocateQueriesForContext( renderContext ) {
  44333. if ( ! this.trackTimestamp ) return null;
  44334. // Check if we have enough space for a new query pair
  44335. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  44336. 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() } ).` );
  44337. return null;
  44338. }
  44339. const baseOffset = this.currentQueryIndex;
  44340. this.currentQueryIndex += 2;
  44341. // Initialize query states
  44342. this.queryStates.set( baseOffset, 'inactive' );
  44343. this.queryOffsets.set( renderContext.id, baseOffset );
  44344. return baseOffset;
  44345. }
  44346. /**
  44347. * Begins a timestamp query for the specified render context.
  44348. *
  44349. * @param {Object} renderContext - The render context to begin timing for.
  44350. */
  44351. beginQuery( renderContext ) {
  44352. if ( ! this.trackTimestamp || this.isDisposed ) {
  44353. return;
  44354. }
  44355. const baseOffset = this.queryOffsets.get( renderContext.id );
  44356. if ( baseOffset == null ) {
  44357. return;
  44358. }
  44359. // Don't start a new query if there's an active one
  44360. if ( this.activeQuery !== null ) {
  44361. return;
  44362. }
  44363. const query = this.queries[ baseOffset ];
  44364. if ( ! query ) {
  44365. return;
  44366. }
  44367. try {
  44368. // Only begin if query is inactive
  44369. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  44370. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  44371. this.activeQuery = baseOffset;
  44372. this.queryStates.set( baseOffset, 'started' );
  44373. }
  44374. } catch ( error ) {
  44375. console.error( 'Error in beginQuery:', error );
  44376. this.activeQuery = null;
  44377. this.queryStates.set( baseOffset, 'inactive' );
  44378. }
  44379. }
  44380. /**
  44381. * Ends the active timestamp query for the specified render context.
  44382. *
  44383. * @param {Object} renderContext - The render context to end timing for.
  44384. * @param {string} renderContext.id - Unique identifier for the render context.
  44385. */
  44386. endQuery( renderContext ) {
  44387. if ( ! this.trackTimestamp || this.isDisposed ) {
  44388. return;
  44389. }
  44390. const baseOffset = this.queryOffsets.get( renderContext.id );
  44391. if ( baseOffset == null ) {
  44392. return;
  44393. }
  44394. // Only end if this is the active query
  44395. if ( this.activeQuery !== baseOffset ) {
  44396. return;
  44397. }
  44398. try {
  44399. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  44400. this.queryStates.set( baseOffset, 'ended' );
  44401. this.activeQuery = null;
  44402. } catch ( error ) {
  44403. console.error( 'Error in endQuery:', error );
  44404. // Reset state on error
  44405. this.queryStates.set( baseOffset, 'inactive' );
  44406. this.activeQuery = null;
  44407. }
  44408. }
  44409. /**
  44410. * Asynchronously resolves all completed queries and returns the total duration.
  44411. *
  44412. * @async
  44413. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  44414. */
  44415. async resolveQueriesAsync() {
  44416. if ( ! this.trackTimestamp || this.pendingResolve ) {
  44417. return this.lastValue;
  44418. }
  44419. this.pendingResolve = true;
  44420. try {
  44421. // Wait for all ended queries to complete
  44422. const resolvePromises = [];
  44423. for ( const [ baseOffset, state ] of this.queryStates ) {
  44424. if ( state === 'ended' ) {
  44425. const query = this.queries[ baseOffset ];
  44426. resolvePromises.push( this.resolveQuery( query ) );
  44427. }
  44428. }
  44429. if ( resolvePromises.length === 0 ) {
  44430. return this.lastValue;
  44431. }
  44432. const results = await Promise.all( resolvePromises );
  44433. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  44434. // Store the last valid result
  44435. this.lastValue = totalDuration;
  44436. // Reset states
  44437. this.currentQueryIndex = 0;
  44438. this.queryOffsets.clear();
  44439. this.queryStates.clear();
  44440. this.activeQuery = null;
  44441. return totalDuration;
  44442. } catch ( error ) {
  44443. console.error( 'Error resolving queries:', error );
  44444. return this.lastValue;
  44445. } finally {
  44446. this.pendingResolve = false;
  44447. }
  44448. }
  44449. /**
  44450. * Resolves a single query, checking for completion and disjoint operation.
  44451. *
  44452. * @async
  44453. * @param {WebGLQuery} query - The query object to resolve.
  44454. * @returns {Promise<number>} The elapsed time in milliseconds.
  44455. */
  44456. async resolveQuery( query ) {
  44457. return new Promise( ( resolve ) => {
  44458. if ( this.isDisposed ) {
  44459. resolve( this.lastValue );
  44460. return;
  44461. }
  44462. let timeoutId;
  44463. let isResolved = false;
  44464. const cleanup = () => {
  44465. if ( timeoutId ) {
  44466. clearTimeout( timeoutId );
  44467. timeoutId = null;
  44468. }
  44469. };
  44470. const finalizeResolution = ( value ) => {
  44471. if ( ! isResolved ) {
  44472. isResolved = true;
  44473. cleanup();
  44474. resolve( value );
  44475. }
  44476. };
  44477. const checkQuery = () => {
  44478. if ( this.isDisposed ) {
  44479. finalizeResolution( this.lastValue );
  44480. return;
  44481. }
  44482. try {
  44483. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  44484. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  44485. if ( disjoint ) {
  44486. finalizeResolution( this.lastValue );
  44487. return;
  44488. }
  44489. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  44490. if ( ! available ) {
  44491. timeoutId = setTimeout( checkQuery, 1 );
  44492. return;
  44493. }
  44494. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  44495. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  44496. } catch ( error ) {
  44497. console.error( 'Error checking query:', error );
  44498. resolve( this.lastValue );
  44499. }
  44500. };
  44501. checkQuery();
  44502. } );
  44503. }
  44504. /**
  44505. * Releases all resources held by this query pool.
  44506. * This includes deleting all query objects and clearing internal state.
  44507. */
  44508. dispose() {
  44509. if ( this.isDisposed ) {
  44510. return;
  44511. }
  44512. this.isDisposed = true;
  44513. if ( ! this.trackTimestamp ) return;
  44514. for ( const query of this.queries ) {
  44515. this.gl.deleteQuery( query );
  44516. }
  44517. this.queries = [];
  44518. this.queryStates.clear();
  44519. this.queryOffsets.clear();
  44520. this.lastValue = 0;
  44521. this.activeQuery = null;
  44522. }
  44523. }
  44524. /**
  44525. * A backend implementation targeting WebGL 2.
  44526. *
  44527. * @private
  44528. * @augments Backend
  44529. */
  44530. class WebGLBackend extends Backend {
  44531. /**
  44532. * WebGLBackend options.
  44533. *
  44534. * @typedef {Object} WebGLBackend~Options
  44535. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  44536. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  44537. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  44538. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  44539. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  44540. * @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.
  44541. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  44542. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  44543. */
  44544. /**
  44545. * Constructs a new WebGPU backend.
  44546. *
  44547. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  44548. */
  44549. constructor( parameters = {} ) {
  44550. super( parameters );
  44551. /**
  44552. * This flag can be used for type testing.
  44553. *
  44554. * @type {boolean}
  44555. * @readonly
  44556. * @default true
  44557. */
  44558. this.isWebGLBackend = true;
  44559. /**
  44560. * A reference to a backend module holding shader attribute-related
  44561. * utility functions.
  44562. *
  44563. * @type {?WebGLAttributeUtils}
  44564. * @default null
  44565. */
  44566. this.attributeUtils = null;
  44567. /**
  44568. * A reference to a backend module holding extension-related
  44569. * utility functions.
  44570. *
  44571. * @type {?WebGLExtensions}
  44572. * @default null
  44573. */
  44574. this.extensions = null;
  44575. /**
  44576. * A reference to a backend module holding capability-related
  44577. * utility functions.
  44578. *
  44579. * @type {?WebGLCapabilities}
  44580. * @default null
  44581. */
  44582. this.capabilities = null;
  44583. /**
  44584. * A reference to a backend module holding texture-related
  44585. * utility functions.
  44586. *
  44587. * @type {?WebGLTextureUtils}
  44588. * @default null
  44589. */
  44590. this.textureUtils = null;
  44591. /**
  44592. * A reference to a backend module holding renderer-related
  44593. * utility functions.
  44594. *
  44595. * @type {?WebGLBufferRenderer}
  44596. * @default null
  44597. */
  44598. this.bufferRenderer = null;
  44599. /**
  44600. * A reference to the rendering context.
  44601. *
  44602. * @type {?WebGL2RenderingContext}
  44603. * @default null
  44604. */
  44605. this.gl = null;
  44606. /**
  44607. * A reference to a backend module holding state-related
  44608. * utility functions.
  44609. *
  44610. * @type {?WebGLState}
  44611. * @default null
  44612. */
  44613. this.state = null;
  44614. /**
  44615. * A reference to a backend module holding common
  44616. * utility functions.
  44617. *
  44618. * @type {?WebGLUtils}
  44619. * @default null
  44620. */
  44621. this.utils = null;
  44622. /**
  44623. * Dictionary for caching VAOs.
  44624. *
  44625. * @type {Object<string,WebGLVertexArrayObject>}
  44626. */
  44627. this.vaoCache = {};
  44628. /**
  44629. * Dictionary for caching transform feedback objects.
  44630. *
  44631. * @type {Object<string,WebGLTransformFeedback>}
  44632. */
  44633. this.transformFeedbackCache = {};
  44634. /**
  44635. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  44636. * Only relevant when using compute shaders.
  44637. *
  44638. * @type {boolean}
  44639. * @default false
  44640. */
  44641. this.discard = false;
  44642. /**
  44643. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  44644. * device does not support the extension.
  44645. *
  44646. * @type {?EXTDisjointTimerQueryWebGL2}
  44647. * @default null
  44648. */
  44649. this.disjoint = null;
  44650. /**
  44651. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  44652. * device does not support the extension.
  44653. *
  44654. * @type {?KHRParallelShaderCompile}
  44655. * @default null
  44656. */
  44657. this.parallel = null;
  44658. /**
  44659. * A reference to the current render context.
  44660. *
  44661. * @private
  44662. * @type {RenderContext}
  44663. * @default null
  44664. */
  44665. this._currentContext = null;
  44666. /**
  44667. * A unique collection of bindings.
  44668. *
  44669. * @private
  44670. * @type {WeakSet<Array<BindGroup>>}
  44671. */
  44672. this._knownBindings = new WeakSet();
  44673. /**
  44674. * Whether the device supports framebuffers invalidation or not.
  44675. *
  44676. * @private
  44677. * @type {boolean}
  44678. */
  44679. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  44680. /**
  44681. * The target framebuffer when rendering with
  44682. * the WebXR device API.
  44683. *
  44684. * @private
  44685. * @type {WebGLFramebuffer}
  44686. * @default null
  44687. */
  44688. this._xrFramebuffer = null;
  44689. }
  44690. /**
  44691. * Initializes the backend so it is ready for usage.
  44692. *
  44693. * @param {Renderer} renderer - The renderer.
  44694. */
  44695. init( renderer ) {
  44696. super.init( renderer );
  44697. //
  44698. const parameters = this.parameters;
  44699. const contextAttributes = {
  44700. antialias: renderer.samples > 0,
  44701. alpha: true, // always true for performance reasons
  44702. depth: renderer.depth,
  44703. stencil: renderer.stencil
  44704. };
  44705. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  44706. function onContextLost( event ) {
  44707. event.preventDefault();
  44708. const contextLossInfo = {
  44709. api: 'WebGL',
  44710. message: event.statusMessage || 'Unknown reason',
  44711. reason: null,
  44712. originalEvent: event
  44713. };
  44714. renderer.onDeviceLost( contextLossInfo );
  44715. }
  44716. this._onContextLost = onContextLost;
  44717. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  44718. this.gl = glContext;
  44719. this.extensions = new WebGLExtensions( this );
  44720. this.capabilities = new WebGLCapabilities( this );
  44721. this.attributeUtils = new WebGLAttributeUtils( this );
  44722. this.textureUtils = new WebGLTextureUtils( this );
  44723. this.bufferRenderer = new WebGLBufferRenderer( this );
  44724. this.state = new WebGLState( this );
  44725. this.utils = new WebGLUtils( this );
  44726. this.extensions.get( 'EXT_color_buffer_float' );
  44727. this.extensions.get( 'WEBGL_clip_cull_distance' );
  44728. this.extensions.get( 'OES_texture_float_linear' );
  44729. this.extensions.get( 'EXT_color_buffer_half_float' );
  44730. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  44731. this.extensions.get( 'WEBGL_render_shared_exponent' );
  44732. this.extensions.get( 'WEBGL_multi_draw' );
  44733. this.extensions.get( 'OVR_multiview2' );
  44734. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  44735. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  44736. }
  44737. /**
  44738. * The coordinate system of the backend.
  44739. *
  44740. * @type {number}
  44741. * @readonly
  44742. */
  44743. get coordinateSystem() {
  44744. return WebGLCoordinateSystem;
  44745. }
  44746. /**
  44747. * This method performs a readback operation by moving buffer data from
  44748. * a storage buffer attribute from the GPU to the CPU.
  44749. *
  44750. * @async
  44751. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  44752. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  44753. */
  44754. async getArrayBufferAsync( attribute ) {
  44755. return await this.attributeUtils.getArrayBufferAsync( attribute );
  44756. }
  44757. /**
  44758. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  44759. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  44760. *
  44761. * @async
  44762. * @return {Promise} A Promise that resolves when synchronization has been finished.
  44763. */
  44764. async waitForGPU() {
  44765. await this.utils._clientWaitAsync();
  44766. }
  44767. /**
  44768. * Ensures the backend is XR compatible.
  44769. *
  44770. * @async
  44771. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  44772. */
  44773. async makeXRCompatible() {
  44774. const attributes = this.gl.getContextAttributes();
  44775. if ( attributes.xrCompatible !== true ) {
  44776. await this.gl.makeXRCompatible();
  44777. }
  44778. }
  44779. /**
  44780. * Sets the XR rendering destination.
  44781. *
  44782. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  44783. */
  44784. setXRTarget( xrFramebuffer ) {
  44785. this._xrFramebuffer = xrFramebuffer;
  44786. }
  44787. /**
  44788. * Configures the given XR render target with external textures.
  44789. *
  44790. * This method is only relevant when using the WebXR Layers API.
  44791. *
  44792. * @param {XRRenderTarget} renderTarget - The XR render target.
  44793. * @param {WebGLTexture} colorTexture - A native color texture.
  44794. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  44795. */
  44796. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  44797. const gl = this.gl;
  44798. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  44799. if ( depthTexture !== null ) {
  44800. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  44801. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  44802. // The multisample_render_to_texture extension doesn't work properly if there
  44803. // are midframe flushes and an external depth texture.
  44804. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  44805. console.warn( 'THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  44806. }
  44807. renderTarget._autoAllocateDepthBuffer = false;
  44808. }
  44809. }
  44810. /**
  44811. * Inits a time stamp query for the given render context.
  44812. *
  44813. * @param {RenderContext} renderContext - The render context.
  44814. */
  44815. initTimestampQuery( renderContext ) {
  44816. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  44817. const type = renderContext.isComputeNode ? 'compute' : 'render';
  44818. if ( ! this.timestampQueryPool[ type ] ) {
  44819. // TODO: Variable maxQueries?
  44820. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  44821. }
  44822. const timestampQueryPool = this.timestampQueryPool[ type ];
  44823. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  44824. if ( baseOffset !== null ) {
  44825. timestampQueryPool.beginQuery( renderContext );
  44826. }
  44827. }
  44828. // timestamp utils
  44829. /**
  44830. * Prepares the timestamp buffer.
  44831. *
  44832. * @param {RenderContext} renderContext - The render context.
  44833. */
  44834. prepareTimestampBuffer( renderContext ) {
  44835. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  44836. const type = renderContext.isComputeNode ? 'compute' : 'render';
  44837. const timestampQueryPool = this.timestampQueryPool[ type ];
  44838. timestampQueryPool.endQuery( renderContext );
  44839. }
  44840. /**
  44841. * Returns the backend's rendering context.
  44842. *
  44843. * @return {WebGL2RenderingContext} The rendering context.
  44844. */
  44845. getContext() {
  44846. return this.gl;
  44847. }
  44848. /**
  44849. * This method is executed at the beginning of a render call and prepares
  44850. * the WebGL state for upcoming render calls
  44851. *
  44852. * @param {RenderContext} renderContext - The render context.
  44853. */
  44854. beginRender( renderContext ) {
  44855. const { state } = this;
  44856. const renderContextData = this.get( renderContext );
  44857. //
  44858. if ( renderContext.viewport ) {
  44859. this.updateViewport( renderContext );
  44860. } else {
  44861. const { width, height } = this.getDrawingBufferSize();
  44862. state.viewport( 0, 0, width, height );
  44863. }
  44864. if ( renderContext.scissor ) {
  44865. const { x, y, width, height } = renderContext.scissorValue;
  44866. state.scissor( x, renderContext.height - height - y, width, height );
  44867. }
  44868. //
  44869. this.initTimestampQuery( renderContext );
  44870. renderContextData.previousContext = this._currentContext;
  44871. this._currentContext = renderContext;
  44872. this._setFramebuffer( renderContext );
  44873. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  44874. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44875. if ( occlusionQueryCount > 0 ) {
  44876. // Get a reference to the array of objects with queries. The renderContextData property
  44877. // can be changed by another render pass before the async reading of all previous queries complete
  44878. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  44879. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  44880. renderContextData.lastOcclusionObject = null;
  44881. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  44882. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  44883. renderContextData.occlusionQueryIndex = 0;
  44884. }
  44885. }
  44886. /**
  44887. * This method is executed at the end of a render call and finalizes work
  44888. * after draw calls.
  44889. *
  44890. * @param {RenderContext} renderContext - The render context.
  44891. */
  44892. finishRender( renderContext ) {
  44893. const { gl, state } = this;
  44894. const renderContextData = this.get( renderContext );
  44895. const previousContext = renderContextData.previousContext;
  44896. state.resetVertexState();
  44897. const occlusionQueryCount = renderContext.occlusionQueryCount;
  44898. if ( occlusionQueryCount > 0 ) {
  44899. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  44900. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  44901. }
  44902. this.resolveOccludedAsync( renderContext );
  44903. }
  44904. const textures = renderContext.textures;
  44905. if ( textures !== null ) {
  44906. for ( let i = 0; i < textures.length; i ++ ) {
  44907. const texture = textures[ i ];
  44908. if ( texture.generateMipmaps ) {
  44909. this.generateMipmaps( texture );
  44910. }
  44911. }
  44912. }
  44913. this._currentContext = previousContext;
  44914. const renderTarget = renderContext.renderTarget;
  44915. if ( renderContext.textures !== null && renderTarget ) {
  44916. const renderTargetContextData = this.get( renderTarget );
  44917. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  44918. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  44919. let mask = gl.COLOR_BUFFER_BIT;
  44920. if ( renderTarget.resolveDepthBuffer ) {
  44921. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  44922. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  44923. }
  44924. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  44925. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  44926. const textures = renderContext.textures;
  44927. const isMRT = textures.length > 1;
  44928. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  44929. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  44930. if ( isMRT ) {
  44931. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  44932. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  44933. for ( let i = 0; i < textures.length; i ++ ) {
  44934. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  44935. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  44936. }
  44937. }
  44938. for ( let i = 0; i < textures.length; i ++ ) {
  44939. if ( isMRT ) {
  44940. // configure attachment for resolve
  44941. const { textureGPU } = this.get( textures[ i ] );
  44942. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  44943. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  44944. }
  44945. if ( renderContext.scissor ) {
  44946. const { x, y, width, height } = renderContext.scissorValue;
  44947. const viewY = renderContext.height - height - y;
  44948. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  44949. } else {
  44950. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  44951. }
  44952. }
  44953. if ( isMRT ) {
  44954. // restore attachments
  44955. for ( let i = 0; i < textures.length; i ++ ) {
  44956. const { textureGPU } = this.get( textures[ i ] );
  44957. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  44958. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  44959. }
  44960. }
  44961. if ( this._supportsInvalidateFramebuffer === true ) {
  44962. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  44963. }
  44964. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  44965. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  44966. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  44967. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  44968. }
  44969. }
  44970. if ( previousContext !== null ) {
  44971. this._setFramebuffer( previousContext );
  44972. if ( previousContext.viewport ) {
  44973. this.updateViewport( previousContext );
  44974. } else {
  44975. const { width, height } = this.getDrawingBufferSize();
  44976. state.viewport( 0, 0, width, height );
  44977. }
  44978. }
  44979. this.prepareTimestampBuffer( renderContext );
  44980. }
  44981. /**
  44982. * This method processes the result of occlusion queries and writes it
  44983. * into render context data.
  44984. *
  44985. * @async
  44986. * @param {RenderContext} renderContext - The render context.
  44987. */
  44988. resolveOccludedAsync( renderContext ) {
  44989. const renderContextData = this.get( renderContext );
  44990. // handle occlusion query results
  44991. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  44992. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  44993. const occluded = new WeakSet();
  44994. const { gl } = this;
  44995. renderContextData.currentOcclusionQueryObjects = null;
  44996. renderContextData.currentOcclusionQueries = null;
  44997. const check = () => {
  44998. let completed = 0;
  44999. // check all queries and requeue as appropriate
  45000. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  45001. const query = currentOcclusionQueries[ i ];
  45002. if ( query === null ) continue;
  45003. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  45004. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  45005. currentOcclusionQueries[ i ] = null;
  45006. gl.deleteQuery( query );
  45007. completed ++;
  45008. }
  45009. }
  45010. if ( completed < currentOcclusionQueries.length ) {
  45011. requestAnimationFrame( check );
  45012. } else {
  45013. renderContextData.occluded = occluded;
  45014. }
  45015. };
  45016. check();
  45017. }
  45018. }
  45019. /**
  45020. * Returns `true` if the given 3D object is fully occluded by other
  45021. * 3D objects in the scene.
  45022. *
  45023. * @param {RenderContext} renderContext - The render context.
  45024. * @param {Object3D} object - The 3D object to test.
  45025. * @return {boolean} Whether the 3D object is fully occluded or not.
  45026. */
  45027. isOccluded( renderContext, object ) {
  45028. const renderContextData = this.get( renderContext );
  45029. return renderContextData.occluded && renderContextData.occluded.has( object );
  45030. }
  45031. /**
  45032. * Updates the viewport with the values from the given render context.
  45033. *
  45034. * @param {RenderContext} renderContext - The render context.
  45035. */
  45036. updateViewport( renderContext ) {
  45037. const { state } = this;
  45038. const { x, y, width, height } = renderContext.viewportValue;
  45039. state.viewport( x, renderContext.height - height - y, width, height );
  45040. }
  45041. /**
  45042. * Defines the scissor test.
  45043. *
  45044. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  45045. */
  45046. setScissorTest( boolean ) {
  45047. const state = this.state;
  45048. state.setScissorTest( boolean );
  45049. }
  45050. /**
  45051. * Returns the clear color and alpha into a single
  45052. * color object.
  45053. *
  45054. * @return {Color4} The clear color.
  45055. */
  45056. getClearColor() {
  45057. const clearColor = super.getClearColor();
  45058. // Since the canvas is always created with alpha: true,
  45059. // WebGL must always premultiply the clear color.
  45060. clearColor.r *= clearColor.a;
  45061. clearColor.g *= clearColor.a;
  45062. clearColor.b *= clearColor.a;
  45063. return clearColor;
  45064. }
  45065. /**
  45066. * Performs a clear operation.
  45067. *
  45068. * @param {boolean} color - Whether the color buffer should be cleared or not.
  45069. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  45070. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  45071. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  45072. * @param {boolean} [setFrameBuffer=true] - TODO.
  45073. */
  45074. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  45075. const { gl, renderer } = this;
  45076. if ( descriptor === null ) {
  45077. const clearColor = this.getClearColor();
  45078. descriptor = {
  45079. textures: null,
  45080. clearColorValue: clearColor
  45081. };
  45082. }
  45083. //
  45084. let clear = 0;
  45085. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  45086. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  45087. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  45088. if ( clear !== 0 ) {
  45089. let clearColor;
  45090. if ( descriptor.clearColorValue ) {
  45091. clearColor = descriptor.clearColorValue;
  45092. } else {
  45093. clearColor = this.getClearColor();
  45094. }
  45095. const clearDepth = renderer.getClearDepth();
  45096. const clearStencil = renderer.getClearStencil();
  45097. if ( depth ) this.state.setDepthMask( true );
  45098. if ( descriptor.textures === null ) {
  45099. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  45100. gl.clear( clear );
  45101. } else {
  45102. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  45103. if ( color ) {
  45104. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  45105. if ( i === 0 ) {
  45106. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  45107. } else {
  45108. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  45109. }
  45110. }
  45111. }
  45112. if ( depth && stencil ) {
  45113. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  45114. } else if ( depth ) {
  45115. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  45116. } else if ( stencil ) {
  45117. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  45118. }
  45119. }
  45120. }
  45121. }
  45122. /**
  45123. * This method is executed at the beginning of a compute call and
  45124. * prepares the state for upcoming compute tasks.
  45125. *
  45126. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45127. */
  45128. beginCompute( computeGroup ) {
  45129. const { state, gl } = this;
  45130. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  45131. this.initTimestampQuery( computeGroup );
  45132. }
  45133. /**
  45134. * Executes a compute command for the given compute node.
  45135. *
  45136. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  45137. * @param {Node} computeNode - The compute node.
  45138. * @param {Array<BindGroup>} bindings - The bindings.
  45139. * @param {ComputePipeline} pipeline - The compute pipeline.
  45140. * @param {number|null} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  45141. */
  45142. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  45143. const { state, gl } = this;
  45144. if ( this.discard === false ) {
  45145. // required here to handle async behaviour of render.compute()
  45146. gl.enable( gl.RASTERIZER_DISCARD );
  45147. this.discard = true;
  45148. }
  45149. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  45150. const vaoKey = this._getVaoKey( attributes );
  45151. const vaoGPU = this.vaoCache[ vaoKey ];
  45152. if ( vaoGPU === undefined ) {
  45153. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  45154. } else {
  45155. state.setVertexState( vaoGPU );
  45156. }
  45157. state.useProgram( programGPU );
  45158. this._bindUniforms( bindings );
  45159. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  45160. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  45161. gl.beginTransformFeedback( gl.POINTS );
  45162. count = ( count !== null ) ? count : computeNode.count;
  45163. if ( Array.isArray( count ) ) {
  45164. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  45165. count = count[ 0 ];
  45166. }
  45167. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  45168. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  45169. } else {
  45170. gl.drawArrays( gl.POINTS, 0, count );
  45171. }
  45172. gl.endTransformFeedback();
  45173. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  45174. // switch active buffers
  45175. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  45176. const dualAttributeData = transformBuffers[ i ];
  45177. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  45178. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  45179. }
  45180. dualAttributeData.switchBuffers();
  45181. }
  45182. }
  45183. /**
  45184. * This method is executed at the end of a compute call and
  45185. * finalizes work after compute tasks.
  45186. *
  45187. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  45188. */
  45189. finishCompute( computeGroup ) {
  45190. const gl = this.gl;
  45191. this.discard = false;
  45192. gl.disable( gl.RASTERIZER_DISCARD );
  45193. this.prepareTimestampBuffer( computeGroup );
  45194. if ( this._currentContext ) {
  45195. this._setFramebuffer( this._currentContext );
  45196. }
  45197. }
  45198. /**
  45199. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  45200. *
  45201. * @param {RenderContext} renderContext - The render context.
  45202. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  45203. *
  45204. * @private
  45205. */
  45206. _isRenderCameraDepthArray( renderContext ) {
  45207. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  45208. }
  45209. /**
  45210. * Executes a draw command for the given render object.
  45211. *
  45212. * @param {RenderObject} renderObject - The render object to draw.
  45213. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  45214. */
  45215. draw( renderObject/*, info*/ ) {
  45216. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  45217. const { programGPU } = this.get( pipeline );
  45218. const { gl, state } = this;
  45219. const contextData = this.get( context );
  45220. const drawParams = renderObject.getDrawParameters();
  45221. if ( drawParams === null ) return;
  45222. //
  45223. this._bindUniforms( renderObject.getBindings() );
  45224. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  45225. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  45226. state.useProgram( programGPU );
  45227. // vertex state
  45228. const attributes = renderObject.getAttributes();
  45229. const attributesData = this.get( attributes );
  45230. let vaoGPU = attributesData.vaoGPU;
  45231. if ( vaoGPU === undefined ) {
  45232. const vaoKey = this._getVaoKey( attributes );
  45233. vaoGPU = this.vaoCache[ vaoKey ];
  45234. if ( vaoGPU === undefined ) {
  45235. vaoGPU = this._createVao( attributes );
  45236. this.vaoCache[ vaoKey ] = vaoGPU;
  45237. attributesData.vaoGPU = vaoGPU;
  45238. }
  45239. }
  45240. const index = renderObject.getIndex();
  45241. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  45242. state.setVertexState( vaoGPU, indexGPU );
  45243. //
  45244. const lastObject = contextData.lastOcclusionObject;
  45245. if ( lastObject !== object && lastObject !== undefined ) {
  45246. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  45247. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  45248. contextData.occlusionQueryIndex ++;
  45249. }
  45250. if ( object.occlusionTest === true ) {
  45251. const query = gl.createQuery();
  45252. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  45253. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  45254. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  45255. }
  45256. contextData.lastOcclusionObject = object;
  45257. }
  45258. //
  45259. const renderer = this.bufferRenderer;
  45260. if ( object.isPoints ) renderer.mode = gl.POINTS;
  45261. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  45262. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  45263. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  45264. else {
  45265. if ( material.wireframe === true ) {
  45266. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  45267. renderer.mode = gl.LINES;
  45268. } else {
  45269. renderer.mode = gl.TRIANGLES;
  45270. }
  45271. }
  45272. //
  45273. const { vertexCount, instanceCount } = drawParams;
  45274. let { firstVertex } = drawParams;
  45275. renderer.object = object;
  45276. if ( index !== null ) {
  45277. firstVertex *= index.array.BYTES_PER_ELEMENT;
  45278. const indexData = this.get( index );
  45279. renderer.index = index.count;
  45280. renderer.type = indexData.type;
  45281. } else {
  45282. renderer.index = 0;
  45283. }
  45284. const draw = () => {
  45285. if ( object.isBatchedMesh ) {
  45286. if ( object._multiDrawInstances !== null ) {
  45287. // @deprecated, r174
  45288. warnOnce( 'THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  45289. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  45290. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  45291. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  45292. } else {
  45293. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  45294. }
  45295. } else if ( instanceCount > 1 ) {
  45296. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  45297. } else {
  45298. renderer.render( firstVertex, vertexCount );
  45299. }
  45300. };
  45301. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  45302. const cameraData = this.get( renderObject.camera );
  45303. const cameras = renderObject.camera.cameras;
  45304. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  45305. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  45306. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  45307. const indexesGPU = [];
  45308. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  45309. const bufferGPU = gl.createBuffer();
  45310. data[ 0 ] = i;
  45311. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  45312. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  45313. indexesGPU.push( bufferGPU );
  45314. }
  45315. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  45316. }
  45317. const cameraIndexData = this.get( cameraIndex );
  45318. const pixelRatio = this.renderer.getPixelRatio();
  45319. const renderTarget = this._currentContext.renderTarget;
  45320. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  45321. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  45322. if ( isRenderCameraDepthArray ) {
  45323. // Clear the depth texture
  45324. const textureData = this.get( renderTarget.depthTexture );
  45325. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  45326. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  45327. const { stencilBuffer } = renderTarget;
  45328. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  45329. this.renderer._activeCubeFace = i;
  45330. this._currentContext.activeCubeFace = i;
  45331. this._setFramebuffer( this._currentContext );
  45332. this.clear( false, true, stencilBuffer, this._currentContext, false );
  45333. }
  45334. this.renderer._activeCubeFace = prevActiveCubeFace;
  45335. this._currentContext.activeCubeFace = prevActiveCubeFace;
  45336. }
  45337. }
  45338. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  45339. const subCamera = cameras[ i ];
  45340. if ( object.layers.test( subCamera.layers ) ) {
  45341. if ( isRenderCameraDepthArray ) {
  45342. // Update the active layer
  45343. this.renderer._activeCubeFace = i;
  45344. this._currentContext.activeCubeFace = i;
  45345. this._setFramebuffer( this._currentContext );
  45346. }
  45347. const vp = subCamera.viewport;
  45348. if ( vp !== undefined ) {
  45349. const x = vp.x * pixelRatio;
  45350. const y = vp.y * pixelRatio;
  45351. const width = vp.width * pixelRatio;
  45352. const height = vp.height * pixelRatio;
  45353. state.viewport(
  45354. Math.floor( x ),
  45355. Math.floor( renderObject.context.height - height - y ),
  45356. Math.floor( width ),
  45357. Math.floor( height )
  45358. );
  45359. }
  45360. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  45361. draw();
  45362. }
  45363. this._currentContext.activeCubeFace = prevActiveCubeFace;
  45364. this.renderer._activeCubeFace = prevActiveCubeFace;
  45365. }
  45366. } else {
  45367. draw();
  45368. }
  45369. }
  45370. /**
  45371. * Explain why always null is returned.
  45372. *
  45373. * @param {RenderObject} renderObject - The render object.
  45374. * @return {boolean} Whether the render pipeline requires an update or not.
  45375. */
  45376. needsRenderUpdate( /*renderObject*/ ) {
  45377. return false;
  45378. }
  45379. /**
  45380. * Explain why no cache key is computed.
  45381. *
  45382. * @param {RenderObject} renderObject - The render object.
  45383. * @return {string} The cache key.
  45384. */
  45385. getRenderCacheKey( /*renderObject*/ ) {
  45386. return '';
  45387. }
  45388. // textures
  45389. /**
  45390. * Creates a default texture for the given texture that can be used
  45391. * as a placeholder until the actual texture is ready for usage.
  45392. *
  45393. * @param {Texture} texture - The texture to create a default texture for.
  45394. */
  45395. createDefaultTexture( texture ) {
  45396. this.textureUtils.createDefaultTexture( texture );
  45397. }
  45398. /**
  45399. * Defines a texture on the GPU for the given texture object.
  45400. *
  45401. * @param {Texture} texture - The texture.
  45402. * @param {Object} [options={}] - Optional configuration parameter.
  45403. */
  45404. createTexture( texture, options ) {
  45405. this.textureUtils.createTexture( texture, options );
  45406. }
  45407. /**
  45408. * Uploads the updated texture data to the GPU.
  45409. *
  45410. * @param {Texture} texture - The texture.
  45411. * @param {Object} [options={}] - Optional configuration parameter.
  45412. */
  45413. updateTexture( texture, options ) {
  45414. this.textureUtils.updateTexture( texture, options );
  45415. }
  45416. /**
  45417. * Generates mipmaps for the given texture.
  45418. *
  45419. * @param {Texture} texture - The texture.
  45420. */
  45421. generateMipmaps( texture ) {
  45422. this.textureUtils.generateMipmaps( texture );
  45423. }
  45424. /**
  45425. * Destroys the GPU data for the given texture object.
  45426. *
  45427. * @param {Texture} texture - The texture.
  45428. */
  45429. destroyTexture( texture ) {
  45430. this.textureUtils.destroyTexture( texture );
  45431. }
  45432. /**
  45433. * Returns texture data as a typed array.
  45434. *
  45435. * @async
  45436. * @param {Texture} texture - The texture to copy.
  45437. * @param {number} x - The x coordinate of the copy origin.
  45438. * @param {number} y - The y coordinate of the copy origin.
  45439. * @param {number} width - The width of the copy.
  45440. * @param {number} height - The height of the copy.
  45441. * @param {number} faceIndex - The face index.
  45442. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  45443. */
  45444. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  45445. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  45446. }
  45447. /**
  45448. * This method does nothing since WebGL 2 has no concept of samplers.
  45449. *
  45450. * @param {Texture} texture - The texture to create the sampler for.
  45451. */
  45452. createSampler( /*texture*/ ) {
  45453. //console.warn( 'Abstract class.' );
  45454. }
  45455. /**
  45456. * This method does nothing since WebGL 2 has no concept of samplers.
  45457. *
  45458. * @param {Texture} texture - The texture to destroy the sampler for.
  45459. */
  45460. destroySampler( /*texture*/ ) {}
  45461. // node builder
  45462. /**
  45463. * Returns a node builder for the given render object.
  45464. *
  45465. * @param {RenderObject} object - The render object.
  45466. * @param {Renderer} renderer - The renderer.
  45467. * @return {GLSLNodeBuilder} The node builder.
  45468. */
  45469. createNodeBuilder( object, renderer ) {
  45470. return new GLSLNodeBuilder( object, renderer );
  45471. }
  45472. // program
  45473. /**
  45474. * Creates a shader program from the given programmable stage.
  45475. *
  45476. * @param {ProgrammableStage} program - The programmable stage.
  45477. */
  45478. createProgram( program ) {
  45479. const gl = this.gl;
  45480. const { stage, code } = program;
  45481. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  45482. gl.shaderSource( shader, code );
  45483. gl.compileShader( shader );
  45484. this.set( program, {
  45485. shaderGPU: shader
  45486. } );
  45487. }
  45488. /**
  45489. * Destroys the shader program of the given programmable stage.
  45490. *
  45491. * @param {ProgrammableStage} program - The programmable stage.
  45492. */
  45493. destroyProgram( program ) {
  45494. this.delete( program );
  45495. }
  45496. /**
  45497. * Creates a render pipeline for the given render object.
  45498. *
  45499. * @param {RenderObject} renderObject - The render object.
  45500. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  45501. */
  45502. createRenderPipeline( renderObject, promises ) {
  45503. const gl = this.gl;
  45504. const pipeline = renderObject.pipeline;
  45505. // Program
  45506. const { fragmentProgram, vertexProgram } = pipeline;
  45507. const programGPU = gl.createProgram();
  45508. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  45509. const vertexShader = this.get( vertexProgram ).shaderGPU;
  45510. gl.attachShader( programGPU, fragmentShader );
  45511. gl.attachShader( programGPU, vertexShader );
  45512. gl.linkProgram( programGPU );
  45513. this.set( pipeline, {
  45514. programGPU,
  45515. fragmentShader,
  45516. vertexShader
  45517. } );
  45518. if ( promises !== null && this.parallel ) {
  45519. const p = new Promise( ( resolve /*, reject*/ ) => {
  45520. const parallel = this.parallel;
  45521. const checkStatus = () => {
  45522. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  45523. this._completeCompile( renderObject, pipeline );
  45524. resolve();
  45525. } else {
  45526. requestAnimationFrame( checkStatus );
  45527. }
  45528. };
  45529. checkStatus();
  45530. } );
  45531. promises.push( p );
  45532. return;
  45533. }
  45534. this._completeCompile( renderObject, pipeline );
  45535. }
  45536. /**
  45537. * Formats the source code of error messages.
  45538. *
  45539. * @private
  45540. * @param {string} string - The code.
  45541. * @param {number} errorLine - The error line.
  45542. * @return {string} The formatted code.
  45543. */
  45544. _handleSource( string, errorLine ) {
  45545. const lines = string.split( '\n' );
  45546. const lines2 = [];
  45547. const from = Math.max( errorLine - 6, 0 );
  45548. const to = Math.min( errorLine + 6, lines.length );
  45549. for ( let i = from; i < to; i ++ ) {
  45550. const line = i + 1;
  45551. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  45552. }
  45553. return lines2.join( '\n' );
  45554. }
  45555. /**
  45556. * Gets the shader compilation errors from the info log.
  45557. *
  45558. * @private
  45559. * @param {WebGL2RenderingContext} gl - The rendering context.
  45560. * @param {WebGLShader} shader - The WebGL shader object.
  45561. * @param {string} type - The shader type.
  45562. * @return {string} The shader errors.
  45563. */
  45564. _getShaderErrors( gl, shader, type ) {
  45565. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  45566. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  45567. const errors = shaderInfoLog.trim();
  45568. if ( status && errors === '' ) return '';
  45569. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  45570. if ( errorMatches ) {
  45571. const errorLine = parseInt( errorMatches[ 1 ] );
  45572. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  45573. } else {
  45574. return errors;
  45575. }
  45576. }
  45577. /**
  45578. * Logs shader compilation errors.
  45579. *
  45580. * @private
  45581. * @param {WebGLProgram} programGPU - The WebGL program.
  45582. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  45583. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  45584. */
  45585. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  45586. if ( this.renderer.debug.checkShaderErrors ) {
  45587. const gl = this.gl;
  45588. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  45589. const programLog = programInfoLog.trim();
  45590. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  45591. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  45592. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  45593. } else {
  45594. // default error reporting
  45595. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  45596. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  45597. console.error(
  45598. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  45599. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  45600. 'Program Info Log: ' + programLog + '\n' +
  45601. vertexErrors + '\n' +
  45602. fragmentErrors
  45603. );
  45604. }
  45605. } else if ( programLog !== '' ) {
  45606. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  45607. }
  45608. }
  45609. }
  45610. /**
  45611. * Completes the shader program setup for the given render object.
  45612. *
  45613. * @private
  45614. * @param {RenderObject} renderObject - The render object.
  45615. * @param {RenderPipeline} pipeline - The render pipeline.
  45616. */
  45617. _completeCompile( renderObject, pipeline ) {
  45618. const { state, gl } = this;
  45619. const pipelineData = this.get( pipeline );
  45620. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  45621. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  45622. this._logProgramError( programGPU, fragmentShader, vertexShader );
  45623. }
  45624. state.useProgram( programGPU );
  45625. // Bindings
  45626. const bindings = renderObject.getBindings();
  45627. this._setupBindings( bindings, programGPU );
  45628. //
  45629. this.set( pipeline, {
  45630. programGPU
  45631. } );
  45632. }
  45633. /**
  45634. * Creates a compute pipeline for the given compute node.
  45635. *
  45636. * @param {ComputePipeline} computePipeline - The compute pipeline.
  45637. * @param {Array<BindGroup>} bindings - The bindings.
  45638. */
  45639. createComputePipeline( computePipeline, bindings ) {
  45640. const { state, gl } = this;
  45641. // Program
  45642. const fragmentProgram = {
  45643. stage: 'fragment',
  45644. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  45645. };
  45646. this.createProgram( fragmentProgram );
  45647. const { computeProgram } = computePipeline;
  45648. const programGPU = gl.createProgram();
  45649. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  45650. const vertexShader = this.get( computeProgram ).shaderGPU;
  45651. const transforms = computeProgram.transforms;
  45652. const transformVaryingNames = [];
  45653. const transformAttributeNodes = [];
  45654. for ( let i = 0; i < transforms.length; i ++ ) {
  45655. const transform = transforms[ i ];
  45656. transformVaryingNames.push( transform.varyingName );
  45657. transformAttributeNodes.push( transform.attributeNode );
  45658. }
  45659. gl.attachShader( programGPU, fragmentShader );
  45660. gl.attachShader( programGPU, vertexShader );
  45661. gl.transformFeedbackVaryings(
  45662. programGPU,
  45663. transformVaryingNames,
  45664. gl.SEPARATE_ATTRIBS
  45665. );
  45666. gl.linkProgram( programGPU );
  45667. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  45668. this._logProgramError( programGPU, fragmentShader, vertexShader );
  45669. }
  45670. state.useProgram( programGPU );
  45671. // Bindings
  45672. this._setupBindings( bindings, programGPU );
  45673. const attributeNodes = computeProgram.attributes;
  45674. const attributes = [];
  45675. const transformBuffers = [];
  45676. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  45677. const attribute = attributeNodes[ i ].node.attribute;
  45678. attributes.push( attribute );
  45679. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  45680. }
  45681. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  45682. const attribute = transformAttributeNodes[ i ].attribute;
  45683. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  45684. const attributeData = this.get( attribute );
  45685. transformBuffers.push( attributeData );
  45686. }
  45687. //
  45688. this.set( computePipeline, {
  45689. programGPU,
  45690. transformBuffers,
  45691. attributes
  45692. } );
  45693. }
  45694. /**
  45695. * Creates bindings from the given bind group definition.
  45696. *
  45697. * @param {BindGroup} bindGroup - The bind group.
  45698. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45699. * @param {number} cacheIndex - The cache index.
  45700. * @param {number} version - The version.
  45701. */
  45702. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  45703. if ( this._knownBindings.has( bindings ) === false ) {
  45704. this._knownBindings.add( bindings );
  45705. let uniformBuffers = 0;
  45706. let textures = 0;
  45707. for ( const bindGroup of bindings ) {
  45708. this.set( bindGroup, {
  45709. textures: textures,
  45710. uniformBuffers: uniformBuffers
  45711. } );
  45712. for ( const binding of bindGroup.bindings ) {
  45713. if ( binding.isUniformBuffer ) uniformBuffers ++;
  45714. if ( binding.isSampledTexture ) textures ++;
  45715. }
  45716. }
  45717. }
  45718. this.updateBindings( bindGroup, bindings );
  45719. }
  45720. /**
  45721. * Updates the given bind group definition.
  45722. *
  45723. * @param {BindGroup} bindGroup - The bind group.
  45724. * @param {Array<BindGroup>} bindings - Array of bind groups.
  45725. * @param {number} cacheIndex - The cache index.
  45726. * @param {number} version - The version.
  45727. */
  45728. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  45729. const { gl } = this;
  45730. const bindGroupData = this.get( bindGroup );
  45731. let i = bindGroupData.uniformBuffers;
  45732. let t = bindGroupData.textures;
  45733. for ( const binding of bindGroup.bindings ) {
  45734. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  45735. const data = binding.buffer;
  45736. const bufferGPU = gl.createBuffer();
  45737. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  45738. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  45739. this.set( binding, {
  45740. index: i ++,
  45741. bufferGPU
  45742. } );
  45743. } else if ( binding.isSampledTexture ) {
  45744. const { textureGPU, glTextureType } = this.get( binding.texture );
  45745. this.set( binding, {
  45746. index: t ++,
  45747. textureGPU,
  45748. glTextureType
  45749. } );
  45750. }
  45751. }
  45752. }
  45753. /**
  45754. * Updates a buffer binding.
  45755. *
  45756. * @param {Buffer} binding - The buffer binding to update.
  45757. */
  45758. updateBinding( binding ) {
  45759. const gl = this.gl;
  45760. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  45761. const bindingData = this.get( binding );
  45762. const bufferGPU = bindingData.bufferGPU;
  45763. const data = binding.buffer;
  45764. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  45765. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  45766. }
  45767. }
  45768. // attributes
  45769. /**
  45770. * Creates the GPU buffer of an indexed shader attribute.
  45771. *
  45772. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  45773. */
  45774. createIndexAttribute( attribute ) {
  45775. const gl = this.gl;
  45776. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  45777. }
  45778. /**
  45779. * Creates the GPU buffer of a shader attribute.
  45780. *
  45781. * @param {BufferAttribute} attribute - The buffer attribute.
  45782. */
  45783. createAttribute( attribute ) {
  45784. if ( this.has( attribute ) ) return;
  45785. const gl = this.gl;
  45786. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  45787. }
  45788. /**
  45789. * Creates the GPU buffer of a storage attribute.
  45790. *
  45791. * @param {BufferAttribute} attribute - The buffer attribute.
  45792. */
  45793. createStorageAttribute( attribute ) {
  45794. if ( this.has( attribute ) ) return;
  45795. const gl = this.gl;
  45796. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  45797. }
  45798. /**
  45799. * Updates the GPU buffer of a shader attribute.
  45800. *
  45801. * @param {BufferAttribute} attribute - The buffer attribute to update.
  45802. */
  45803. updateAttribute( attribute ) {
  45804. this.attributeUtils.updateAttribute( attribute );
  45805. }
  45806. /**
  45807. * Destroys the GPU buffer of a shader attribute.
  45808. *
  45809. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  45810. */
  45811. destroyAttribute( attribute ) {
  45812. this.attributeUtils.destroyAttribute( attribute );
  45813. }
  45814. /**
  45815. * Checks if the given feature is supported by the backend.
  45816. *
  45817. * @param {string} name - The feature's name.
  45818. * @return {boolean} Whether the feature is supported or not.
  45819. */
  45820. hasFeature( name ) {
  45821. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  45822. const extensions = this.extensions;
  45823. for ( let i = 0; i < keysMatching.length; i ++ ) {
  45824. if ( extensions.has( keysMatching[ i ] ) ) return true;
  45825. }
  45826. return false;
  45827. }
  45828. /**
  45829. * Returns the maximum anisotropy texture filtering value.
  45830. *
  45831. * @return {number} The maximum anisotropy texture filtering value.
  45832. */
  45833. getMaxAnisotropy() {
  45834. return this.capabilities.getMaxAnisotropy();
  45835. }
  45836. /**
  45837. * Copies data of the given source texture to the given destination texture.
  45838. *
  45839. * @param {Texture} srcTexture - The source texture.
  45840. * @param {Texture} dstTexture - The destination texture.
  45841. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  45842. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  45843. * @param {number} [srcLevel=0] - The source mip level to copy from.
  45844. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  45845. */
  45846. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  45847. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  45848. }
  45849. /**
  45850. * Copies the current bound framebuffer to the given texture.
  45851. *
  45852. * @param {Texture} texture - The destination texture.
  45853. * @param {RenderContext} renderContext - The render context.
  45854. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  45855. */
  45856. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  45857. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  45858. }
  45859. /**
  45860. * Configures the active framebuffer from the given render context.
  45861. *
  45862. * @private
  45863. * @param {RenderContext} descriptor - The render context.
  45864. */
  45865. _setFramebuffer( descriptor ) {
  45866. const { gl, state } = this;
  45867. let currentFrameBuffer = null;
  45868. if ( descriptor.textures !== null ) {
  45869. const renderTarget = descriptor.renderTarget;
  45870. const renderTargetContextData = this.get( renderTarget );
  45871. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  45872. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  45873. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  45874. const isRenderTargetArray = renderTarget.depth > 1;
  45875. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  45876. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  45877. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  45878. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  45879. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  45880. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  45881. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  45882. const cacheKey = getCacheKey( descriptor );
  45883. let fb;
  45884. if ( isCube ) {
  45885. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  45886. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  45887. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  45888. fb = this._xrFramebuffer;
  45889. } else {
  45890. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  45891. fb = renderTargetContextData.framebuffers[ cacheKey ];
  45892. }
  45893. if ( fb === undefined ) {
  45894. fb = gl.createFramebuffer();
  45895. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  45896. const textures = descriptor.textures;
  45897. const depthInvalidationArray = [];
  45898. if ( isCube ) {
  45899. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  45900. const { textureGPU } = this.get( textures[ 0 ] );
  45901. const cubeFace = this.renderer._activeCubeFace;
  45902. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  45903. } else {
  45904. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  45905. for ( let i = 0; i < textures.length; i ++ ) {
  45906. const texture = textures[ i ];
  45907. const textureData = this.get( texture );
  45908. textureData.renderTarget = descriptor.renderTarget;
  45909. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  45910. const attachment = gl.COLOR_ATTACHMENT0 + i;
  45911. if ( renderTarget.multiview ) {
  45912. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  45913. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  45914. const layer = this.renderer._activeCubeFace;
  45915. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  45916. } else {
  45917. if ( useMultisampledRTT ) {
  45918. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  45919. } else {
  45920. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  45921. }
  45922. }
  45923. }
  45924. }
  45925. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  45926. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  45927. const renderbuffer = gl.createRenderbuffer();
  45928. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  45929. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  45930. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  45931. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  45932. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  45933. } else {
  45934. if ( descriptor.depthTexture !== null ) {
  45935. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  45936. const textureData = this.get( descriptor.depthTexture );
  45937. textureData.renderTarget = descriptor.renderTarget;
  45938. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  45939. if ( renderTarget.multiview ) {
  45940. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  45941. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  45942. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  45943. } else {
  45944. if ( descriptor.depthTexture.isArrayTexture ) {
  45945. const layer = this.renderer._activeCubeFace;
  45946. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  45947. } else {
  45948. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  45949. }
  45950. }
  45951. }
  45952. }
  45953. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  45954. } else {
  45955. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  45956. if ( isRenderCameraDepthArray ) {
  45957. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  45958. const layer = this.renderer._activeCubeFace;
  45959. const depthData = this.get( descriptor.depthTexture );
  45960. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  45961. gl.framebufferTextureLayer(
  45962. gl.FRAMEBUFFER,
  45963. depthStyle,
  45964. depthData.textureGPU,
  45965. 0,
  45966. layer
  45967. );
  45968. }
  45969. // rebind external XR textures
  45970. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  45971. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  45972. // rebind color
  45973. const textureData = this.get( descriptor.textures[ 0 ] );
  45974. if ( renderTarget.multiview ) {
  45975. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  45976. } else if ( useMultisampledRTT ) {
  45977. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  45978. } else {
  45979. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  45980. }
  45981. // rebind depth
  45982. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  45983. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  45984. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  45985. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  45986. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  45987. } else {
  45988. const textureData = this.get( descriptor.depthTexture );
  45989. if ( renderTarget.multiview ) {
  45990. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  45991. } else if ( useMultisampledRTT ) {
  45992. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  45993. } else {
  45994. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  45995. }
  45996. }
  45997. }
  45998. }
  45999. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  46000. if ( msaaFb === undefined ) {
  46001. const invalidationArray = [];
  46002. msaaFb = gl.createFramebuffer();
  46003. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  46004. const msaaRenderbuffers = [];
  46005. const textures = descriptor.textures;
  46006. for ( let i = 0; i < textures.length; i ++ ) {
  46007. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  46008. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  46009. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  46010. const texture = descriptor.textures[ i ];
  46011. const textureData = this.get( texture );
  46012. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  46013. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  46014. }
  46015. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  46016. renderTargetContextData.msaaFrameBuffer = msaaFb;
  46017. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  46018. if ( depthBuffer && depthRenderbuffer === undefined ) {
  46019. depthRenderbuffer = gl.createRenderbuffer();
  46020. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  46021. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  46022. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  46023. invalidationArray.push( depthStyle );
  46024. }
  46025. renderTargetContextData.invalidationArray = invalidationArray;
  46026. }
  46027. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  46028. } else {
  46029. currentFrameBuffer = fb;
  46030. }
  46031. state.drawBuffers( descriptor, fb );
  46032. }
  46033. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  46034. }
  46035. /**
  46036. * Computes the VAO key for the given index and attributes.
  46037. *
  46038. * @private
  46039. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  46040. * @return {string} The VAO key.
  46041. */
  46042. _getVaoKey( attributes ) {
  46043. let key = '';
  46044. for ( let i = 0; i < attributes.length; i ++ ) {
  46045. const attributeData = this.get( attributes[ i ] );
  46046. key += ':' + attributeData.id;
  46047. }
  46048. return key;
  46049. }
  46050. /**
  46051. * Creates a VAO from the index and attributes.
  46052. *
  46053. * @private
  46054. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  46055. * @return {Object} The VAO data.
  46056. */
  46057. _createVao( attributes ) {
  46058. const { gl } = this;
  46059. const vaoGPU = gl.createVertexArray();
  46060. gl.bindVertexArray( vaoGPU );
  46061. for ( let i = 0; i < attributes.length; i ++ ) {
  46062. const attribute = attributes[ i ];
  46063. const attributeData = this.get( attribute );
  46064. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  46065. gl.enableVertexAttribArray( i );
  46066. let stride, offset;
  46067. if ( attribute.isInterleavedBufferAttribute === true ) {
  46068. stride = attribute.data.stride * attributeData.bytesPerElement;
  46069. offset = attribute.offset * attributeData.bytesPerElement;
  46070. } else {
  46071. stride = 0;
  46072. offset = 0;
  46073. }
  46074. if ( attributeData.isInteger ) {
  46075. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  46076. } else {
  46077. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  46078. }
  46079. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  46080. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  46081. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  46082. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  46083. }
  46084. }
  46085. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  46086. return vaoGPU;
  46087. }
  46088. /**
  46089. * Creates a transform feedback from the given transform buffers.
  46090. *
  46091. * @private
  46092. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  46093. * @return {WebGLTransformFeedback} The transform feedback.
  46094. */
  46095. _getTransformFeedback( transformBuffers ) {
  46096. let key = '';
  46097. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  46098. key += ':' + transformBuffers[ i ].id;
  46099. }
  46100. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  46101. if ( transformFeedbackGPU !== undefined ) {
  46102. return transformFeedbackGPU;
  46103. }
  46104. const { gl } = this;
  46105. transformFeedbackGPU = gl.createTransformFeedback();
  46106. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  46107. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  46108. const attributeData = transformBuffers[ i ];
  46109. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  46110. }
  46111. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  46112. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  46113. return transformFeedbackGPU;
  46114. }
  46115. /**
  46116. * Setups the given bindings.
  46117. *
  46118. * @private
  46119. * @param {Array<BindGroup>} bindings - The bindings.
  46120. * @param {WebGLProgram} programGPU - The WebGL program.
  46121. */
  46122. _setupBindings( bindings, programGPU ) {
  46123. const gl = this.gl;
  46124. for ( const bindGroup of bindings ) {
  46125. for ( const binding of bindGroup.bindings ) {
  46126. const bindingData = this.get( binding );
  46127. const index = bindingData.index;
  46128. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  46129. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  46130. gl.uniformBlockBinding( programGPU, location, index );
  46131. } else if ( binding.isSampledTexture ) {
  46132. const location = gl.getUniformLocation( programGPU, binding.name );
  46133. gl.uniform1i( location, index );
  46134. }
  46135. }
  46136. }
  46137. }
  46138. /**
  46139. * Binds the given uniforms.
  46140. *
  46141. * @private
  46142. * @param {Array<BindGroup>} bindings - The bindings.
  46143. */
  46144. _bindUniforms( bindings ) {
  46145. const { gl, state } = this;
  46146. for ( const bindGroup of bindings ) {
  46147. for ( const binding of bindGroup.bindings ) {
  46148. const bindingData = this.get( binding );
  46149. const index = bindingData.index;
  46150. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  46151. // TODO USE bindBufferRange to group multiple uniform buffers
  46152. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  46153. } else if ( binding.isSampledTexture ) {
  46154. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  46155. }
  46156. }
  46157. }
  46158. }
  46159. /**
  46160. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  46161. * should be used when MSAA is enabled.
  46162. *
  46163. * @private
  46164. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  46165. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  46166. */
  46167. _useMultisampledExtension( renderTarget ) {
  46168. if ( renderTarget.multiview === true ) {
  46169. return true;
  46170. }
  46171. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  46172. }
  46173. /**
  46174. * Frees internal resources.
  46175. */
  46176. dispose() {
  46177. const extension = this.extensions.get( 'WEBGL_lose_context' );
  46178. if ( extension ) extension.loseContext();
  46179. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  46180. }
  46181. }
  46182. const GPUPrimitiveTopology = {
  46183. PointList: 'point-list',
  46184. LineList: 'line-list',
  46185. LineStrip: 'line-strip',
  46186. TriangleList: 'triangle-list',
  46187. TriangleStrip: 'triangle-strip',
  46188. };
  46189. const GPUCompareFunction = {
  46190. Never: 'never',
  46191. Less: 'less',
  46192. Equal: 'equal',
  46193. LessEqual: 'less-equal',
  46194. Greater: 'greater',
  46195. NotEqual: 'not-equal',
  46196. GreaterEqual: 'greater-equal',
  46197. Always: 'always'
  46198. };
  46199. const GPUStoreOp = {
  46200. Store: 'store'};
  46201. const GPULoadOp = {
  46202. Load: 'load',
  46203. Clear: 'clear'
  46204. };
  46205. const GPUFrontFace = {
  46206. CCW: 'ccw'};
  46207. const GPUCullMode = {
  46208. None: 'none',
  46209. Front: 'front',
  46210. Back: 'back'
  46211. };
  46212. const GPUIndexFormat = {
  46213. Uint16: 'uint16',
  46214. Uint32: 'uint32'
  46215. };
  46216. const GPUTextureFormat = {
  46217. // 8-bit formats
  46218. R8Unorm: 'r8unorm',
  46219. R8Snorm: 'r8snorm',
  46220. R8Uint: 'r8uint',
  46221. R8Sint: 'r8sint',
  46222. // 16-bit formats
  46223. R16Uint: 'r16uint',
  46224. R16Sint: 'r16sint',
  46225. R16Float: 'r16float',
  46226. RG8Unorm: 'rg8unorm',
  46227. RG8Snorm: 'rg8snorm',
  46228. RG8Uint: 'rg8uint',
  46229. RG8Sint: 'rg8sint',
  46230. // 32-bit formats
  46231. R32Uint: 'r32uint',
  46232. R32Sint: 'r32sint',
  46233. R32Float: 'r32float',
  46234. RG16Uint: 'rg16uint',
  46235. RG16Sint: 'rg16sint',
  46236. RG16Float: 'rg16float',
  46237. RGBA8Unorm: 'rgba8unorm',
  46238. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  46239. RGBA8Snorm: 'rgba8snorm',
  46240. RGBA8Uint: 'rgba8uint',
  46241. RGBA8Sint: 'rgba8sint',
  46242. BGRA8Unorm: 'bgra8unorm',
  46243. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  46244. // Packed 32-bit formats
  46245. RGB9E5UFloat: 'rgb9e5ufloat',
  46246. RGB10A2Unorm: 'rgb10a2unorm',
  46247. RG11B10UFloat: 'rgb10a2unorm',
  46248. // 64-bit formats
  46249. RG32Uint: 'rg32uint',
  46250. RG32Sint: 'rg32sint',
  46251. RG32Float: 'rg32float',
  46252. RGBA16Uint: 'rgba16uint',
  46253. RGBA16Sint: 'rgba16sint',
  46254. RGBA16Float: 'rgba16float',
  46255. // 128-bit formats
  46256. RGBA32Uint: 'rgba32uint',
  46257. RGBA32Sint: 'rgba32sint',
  46258. RGBA32Float: 'rgba32float',
  46259. Depth16Unorm: 'depth16unorm',
  46260. Depth24Plus: 'depth24plus',
  46261. Depth24PlusStencil8: 'depth24plus-stencil8',
  46262. Depth32Float: 'depth32float',
  46263. // 'depth32float-stencil8' extension
  46264. Depth32FloatStencil8: 'depth32float-stencil8',
  46265. // BC compressed formats usable if 'texture-compression-bc' is both
  46266. // supported by the device/user agent and enabled in requestDevice.
  46267. BC1RGBAUnorm: 'bc1-rgba-unorm',
  46268. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  46269. BC2RGBAUnorm: 'bc2-rgba-unorm',
  46270. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  46271. BC3RGBAUnorm: 'bc3-rgba-unorm',
  46272. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  46273. BC4RUnorm: 'bc4-r-unorm',
  46274. BC4RSnorm: 'bc4-r-snorm',
  46275. BC5RGUnorm: 'bc5-rg-unorm',
  46276. BC5RGSnorm: 'bc5-rg-snorm',
  46277. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  46278. BC6HRGBFloat: 'bc6h-rgb-float',
  46279. BC7RGBAUnorm: 'bc7-rgba-unorm',
  46280. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  46281. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  46282. // supported by the device/user agent and enabled in requestDevice.
  46283. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  46284. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  46285. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  46286. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  46287. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  46288. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  46289. EACR11Unorm: 'eac-r11unorm',
  46290. EACR11Snorm: 'eac-r11snorm',
  46291. EACRG11Unorm: 'eac-rg11unorm',
  46292. EACRG11Snorm: 'eac-rg11snorm',
  46293. // ASTC compressed formats usable if 'texture-compression-astc' is both
  46294. // supported by the device/user agent and enabled in requestDevice.
  46295. ASTC4x4Unorm: 'astc-4x4-unorm',
  46296. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  46297. ASTC5x4Unorm: 'astc-5x4-unorm',
  46298. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  46299. ASTC5x5Unorm: 'astc-5x5-unorm',
  46300. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  46301. ASTC6x5Unorm: 'astc-6x5-unorm',
  46302. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  46303. ASTC6x6Unorm: 'astc-6x6-unorm',
  46304. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  46305. ASTC8x5Unorm: 'astc-8x5-unorm',
  46306. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  46307. ASTC8x6Unorm: 'astc-8x6-unorm',
  46308. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  46309. ASTC8x8Unorm: 'astc-8x8-unorm',
  46310. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  46311. ASTC10x5Unorm: 'astc-10x5-unorm',
  46312. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  46313. ASTC10x6Unorm: 'astc-10x6-unorm',
  46314. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  46315. ASTC10x8Unorm: 'astc-10x8-unorm',
  46316. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  46317. ASTC10x10Unorm: 'astc-10x10-unorm',
  46318. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  46319. ASTC12x10Unorm: 'astc-12x10-unorm',
  46320. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  46321. ASTC12x12Unorm: 'astc-12x12-unorm',
  46322. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  46323. };
  46324. const GPUAddressMode = {
  46325. ClampToEdge: 'clamp-to-edge',
  46326. Repeat: 'repeat',
  46327. MirrorRepeat: 'mirror-repeat'
  46328. };
  46329. const GPUFilterMode = {
  46330. Linear: 'linear',
  46331. Nearest: 'nearest'
  46332. };
  46333. const GPUBlendFactor = {
  46334. Zero: 'zero',
  46335. One: 'one',
  46336. Src: 'src',
  46337. OneMinusSrc: 'one-minus-src',
  46338. SrcAlpha: 'src-alpha',
  46339. OneMinusSrcAlpha: 'one-minus-src-alpha',
  46340. Dst: 'dst',
  46341. OneMinusDst: 'one-minus-dst',
  46342. DstAlpha: 'dst-alpha',
  46343. OneMinusDstAlpha: 'one-minus-dst-alpha',
  46344. SrcAlphaSaturated: 'src-alpha-saturated',
  46345. Constant: 'constant',
  46346. OneMinusConstant: 'one-minus-constant'
  46347. };
  46348. const GPUBlendOperation = {
  46349. Add: 'add',
  46350. Subtract: 'subtract',
  46351. ReverseSubtract: 'reverse-subtract',
  46352. Min: 'min',
  46353. Max: 'max'
  46354. };
  46355. const GPUColorWriteFlags = {
  46356. None: 0,
  46357. All: 0xF
  46358. };
  46359. const GPUStencilOperation = {
  46360. Keep: 'keep',
  46361. Zero: 'zero',
  46362. Replace: 'replace',
  46363. Invert: 'invert',
  46364. IncrementClamp: 'increment-clamp',
  46365. DecrementClamp: 'decrement-clamp',
  46366. IncrementWrap: 'increment-wrap',
  46367. DecrementWrap: 'decrement-wrap'
  46368. };
  46369. const GPUBufferBindingType = {
  46370. Storage: 'storage',
  46371. ReadOnlyStorage: 'read-only-storage'
  46372. };
  46373. const GPUStorageTextureAccess = {
  46374. WriteOnly: 'write-only',
  46375. ReadOnly: 'read-only',
  46376. ReadWrite: 'read-write',
  46377. };
  46378. const GPUSamplerBindingType = {
  46379. NonFiltering: 'non-filtering',
  46380. Comparison: 'comparison'
  46381. };
  46382. const GPUTextureSampleType = {
  46383. Float: 'float',
  46384. UnfilterableFloat: 'unfilterable-float',
  46385. Depth: 'depth',
  46386. SInt: 'sint',
  46387. UInt: 'uint'
  46388. };
  46389. const GPUTextureDimension = {
  46390. TwoD: '2d',
  46391. ThreeD: '3d'
  46392. };
  46393. const GPUTextureViewDimension = {
  46394. TwoD: '2d',
  46395. TwoDArray: '2d-array',
  46396. Cube: 'cube',
  46397. ThreeD: '3d'
  46398. };
  46399. const GPUTextureAspect = {
  46400. All: 'all'};
  46401. const GPUInputStepMode = {
  46402. Vertex: 'vertex',
  46403. Instance: 'instance'
  46404. };
  46405. const GPUFeatureName = {
  46406. CoreFeaturesAndLimits: 'core-features-and-limits',
  46407. DepthClipControl: 'depth-clip-control',
  46408. Depth32FloatStencil8: 'depth32float-stencil8',
  46409. TextureCompressionBC: 'texture-compression-bc',
  46410. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  46411. TextureCompressionETC2: 'texture-compression-etc2',
  46412. TextureCompressionASTC: 'texture-compression-astc',
  46413. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  46414. TimestampQuery: 'timestamp-query',
  46415. IndirectFirstInstance: 'indirect-first-instance',
  46416. ShaderF16: 'shader-f16',
  46417. RG11B10UFloat: 'rg11b10ufloat-renderable',
  46418. BGRA8UNormStorage: 'bgra8unorm-storage',
  46419. Float32Filterable: 'float32-filterable',
  46420. Float32Blendable: 'float32-blendable',
  46421. ClipDistances: 'clip-distances',
  46422. DualSourceBlending: 'dual-source-blending',
  46423. Subgroups: 'subgroups',
  46424. TextureFormatsTier1: 'texture-formats-tier1',
  46425. TextureFormatsTier2: 'texture-formats-tier2'
  46426. };
  46427. /**
  46428. * A special form of sampler binding type.
  46429. * It's texture value is managed by a node object.
  46430. *
  46431. * @private
  46432. * @augments Sampler
  46433. */
  46434. class NodeSampler extends Sampler {
  46435. /**
  46436. * Constructs a new node-based sampler.
  46437. *
  46438. * @param {string} name - The samplers's name.
  46439. * @param {TextureNode} textureNode - The texture node.
  46440. * @param {UniformGroupNode} groupNode - The uniform group node.
  46441. */
  46442. constructor( name, textureNode, groupNode ) {
  46443. super( name, textureNode ? textureNode.value : null );
  46444. /**
  46445. * The texture node.
  46446. *
  46447. * @type {TextureNode}
  46448. */
  46449. this.textureNode = textureNode;
  46450. /**
  46451. * The uniform group node.
  46452. *
  46453. * @type {UniformGroupNode}
  46454. */
  46455. this.groupNode = groupNode;
  46456. }
  46457. /**
  46458. * Updates the texture value of this sampler.
  46459. */
  46460. update() {
  46461. this.texture = this.textureNode.value;
  46462. }
  46463. }
  46464. /**
  46465. * Represents a storage buffer binding type.
  46466. *
  46467. * @private
  46468. * @augments Buffer
  46469. */
  46470. class StorageBuffer extends Buffer {
  46471. /**
  46472. * Constructs a new uniform buffer.
  46473. *
  46474. * @param {string} name - The buffer's name.
  46475. * @param {BufferAttribute} attribute - The buffer attribute.
  46476. */
  46477. constructor( name, attribute ) {
  46478. super( name, attribute ? attribute.array : null );
  46479. /**
  46480. * This flag can be used for type testing.
  46481. *
  46482. * @type {BufferAttribute}
  46483. */
  46484. this.attribute = attribute;
  46485. /**
  46486. * This flag can be used for type testing.
  46487. *
  46488. * @type {boolean}
  46489. * @readonly
  46490. * @default true
  46491. */
  46492. this.isStorageBuffer = true;
  46493. }
  46494. }
  46495. let _id = 0;
  46496. /**
  46497. * A special form of storage buffer binding type.
  46498. * It's buffer value is managed by a node object.
  46499. *
  46500. * @private
  46501. * @augments StorageBuffer
  46502. */
  46503. class NodeStorageBuffer extends StorageBuffer {
  46504. /**
  46505. * Constructs a new node-based storage buffer.
  46506. *
  46507. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  46508. * @param {UniformGroupNode} groupNode - The uniform group node.
  46509. */
  46510. constructor( nodeUniform, groupNode ) {
  46511. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  46512. /**
  46513. * The node uniform.
  46514. *
  46515. * @type {StorageBufferNode}
  46516. */
  46517. this.nodeUniform = nodeUniform;
  46518. /**
  46519. * The access type.
  46520. *
  46521. * @type {string}
  46522. */
  46523. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  46524. /**
  46525. * The uniform group node.
  46526. *
  46527. * @type {UniformGroupNode}
  46528. */
  46529. this.groupNode = groupNode;
  46530. }
  46531. /**
  46532. * The storage buffer.
  46533. *
  46534. * @type {BufferAttribute}
  46535. */
  46536. get buffer() {
  46537. return this.nodeUniform.value;
  46538. }
  46539. }
  46540. /**
  46541. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  46542. *
  46543. * @private
  46544. */
  46545. class WebGPUTexturePassUtils extends DataMap {
  46546. /**
  46547. * Constructs a new utility object.
  46548. *
  46549. * @param {GPUDevice} device - The WebGPU device.
  46550. */
  46551. constructor( device ) {
  46552. super();
  46553. /**
  46554. * The WebGPU device.
  46555. *
  46556. * @type {GPUDevice}
  46557. */
  46558. this.device = device;
  46559. const mipmapVertexSource = `
  46560. struct VarysStruct {
  46561. @builtin( position ) Position: vec4<f32>,
  46562. @location( 0 ) vTex : vec2<f32>
  46563. };
  46564. @vertex
  46565. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  46566. var Varys : VarysStruct;
  46567. var pos = array< vec2<f32>, 4 >(
  46568. vec2<f32>( -1.0, 1.0 ),
  46569. vec2<f32>( 1.0, 1.0 ),
  46570. vec2<f32>( -1.0, -1.0 ),
  46571. vec2<f32>( 1.0, -1.0 )
  46572. );
  46573. var tex = array< vec2<f32>, 4 >(
  46574. vec2<f32>( 0.0, 0.0 ),
  46575. vec2<f32>( 1.0, 0.0 ),
  46576. vec2<f32>( 0.0, 1.0 ),
  46577. vec2<f32>( 1.0, 1.0 )
  46578. );
  46579. Varys.vTex = tex[ vertexIndex ];
  46580. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  46581. return Varys;
  46582. }
  46583. `;
  46584. const mipmapFragmentSource = `
  46585. @group( 0 ) @binding( 0 )
  46586. var imgSampler : sampler;
  46587. @group( 0 ) @binding( 1 )
  46588. var img : texture_2d<f32>;
  46589. @fragment
  46590. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  46591. return textureSample( img, imgSampler, vTex );
  46592. }
  46593. `;
  46594. const flipYFragmentSource = `
  46595. @group( 0 ) @binding( 0 )
  46596. var imgSampler : sampler;
  46597. @group( 0 ) @binding( 1 )
  46598. var img : texture_2d<f32>;
  46599. @fragment
  46600. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  46601. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  46602. }
  46603. `;
  46604. /**
  46605. * The mipmap GPU sampler.
  46606. *
  46607. * @type {GPUSampler}
  46608. */
  46609. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  46610. /**
  46611. * The flipY GPU sampler.
  46612. *
  46613. * @type {GPUSampler}
  46614. */
  46615. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  46616. /**
  46617. * A cache for GPU render pipelines used for copy/transfer passes.
  46618. * Every texture format requires a unique pipeline.
  46619. *
  46620. * @type {Object<string,GPURenderPipeline>}
  46621. */
  46622. this.transferPipelines = {};
  46623. /**
  46624. * A cache for GPU render pipelines used for flipY passes.
  46625. * Every texture format requires a unique pipeline.
  46626. *
  46627. * @type {Object<string,GPURenderPipeline>}
  46628. */
  46629. this.flipYPipelines = {};
  46630. /**
  46631. * The mipmap vertex shader module.
  46632. *
  46633. * @type {GPUShaderModule}
  46634. */
  46635. this.mipmapVertexShaderModule = device.createShaderModule( {
  46636. label: 'mipmapVertex',
  46637. code: mipmapVertexSource
  46638. } );
  46639. /**
  46640. * The mipmap fragment shader module.
  46641. *
  46642. * @type {GPUShaderModule}
  46643. */
  46644. this.mipmapFragmentShaderModule = device.createShaderModule( {
  46645. label: 'mipmapFragment',
  46646. code: mipmapFragmentSource
  46647. } );
  46648. /**
  46649. * The flipY fragment shader module.
  46650. *
  46651. * @type {GPUShaderModule}
  46652. */
  46653. this.flipYFragmentShaderModule = device.createShaderModule( {
  46654. label: 'flipYFragment',
  46655. code: flipYFragmentSource
  46656. } );
  46657. }
  46658. /**
  46659. * Returns a render pipeline for the internal copy render pass. The pass
  46660. * requires a unique render pipeline for each texture format.
  46661. *
  46662. * @param {string} format - The GPU texture format
  46663. * @return {GPURenderPipeline} The GPU render pipeline.
  46664. */
  46665. getTransferPipeline( format ) {
  46666. let pipeline = this.transferPipelines[ format ];
  46667. if ( pipeline === undefined ) {
  46668. pipeline = this.device.createRenderPipeline( {
  46669. label: `mipmap-${ format }`,
  46670. vertex: {
  46671. module: this.mipmapVertexShaderModule,
  46672. entryPoint: 'main'
  46673. },
  46674. fragment: {
  46675. module: this.mipmapFragmentShaderModule,
  46676. entryPoint: 'main',
  46677. targets: [ { format } ]
  46678. },
  46679. primitive: {
  46680. topology: GPUPrimitiveTopology.TriangleStrip,
  46681. stripIndexFormat: GPUIndexFormat.Uint32
  46682. },
  46683. layout: 'auto'
  46684. } );
  46685. this.transferPipelines[ format ] = pipeline;
  46686. }
  46687. return pipeline;
  46688. }
  46689. /**
  46690. * Returns a render pipeline for the flipY render pass. The pass
  46691. * requires a unique render pipeline for each texture format.
  46692. *
  46693. * @param {string} format - The GPU texture format
  46694. * @return {GPURenderPipeline} The GPU render pipeline.
  46695. */
  46696. getFlipYPipeline( format ) {
  46697. let pipeline = this.flipYPipelines[ format ];
  46698. if ( pipeline === undefined ) {
  46699. pipeline = this.device.createRenderPipeline( {
  46700. label: `flipY-${ format }`,
  46701. vertex: {
  46702. module: this.mipmapVertexShaderModule,
  46703. entryPoint: 'main'
  46704. },
  46705. fragment: {
  46706. module: this.flipYFragmentShaderModule,
  46707. entryPoint: 'main',
  46708. targets: [ { format } ]
  46709. },
  46710. primitive: {
  46711. topology: GPUPrimitiveTopology.TriangleStrip,
  46712. stripIndexFormat: GPUIndexFormat.Uint32
  46713. },
  46714. layout: 'auto'
  46715. } );
  46716. this.flipYPipelines[ format ] = pipeline;
  46717. }
  46718. return pipeline;
  46719. }
  46720. /**
  46721. * Flip the contents of the given GPU texture along its vertical axis.
  46722. *
  46723. * @param {GPUTexture} textureGPU - The GPU texture object.
  46724. * @param {Object} textureGPUDescriptor - The texture descriptor.
  46725. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  46726. */
  46727. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  46728. const format = textureGPUDescriptor.format;
  46729. const { width, height } = textureGPUDescriptor.size;
  46730. const transferPipeline = this.getTransferPipeline( format );
  46731. const flipYPipeline = this.getFlipYPipeline( format );
  46732. const tempTexture = this.device.createTexture( {
  46733. size: { width, height, depthOrArrayLayers: 1 },
  46734. format,
  46735. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  46736. } );
  46737. const srcView = textureGPU.createView( {
  46738. baseMipLevel: 0,
  46739. mipLevelCount: 1,
  46740. dimension: GPUTextureViewDimension.TwoD,
  46741. baseArrayLayer
  46742. } );
  46743. const dstView = tempTexture.createView( {
  46744. baseMipLevel: 0,
  46745. mipLevelCount: 1,
  46746. dimension: GPUTextureViewDimension.TwoD,
  46747. baseArrayLayer: 0
  46748. } );
  46749. const commandEncoder = this.device.createCommandEncoder( {} );
  46750. const pass = ( pipeline, sourceView, destinationView ) => {
  46751. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  46752. const bindGroup = this.device.createBindGroup( {
  46753. layout: bindGroupLayout,
  46754. entries: [ {
  46755. binding: 0,
  46756. resource: this.flipYSampler
  46757. }, {
  46758. binding: 1,
  46759. resource: sourceView
  46760. } ]
  46761. } );
  46762. const passEncoder = commandEncoder.beginRenderPass( {
  46763. colorAttachments: [ {
  46764. view: destinationView,
  46765. loadOp: GPULoadOp.Clear,
  46766. storeOp: GPUStoreOp.Store,
  46767. clearValue: [ 0, 0, 0, 0 ]
  46768. } ]
  46769. } );
  46770. passEncoder.setPipeline( pipeline );
  46771. passEncoder.setBindGroup( 0, bindGroup );
  46772. passEncoder.draw( 4, 1, 0, 0 );
  46773. passEncoder.end();
  46774. };
  46775. pass( transferPipeline, srcView, dstView );
  46776. pass( flipYPipeline, dstView, srcView );
  46777. this.device.queue.submit( [ commandEncoder.finish() ] );
  46778. tempTexture.destroy();
  46779. }
  46780. /**
  46781. * Generates mipmaps for the given GPU texture.
  46782. *
  46783. * @param {GPUTexture} textureGPU - The GPU texture object.
  46784. * @param {Object} textureGPUDescriptor - The texture descriptor.
  46785. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  46786. */
  46787. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  46788. const textureData = this.get( textureGPU );
  46789. if ( textureData.useCount === undefined ) {
  46790. textureData.useCount = 0;
  46791. textureData.layers = [];
  46792. }
  46793. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  46794. const commandEncoder = this.device.createCommandEncoder( {} );
  46795. this._mipmapRunBundles( commandEncoder, passes );
  46796. this.device.queue.submit( [ commandEncoder.finish() ] );
  46797. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  46798. textureData.useCount ++;
  46799. }
  46800. /**
  46801. * Since multiple copy render passes are required to generate mipmaps, the passes
  46802. * are managed as render bundles to improve performance.
  46803. *
  46804. * @param {GPUTexture} textureGPU - The GPU texture object.
  46805. * @param {Object} textureGPUDescriptor - The texture descriptor.
  46806. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  46807. * @return {Array<Object>} An array of render bundles.
  46808. */
  46809. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  46810. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  46811. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  46812. let srcView = textureGPU.createView( {
  46813. baseMipLevel: 0,
  46814. mipLevelCount: 1,
  46815. dimension: GPUTextureViewDimension.TwoD,
  46816. baseArrayLayer
  46817. } );
  46818. const passes = [];
  46819. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  46820. const bindGroup = this.device.createBindGroup( {
  46821. layout: bindGroupLayout,
  46822. entries: [ {
  46823. binding: 0,
  46824. resource: this.mipmapSampler
  46825. }, {
  46826. binding: 1,
  46827. resource: srcView
  46828. } ]
  46829. } );
  46830. const dstView = textureGPU.createView( {
  46831. baseMipLevel: i,
  46832. mipLevelCount: 1,
  46833. dimension: GPUTextureViewDimension.TwoD,
  46834. baseArrayLayer
  46835. } );
  46836. const passDescriptor = {
  46837. colorAttachments: [ {
  46838. view: dstView,
  46839. loadOp: GPULoadOp.Clear,
  46840. storeOp: GPUStoreOp.Store,
  46841. clearValue: [ 0, 0, 0, 0 ]
  46842. } ]
  46843. };
  46844. const passEncoder = this.device.createRenderBundleEncoder( {
  46845. colorFormats: [ textureGPUDescriptor.format ]
  46846. } );
  46847. passEncoder.setPipeline( pipeline );
  46848. passEncoder.setBindGroup( 0, bindGroup );
  46849. passEncoder.draw( 4, 1, 0, 0 );
  46850. passes.push( {
  46851. renderBundles: [ passEncoder.finish() ],
  46852. passDescriptor
  46853. } );
  46854. srcView = dstView;
  46855. }
  46856. return passes;
  46857. }
  46858. /**
  46859. * Executes the render bundles.
  46860. *
  46861. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  46862. * @param {Array<Object>} passes - An array of render bundles.
  46863. */
  46864. _mipmapRunBundles( commandEncoder, passes ) {
  46865. const levels = passes.length;
  46866. for ( let i = 0; i < levels; i ++ ) {
  46867. const pass = passes[ i ];
  46868. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  46869. passEncoder.executeBundles( pass.renderBundles );
  46870. passEncoder.end();
  46871. }
  46872. }
  46873. }
  46874. const _compareToWebGPU = {
  46875. [ NeverCompare ]: 'never',
  46876. [ LessCompare ]: 'less',
  46877. [ EqualCompare ]: 'equal',
  46878. [ LessEqualCompare ]: 'less-equal',
  46879. [ GreaterCompare ]: 'greater',
  46880. [ GreaterEqualCompare ]: 'greater-equal',
  46881. [ AlwaysCompare ]: 'always',
  46882. [ NotEqualCompare ]: 'not-equal'
  46883. };
  46884. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  46885. /**
  46886. * A WebGPU backend utility module for managing textures.
  46887. *
  46888. * @private
  46889. */
  46890. class WebGPUTextureUtils {
  46891. /**
  46892. * Constructs a new utility object.
  46893. *
  46894. * @param {WebGPUBackend} backend - The WebGPU backend.
  46895. */
  46896. constructor( backend ) {
  46897. /**
  46898. * A reference to the WebGPU backend.
  46899. *
  46900. * @type {WebGPUBackend}
  46901. */
  46902. this.backend = backend;
  46903. /**
  46904. * A reference to the pass utils.
  46905. *
  46906. * @type {?WebGPUTexturePassUtils}
  46907. * @default null
  46908. */
  46909. this._passUtils = null;
  46910. /**
  46911. * A dictionary for managing default textures. The key
  46912. * is the texture format, the value the texture object.
  46913. *
  46914. * @type {Object<string,Texture>}
  46915. */
  46916. this.defaultTexture = {};
  46917. /**
  46918. * A dictionary for managing default cube textures. The key
  46919. * is the texture format, the value the texture object.
  46920. *
  46921. * @type {Object<string,CubeTexture>}
  46922. */
  46923. this.defaultCubeTexture = {};
  46924. /**
  46925. * A default video frame.
  46926. *
  46927. * @type {?VideoFrame}
  46928. * @default null
  46929. */
  46930. this.defaultVideoFrame = null;
  46931. /**
  46932. * Represents the color attachment of the default framebuffer.
  46933. *
  46934. * @type {?GPUTexture}
  46935. * @default null
  46936. */
  46937. this.colorBuffer = null;
  46938. /**
  46939. * Represents the depth attachment of the default framebuffer.
  46940. *
  46941. * @type {DepthTexture}
  46942. */
  46943. this.depthTexture = new DepthTexture();
  46944. this.depthTexture.name = 'depthBuffer';
  46945. }
  46946. /**
  46947. * Creates a GPU sampler for the given texture.
  46948. *
  46949. * @param {Texture} texture - The texture to create the sampler for.
  46950. */
  46951. createSampler( texture ) {
  46952. const backend = this.backend;
  46953. const device = backend.device;
  46954. const textureGPU = backend.get( texture );
  46955. const samplerDescriptorGPU = {
  46956. addressModeU: this._convertAddressMode( texture.wrapS ),
  46957. addressModeV: this._convertAddressMode( texture.wrapT ),
  46958. addressModeW: this._convertAddressMode( texture.wrapR ),
  46959. magFilter: this._convertFilterMode( texture.magFilter ),
  46960. minFilter: this._convertFilterMode( texture.minFilter ),
  46961. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  46962. maxAnisotropy: 1
  46963. };
  46964. // anisotropy can only be used when all filter modes are set to linear.
  46965. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  46966. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  46967. }
  46968. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  46969. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  46970. }
  46971. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  46972. }
  46973. /**
  46974. * Creates a default texture for the given texture that can be used
  46975. * as a placeholder until the actual texture is ready for usage.
  46976. *
  46977. * @param {Texture} texture - The texture to create a default texture for.
  46978. */
  46979. createDefaultTexture( texture ) {
  46980. let textureGPU;
  46981. const format = getFormat( texture );
  46982. if ( texture.isCubeTexture ) {
  46983. textureGPU = this._getDefaultCubeTextureGPU( format );
  46984. } else {
  46985. textureGPU = this._getDefaultTextureGPU( format );
  46986. }
  46987. this.backend.get( texture ).texture = textureGPU;
  46988. }
  46989. /**
  46990. * Defines a texture on the GPU for the given texture object.
  46991. *
  46992. * @param {Texture} texture - The texture.
  46993. * @param {Object} [options={}] - Optional configuration parameter.
  46994. */
  46995. createTexture( texture, options = {} ) {
  46996. const backend = this.backend;
  46997. const textureData = backend.get( texture );
  46998. if ( textureData.initialized ) {
  46999. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  47000. }
  47001. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  47002. if ( options.levels === undefined ) options.levels = 1;
  47003. if ( options.depth === undefined ) options.depth = 1;
  47004. const { width, height, depth, levels } = options;
  47005. if ( texture.isFramebufferTexture ) {
  47006. if ( options.renderTarget ) {
  47007. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  47008. } else {
  47009. options.format = this.backend.utils.getPreferredCanvasFormat();
  47010. }
  47011. }
  47012. const dimension = this._getDimension( texture );
  47013. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  47014. textureData.format = format;
  47015. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  47016. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  47017. if ( texture.isStorageTexture === true ) {
  47018. usage |= GPUTextureUsage.STORAGE_BINDING;
  47019. }
  47020. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  47021. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  47022. }
  47023. const textureDescriptorGPU = {
  47024. label: texture.name,
  47025. size: {
  47026. width: width,
  47027. height: height,
  47028. depthOrArrayLayers: depth,
  47029. },
  47030. mipLevelCount: levels,
  47031. sampleCount: primarySamples,
  47032. dimension: dimension,
  47033. format: format,
  47034. usage: usage
  47035. };
  47036. // texture creation
  47037. if ( format === undefined ) {
  47038. console.warn( 'WebGPURenderer: Texture format not supported.' );
  47039. this.createDefaultTexture( texture );
  47040. return;
  47041. }
  47042. if ( texture.isCubeTexture ) {
  47043. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  47044. }
  47045. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  47046. if ( isMSAA ) {
  47047. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  47048. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  47049. msaaTextureDescriptorGPU.sampleCount = samples;
  47050. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  47051. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  47052. }
  47053. textureData.initialized = true;
  47054. textureData.textureDescriptorGPU = textureDescriptorGPU;
  47055. }
  47056. /**
  47057. * Destroys the GPU data for the given texture object.
  47058. *
  47059. * @param {Texture} texture - The texture.
  47060. */
  47061. destroyTexture( texture ) {
  47062. const backend = this.backend;
  47063. const textureData = backend.get( texture );
  47064. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  47065. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  47066. backend.delete( texture );
  47067. }
  47068. /**
  47069. * Destroys the GPU sampler for the given texture.
  47070. *
  47071. * @param {Texture} texture - The texture to destroy the sampler for.
  47072. */
  47073. destroySampler( texture ) {
  47074. const backend = this.backend;
  47075. const textureData = backend.get( texture );
  47076. delete textureData.sampler;
  47077. }
  47078. /**
  47079. * Generates mipmaps for the given texture.
  47080. *
  47081. * @param {Texture} texture - The texture.
  47082. */
  47083. generateMipmaps( texture ) {
  47084. const textureData = this.backend.get( texture );
  47085. if ( texture.isCubeTexture ) {
  47086. for ( let i = 0; i < 6; i ++ ) {
  47087. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  47088. }
  47089. } else {
  47090. const depth = texture.image.depth || 1;
  47091. for ( let i = 0; i < depth; i ++ ) {
  47092. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  47093. }
  47094. }
  47095. }
  47096. /**
  47097. * Returns the color buffer representing the color
  47098. * attachment of the default framebuffer.
  47099. *
  47100. * @return {GPUTexture} The color buffer.
  47101. */
  47102. getColorBuffer() {
  47103. if ( this.colorBuffer ) this.colorBuffer.destroy();
  47104. const backend = this.backend;
  47105. const { width, height } = backend.getDrawingBufferSize();
  47106. this.colorBuffer = backend.device.createTexture( {
  47107. label: 'colorBuffer',
  47108. size: {
  47109. width: width,
  47110. height: height,
  47111. depthOrArrayLayers: 1
  47112. },
  47113. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  47114. format: backend.utils.getPreferredCanvasFormat(),
  47115. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  47116. } );
  47117. return this.colorBuffer;
  47118. }
  47119. /**
  47120. * Returns the depth buffer representing the depth
  47121. * attachment of the default framebuffer.
  47122. *
  47123. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  47124. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  47125. * @return {GPUTexture} The depth buffer.
  47126. */
  47127. getDepthBuffer( depth = true, stencil = false ) {
  47128. const backend = this.backend;
  47129. const { width, height } = backend.getDrawingBufferSize();
  47130. const depthTexture = this.depthTexture;
  47131. const depthTextureGPU = backend.get( depthTexture ).texture;
  47132. let format, type;
  47133. if ( stencil ) {
  47134. format = DepthStencilFormat;
  47135. type = UnsignedInt248Type;
  47136. } else if ( depth ) {
  47137. format = DepthFormat;
  47138. type = UnsignedIntType;
  47139. }
  47140. if ( depthTextureGPU !== undefined ) {
  47141. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  47142. return depthTextureGPU;
  47143. }
  47144. this.destroyTexture( depthTexture );
  47145. }
  47146. depthTexture.name = 'depthBuffer';
  47147. depthTexture.format = format;
  47148. depthTexture.type = type;
  47149. depthTexture.image.width = width;
  47150. depthTexture.image.height = height;
  47151. this.createTexture( depthTexture, { width, height } );
  47152. return backend.get( depthTexture ).texture;
  47153. }
  47154. /**
  47155. * Uploads the updated texture data to the GPU.
  47156. *
  47157. * @param {Texture} texture - The texture.
  47158. * @param {Object} [options={}] - Optional configuration parameter.
  47159. */
  47160. updateTexture( texture, options ) {
  47161. const textureData = this.backend.get( texture );
  47162. const { textureDescriptorGPU } = textureData;
  47163. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  47164. return;
  47165. // transfer texture data
  47166. if ( texture.isDataTexture ) {
  47167. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  47168. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  47169. for ( let i = 0; i < options.image.depth; i ++ ) {
  47170. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  47171. }
  47172. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  47173. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  47174. } else if ( texture.isCubeTexture ) {
  47175. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY, texture.premultiplyAlpha );
  47176. } else {
  47177. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  47178. }
  47179. //
  47180. textureData.version = texture.version;
  47181. if ( texture.onUpdate ) texture.onUpdate( texture );
  47182. }
  47183. /**
  47184. * Returns texture data as a typed array.
  47185. *
  47186. * @async
  47187. * @param {Texture} texture - The texture to copy.
  47188. * @param {number} x - The x coordinate of the copy origin.
  47189. * @param {number} y - The y coordinate of the copy origin.
  47190. * @param {number} width - The width of the copy.
  47191. * @param {number} height - The height of the copy.
  47192. * @param {number} faceIndex - The face index.
  47193. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  47194. */
  47195. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  47196. const device = this.backend.device;
  47197. const textureData = this.backend.get( texture );
  47198. const textureGPU = textureData.texture;
  47199. const format = textureData.textureDescriptorGPU.format;
  47200. const bytesPerTexel = this._getBytesPerTexel( format );
  47201. let bytesPerRow = width * bytesPerTexel;
  47202. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  47203. const readBuffer = device.createBuffer(
  47204. {
  47205. size: width * height * bytesPerTexel,
  47206. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  47207. }
  47208. );
  47209. const encoder = device.createCommandEncoder();
  47210. encoder.copyTextureToBuffer(
  47211. {
  47212. texture: textureGPU,
  47213. origin: { x, y, z: faceIndex },
  47214. },
  47215. {
  47216. buffer: readBuffer,
  47217. bytesPerRow: bytesPerRow
  47218. },
  47219. {
  47220. width: width,
  47221. height: height
  47222. }
  47223. );
  47224. const typedArrayType = this._getTypedArrayType( format );
  47225. device.queue.submit( [ encoder.finish() ] );
  47226. await readBuffer.mapAsync( GPUMapMode.READ );
  47227. const buffer = readBuffer.getMappedRange();
  47228. return new typedArrayType( buffer );
  47229. }
  47230. /**
  47231. * Returns the default GPU texture for the given format.
  47232. *
  47233. * @private
  47234. * @param {string} format - The GPU format.
  47235. * @return {GPUTexture} The GPU texture.
  47236. */
  47237. _getDefaultTextureGPU( format ) {
  47238. let defaultTexture = this.defaultTexture[ format ];
  47239. if ( defaultTexture === undefined ) {
  47240. const texture = new Texture();
  47241. texture.minFilter = NearestFilter;
  47242. texture.magFilter = NearestFilter;
  47243. this.createTexture( texture, { width: 1, height: 1, format } );
  47244. this.defaultTexture[ format ] = defaultTexture = texture;
  47245. }
  47246. return this.backend.get( defaultTexture ).texture;
  47247. }
  47248. /**
  47249. * Returns the default GPU cube texture for the given format.
  47250. *
  47251. * @private
  47252. * @param {string} format - The GPU format.
  47253. * @return {GPUTexture} The GPU texture.
  47254. */
  47255. _getDefaultCubeTextureGPU( format ) {
  47256. let defaultCubeTexture = this.defaultTexture[ format ];
  47257. if ( defaultCubeTexture === undefined ) {
  47258. const texture = new CubeTexture();
  47259. texture.minFilter = NearestFilter;
  47260. texture.magFilter = NearestFilter;
  47261. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  47262. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  47263. }
  47264. return this.backend.get( defaultCubeTexture ).texture;
  47265. }
  47266. /**
  47267. * Uploads cube texture image data to the GPU memory.
  47268. *
  47269. * @private
  47270. * @param {Array} images - The cube image data.
  47271. * @param {GPUTexture} textureGPU - The GPU texture.
  47272. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  47273. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  47274. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  47275. */
  47276. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY, premultiplyAlpha ) {
  47277. for ( let i = 0; i < 6; i ++ ) {
  47278. const image = images[ i ];
  47279. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  47280. if ( image.isDataTexture ) {
  47281. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  47282. } else {
  47283. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY, premultiplyAlpha );
  47284. }
  47285. }
  47286. }
  47287. /**
  47288. * Uploads texture image data to the GPU memory.
  47289. *
  47290. * @private
  47291. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  47292. * @param {GPUTexture} textureGPU - The GPU texture.
  47293. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  47294. * @param {number} originDepth - The origin depth.
  47295. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  47296. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  47297. */
  47298. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha ) {
  47299. const device = this.backend.device;
  47300. device.queue.copyExternalImageToTexture(
  47301. {
  47302. source: image,
  47303. flipY: flipY
  47304. }, {
  47305. texture: textureGPU,
  47306. mipLevel: 0,
  47307. origin: { x: 0, y: 0, z: originDepth },
  47308. premultipliedAlpha: premultiplyAlpha
  47309. }, {
  47310. width: textureDescriptorGPU.size.width,
  47311. height: textureDescriptorGPU.size.height,
  47312. depthOrArrayLayers: 1
  47313. }
  47314. );
  47315. }
  47316. /**
  47317. * Returns the pass utils singleton.
  47318. *
  47319. * @private
  47320. * @return {WebGPUTexturePassUtils} The utils instance.
  47321. */
  47322. _getPassUtils() {
  47323. let passUtils = this._passUtils;
  47324. if ( passUtils === null ) {
  47325. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  47326. }
  47327. return passUtils;
  47328. }
  47329. /**
  47330. * Generates mipmaps for the given GPU texture.
  47331. *
  47332. * @private
  47333. * @param {GPUTexture} textureGPU - The GPU texture object.
  47334. * @param {Object} textureDescriptorGPU - The texture descriptor.
  47335. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  47336. */
  47337. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  47338. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  47339. }
  47340. /**
  47341. * Flip the contents of the given GPU texture along its vertical axis.
  47342. *
  47343. * @private
  47344. * @param {GPUTexture} textureGPU - The GPU texture object.
  47345. * @param {Object} textureDescriptorGPU - The texture descriptor.
  47346. * @param {number} [originDepth=0] - The origin depth.
  47347. */
  47348. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  47349. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  47350. }
  47351. /**
  47352. * Uploads texture buffer data to the GPU memory.
  47353. *
  47354. * @private
  47355. * @param {Object} image - An object defining the image buffer data.
  47356. * @param {GPUTexture} textureGPU - The GPU texture.
  47357. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  47358. * @param {number} originDepth - The origin depth.
  47359. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  47360. * @param {number} [depth=0] - TODO.
  47361. */
  47362. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  47363. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  47364. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  47365. const device = this.backend.device;
  47366. const data = image.data;
  47367. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  47368. const bytesPerRow = image.width * bytesPerTexel;
  47369. device.queue.writeTexture(
  47370. {
  47371. texture: textureGPU,
  47372. mipLevel: 0,
  47373. origin: { x: 0, y: 0, z: originDepth }
  47374. },
  47375. data,
  47376. {
  47377. offset: image.width * image.height * bytesPerTexel * depth,
  47378. bytesPerRow
  47379. },
  47380. {
  47381. width: image.width,
  47382. height: image.height,
  47383. depthOrArrayLayers: 1
  47384. } );
  47385. if ( flipY === true ) {
  47386. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  47387. }
  47388. }
  47389. /**
  47390. * Uploads compressed texture data to the GPU memory.
  47391. *
  47392. * @private
  47393. * @param {Array<Object>} mipmaps - An array with mipmap data.
  47394. * @param {GPUTexture} textureGPU - The GPU texture.
  47395. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  47396. */
  47397. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  47398. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  47399. const device = this.backend.device;
  47400. const blockData = this._getBlockData( textureDescriptorGPU.format );
  47401. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  47402. for ( let i = 0; i < mipmaps.length; i ++ ) {
  47403. const mipmap = mipmaps[ i ];
  47404. const width = mipmap.width;
  47405. const height = mipmap.height;
  47406. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  47407. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  47408. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  47409. for ( let j = 0; j < depth; j ++ ) {
  47410. device.queue.writeTexture(
  47411. {
  47412. texture: textureGPU,
  47413. mipLevel: i,
  47414. origin: { x: 0, y: 0, z: j }
  47415. },
  47416. mipmap.data,
  47417. {
  47418. offset: j * bytesPerImage,
  47419. bytesPerRow,
  47420. rowsPerImage: Math.ceil( height / blockData.height )
  47421. },
  47422. {
  47423. width: Math.ceil( width / blockData.width ) * blockData.width,
  47424. height: Math.ceil( height / blockData.height ) * blockData.height,
  47425. depthOrArrayLayers: 1
  47426. }
  47427. );
  47428. }
  47429. }
  47430. }
  47431. /**
  47432. * This method is only relevant for compressed texture formats. It returns a block
  47433. * data descriptor for the given GPU compressed texture format.
  47434. *
  47435. * @private
  47436. * @param {string} format - The GPU compressed texture format.
  47437. * @return {Object} The block data descriptor.
  47438. */
  47439. _getBlockData( format ) {
  47440. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  47441. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  47442. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  47443. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  47444. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  47445. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  47446. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  47447. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  47448. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  47449. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  47450. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  47451. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  47452. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  47453. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  47454. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  47455. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  47456. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  47457. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  47458. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  47459. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  47460. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  47461. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  47462. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  47463. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  47464. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  47465. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  47466. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  47467. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  47468. }
  47469. /**
  47470. * Converts the three.js uv wrapping constants to GPU address mode constants.
  47471. *
  47472. * @private
  47473. * @param {number} value - The three.js constant defining a uv wrapping mode.
  47474. * @return {string} The GPU address mode.
  47475. */
  47476. _convertAddressMode( value ) {
  47477. let addressMode = GPUAddressMode.ClampToEdge;
  47478. if ( value === RepeatWrapping ) {
  47479. addressMode = GPUAddressMode.Repeat;
  47480. } else if ( value === MirroredRepeatWrapping ) {
  47481. addressMode = GPUAddressMode.MirrorRepeat;
  47482. }
  47483. return addressMode;
  47484. }
  47485. /**
  47486. * Converts the three.js filter constants to GPU filter constants.
  47487. *
  47488. * @private
  47489. * @param {number} value - The three.js constant defining a filter mode.
  47490. * @return {string} The GPU filter mode.
  47491. */
  47492. _convertFilterMode( value ) {
  47493. let filterMode = GPUFilterMode.Linear;
  47494. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  47495. filterMode = GPUFilterMode.Nearest;
  47496. }
  47497. return filterMode;
  47498. }
  47499. /**
  47500. * Returns the bytes-per-texel value for the given GPU texture format.
  47501. *
  47502. * @private
  47503. * @param {string} format - The GPU texture format.
  47504. * @return {number} The bytes-per-texel.
  47505. */
  47506. _getBytesPerTexel( format ) {
  47507. // 8-bit formats
  47508. if ( format === GPUTextureFormat.R8Unorm ||
  47509. format === GPUTextureFormat.R8Snorm ||
  47510. format === GPUTextureFormat.R8Uint ||
  47511. format === GPUTextureFormat.R8Sint ) return 1;
  47512. // 16-bit formats
  47513. if ( format === GPUTextureFormat.R16Uint ||
  47514. format === GPUTextureFormat.R16Sint ||
  47515. format === GPUTextureFormat.R16Float ||
  47516. format === GPUTextureFormat.RG8Unorm ||
  47517. format === GPUTextureFormat.RG8Snorm ||
  47518. format === GPUTextureFormat.RG8Uint ||
  47519. format === GPUTextureFormat.RG8Sint ) return 2;
  47520. // 32-bit formats
  47521. if ( format === GPUTextureFormat.R32Uint ||
  47522. format === GPUTextureFormat.R32Sint ||
  47523. format === GPUTextureFormat.R32Float ||
  47524. format === GPUTextureFormat.RG16Uint ||
  47525. format === GPUTextureFormat.RG16Sint ||
  47526. format === GPUTextureFormat.RG16Float ||
  47527. format === GPUTextureFormat.RGBA8Unorm ||
  47528. format === GPUTextureFormat.RGBA8UnormSRGB ||
  47529. format === GPUTextureFormat.RGBA8Snorm ||
  47530. format === GPUTextureFormat.RGBA8Uint ||
  47531. format === GPUTextureFormat.RGBA8Sint ||
  47532. format === GPUTextureFormat.BGRA8Unorm ||
  47533. format === GPUTextureFormat.BGRA8UnormSRGB ||
  47534. // Packed 32-bit formats
  47535. format === GPUTextureFormat.RGB9E5UFloat ||
  47536. format === GPUTextureFormat.RGB10A2Unorm ||
  47537. format === GPUTextureFormat.RG11B10UFloat ||
  47538. format === GPUTextureFormat.Depth32Float ||
  47539. format === GPUTextureFormat.Depth24Plus ||
  47540. format === GPUTextureFormat.Depth24PlusStencil8 ||
  47541. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  47542. // 64-bit formats
  47543. if ( format === GPUTextureFormat.RG32Uint ||
  47544. format === GPUTextureFormat.RG32Sint ||
  47545. format === GPUTextureFormat.RG32Float ||
  47546. format === GPUTextureFormat.RGBA16Uint ||
  47547. format === GPUTextureFormat.RGBA16Sint ||
  47548. format === GPUTextureFormat.RGBA16Float ) return 8;
  47549. // 128-bit formats
  47550. if ( format === GPUTextureFormat.RGBA32Uint ||
  47551. format === GPUTextureFormat.RGBA32Sint ||
  47552. format === GPUTextureFormat.RGBA32Float ) return 16;
  47553. }
  47554. /**
  47555. * Returns the corresponding typed array type for the given GPU texture format.
  47556. *
  47557. * @private
  47558. * @param {string} format - The GPU texture format.
  47559. * @return {TypedArray.constructor} The typed array type.
  47560. */
  47561. _getTypedArrayType( format ) {
  47562. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  47563. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  47564. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  47565. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  47566. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  47567. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  47568. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  47569. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  47570. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  47571. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  47572. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  47573. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  47574. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  47575. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  47576. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  47577. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  47578. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  47579. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  47580. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  47581. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  47582. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  47583. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  47584. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  47585. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  47586. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  47587. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  47588. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  47589. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  47590. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  47591. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  47592. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  47593. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  47594. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  47595. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  47596. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  47597. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  47598. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  47599. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  47600. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  47601. }
  47602. /**
  47603. * Returns the GPU dimensions for the given texture.
  47604. *
  47605. * @private
  47606. * @param {Texture} texture - The texture.
  47607. * @return {string} The GPU dimension.
  47608. */
  47609. _getDimension( texture ) {
  47610. let dimension;
  47611. if ( texture.is3DTexture || texture.isData3DTexture ) {
  47612. dimension = GPUTextureDimension.ThreeD;
  47613. } else {
  47614. dimension = GPUTextureDimension.TwoD;
  47615. }
  47616. return dimension;
  47617. }
  47618. }
  47619. /**
  47620. * Returns the GPU format for the given texture.
  47621. *
  47622. * @param {Texture} texture - The texture.
  47623. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  47624. * It is not necessary to apply the device for most formats.
  47625. * @return {string} The GPU format.
  47626. */
  47627. function getFormat( texture, device = null ) {
  47628. const format = texture.format;
  47629. const type = texture.type;
  47630. const colorSpace = texture.colorSpace;
  47631. const transfer = ColorManagement.getTransfer( colorSpace );
  47632. let formatGPU;
  47633. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  47634. switch ( format ) {
  47635. case RGBA_S3TC_DXT1_Format:
  47636. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  47637. break;
  47638. case RGBA_S3TC_DXT3_Format:
  47639. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  47640. break;
  47641. case RGBA_S3TC_DXT5_Format:
  47642. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  47643. break;
  47644. case RGB_ETC2_Format:
  47645. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  47646. break;
  47647. case RGBA_ETC2_EAC_Format:
  47648. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  47649. break;
  47650. case RGBA_ASTC_4x4_Format:
  47651. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  47652. break;
  47653. case RGBA_ASTC_5x4_Format:
  47654. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  47655. break;
  47656. case RGBA_ASTC_5x5_Format:
  47657. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  47658. break;
  47659. case RGBA_ASTC_6x5_Format:
  47660. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  47661. break;
  47662. case RGBA_ASTC_6x6_Format:
  47663. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  47664. break;
  47665. case RGBA_ASTC_8x5_Format:
  47666. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  47667. break;
  47668. case RGBA_ASTC_8x6_Format:
  47669. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  47670. break;
  47671. case RGBA_ASTC_8x8_Format:
  47672. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  47673. break;
  47674. case RGBA_ASTC_10x5_Format:
  47675. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  47676. break;
  47677. case RGBA_ASTC_10x6_Format:
  47678. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  47679. break;
  47680. case RGBA_ASTC_10x8_Format:
  47681. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  47682. break;
  47683. case RGBA_ASTC_10x10_Format:
  47684. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  47685. break;
  47686. case RGBA_ASTC_12x10_Format:
  47687. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  47688. break;
  47689. case RGBA_ASTC_12x12_Format:
  47690. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  47691. break;
  47692. case RGBAFormat:
  47693. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  47694. break;
  47695. default:
  47696. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  47697. }
  47698. } else {
  47699. switch ( format ) {
  47700. case RGBAFormat:
  47701. switch ( type ) {
  47702. case ByteType:
  47703. formatGPU = GPUTextureFormat.RGBA8Snorm;
  47704. break;
  47705. case ShortType:
  47706. formatGPU = GPUTextureFormat.RGBA16Sint;
  47707. break;
  47708. case UnsignedShortType:
  47709. formatGPU = GPUTextureFormat.RGBA16Uint;
  47710. break;
  47711. case UnsignedIntType:
  47712. formatGPU = GPUTextureFormat.RGBA32Uint;
  47713. break;
  47714. case IntType:
  47715. formatGPU = GPUTextureFormat.RGBA32Sint;
  47716. break;
  47717. case UnsignedByteType:
  47718. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  47719. break;
  47720. case HalfFloatType:
  47721. formatGPU = GPUTextureFormat.RGBA16Float;
  47722. break;
  47723. case FloatType:
  47724. formatGPU = GPUTextureFormat.RGBA32Float;
  47725. break;
  47726. default:
  47727. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  47728. }
  47729. break;
  47730. case RGBFormat:
  47731. switch ( type ) {
  47732. case UnsignedInt5999Type:
  47733. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  47734. break;
  47735. default:
  47736. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  47737. }
  47738. break;
  47739. case RedFormat:
  47740. switch ( type ) {
  47741. case ByteType:
  47742. formatGPU = GPUTextureFormat.R8Snorm;
  47743. break;
  47744. case ShortType:
  47745. formatGPU = GPUTextureFormat.R16Sint;
  47746. break;
  47747. case UnsignedShortType:
  47748. formatGPU = GPUTextureFormat.R16Uint;
  47749. break;
  47750. case UnsignedIntType:
  47751. formatGPU = GPUTextureFormat.R32Uint;
  47752. break;
  47753. case IntType:
  47754. formatGPU = GPUTextureFormat.R32Sint;
  47755. break;
  47756. case UnsignedByteType:
  47757. formatGPU = GPUTextureFormat.R8Unorm;
  47758. break;
  47759. case HalfFloatType:
  47760. formatGPU = GPUTextureFormat.R16Float;
  47761. break;
  47762. case FloatType:
  47763. formatGPU = GPUTextureFormat.R32Float;
  47764. break;
  47765. default:
  47766. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  47767. }
  47768. break;
  47769. case RGFormat:
  47770. switch ( type ) {
  47771. case ByteType:
  47772. formatGPU = GPUTextureFormat.RG8Snorm;
  47773. break;
  47774. case ShortType:
  47775. formatGPU = GPUTextureFormat.RG16Sint;
  47776. break;
  47777. case UnsignedShortType:
  47778. formatGPU = GPUTextureFormat.RG16Uint;
  47779. break;
  47780. case UnsignedIntType:
  47781. formatGPU = GPUTextureFormat.RG32Uint;
  47782. break;
  47783. case IntType:
  47784. formatGPU = GPUTextureFormat.RG32Sint;
  47785. break;
  47786. case UnsignedByteType:
  47787. formatGPU = GPUTextureFormat.RG8Unorm;
  47788. break;
  47789. case HalfFloatType:
  47790. formatGPU = GPUTextureFormat.RG16Float;
  47791. break;
  47792. case FloatType:
  47793. formatGPU = GPUTextureFormat.RG32Float;
  47794. break;
  47795. default:
  47796. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  47797. }
  47798. break;
  47799. case DepthFormat:
  47800. switch ( type ) {
  47801. case UnsignedShortType:
  47802. formatGPU = GPUTextureFormat.Depth16Unorm;
  47803. break;
  47804. case UnsignedIntType:
  47805. formatGPU = GPUTextureFormat.Depth24Plus;
  47806. break;
  47807. case FloatType:
  47808. formatGPU = GPUTextureFormat.Depth32Float;
  47809. break;
  47810. default:
  47811. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  47812. }
  47813. break;
  47814. case DepthStencilFormat:
  47815. switch ( type ) {
  47816. case UnsignedInt248Type:
  47817. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  47818. break;
  47819. case FloatType:
  47820. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  47821. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  47822. }
  47823. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  47824. break;
  47825. default:
  47826. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  47827. }
  47828. break;
  47829. case RedIntegerFormat:
  47830. switch ( type ) {
  47831. case IntType:
  47832. formatGPU = GPUTextureFormat.R32Sint;
  47833. break;
  47834. case UnsignedIntType:
  47835. formatGPU = GPUTextureFormat.R32Uint;
  47836. break;
  47837. default:
  47838. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  47839. }
  47840. break;
  47841. case RGIntegerFormat:
  47842. switch ( type ) {
  47843. case IntType:
  47844. formatGPU = GPUTextureFormat.RG32Sint;
  47845. break;
  47846. case UnsignedIntType:
  47847. formatGPU = GPUTextureFormat.RG32Uint;
  47848. break;
  47849. default:
  47850. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  47851. }
  47852. break;
  47853. case RGBAIntegerFormat:
  47854. switch ( type ) {
  47855. case IntType:
  47856. formatGPU = GPUTextureFormat.RGBA32Sint;
  47857. break;
  47858. case UnsignedIntType:
  47859. formatGPU = GPUTextureFormat.RGBA32Uint;
  47860. break;
  47861. default:
  47862. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  47863. }
  47864. break;
  47865. default:
  47866. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  47867. }
  47868. }
  47869. return formatGPU;
  47870. }
  47871. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  47872. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  47873. const wgslTypeLib$1 = {
  47874. 'f32': 'float',
  47875. 'i32': 'int',
  47876. 'u32': 'uint',
  47877. 'bool': 'bool',
  47878. 'vec2<f32>': 'vec2',
  47879. 'vec2<i32>': 'ivec2',
  47880. 'vec2<u32>': 'uvec2',
  47881. 'vec2<bool>': 'bvec2',
  47882. 'vec2f': 'vec2',
  47883. 'vec2i': 'ivec2',
  47884. 'vec2u': 'uvec2',
  47885. 'vec2b': 'bvec2',
  47886. 'vec3<f32>': 'vec3',
  47887. 'vec3<i32>': 'ivec3',
  47888. 'vec3<u32>': 'uvec3',
  47889. 'vec3<bool>': 'bvec3',
  47890. 'vec3f': 'vec3',
  47891. 'vec3i': 'ivec3',
  47892. 'vec3u': 'uvec3',
  47893. 'vec3b': 'bvec3',
  47894. 'vec4<f32>': 'vec4',
  47895. 'vec4<i32>': 'ivec4',
  47896. 'vec4<u32>': 'uvec4',
  47897. 'vec4<bool>': 'bvec4',
  47898. 'vec4f': 'vec4',
  47899. 'vec4i': 'ivec4',
  47900. 'vec4u': 'uvec4',
  47901. 'vec4b': 'bvec4',
  47902. 'mat2x2<f32>': 'mat2',
  47903. 'mat2x2f': 'mat2',
  47904. 'mat3x3<f32>': 'mat3',
  47905. 'mat3x3f': 'mat3',
  47906. 'mat4x4<f32>': 'mat4',
  47907. 'mat4x4f': 'mat4',
  47908. 'sampler': 'sampler',
  47909. 'texture_1d': 'texture',
  47910. 'texture_2d': 'texture',
  47911. 'texture_2d_array': 'texture',
  47912. 'texture_multisampled_2d': 'cubeTexture',
  47913. 'texture_depth_2d': 'depthTexture',
  47914. 'texture_depth_2d_array': 'depthTexture',
  47915. 'texture_depth_multisampled_2d': 'depthTexture',
  47916. 'texture_depth_cube': 'depthTexture',
  47917. 'texture_depth_cube_array': 'depthTexture',
  47918. 'texture_3d': 'texture3D',
  47919. 'texture_cube': 'cubeTexture',
  47920. 'texture_cube_array': 'cubeTexture',
  47921. 'texture_storage_1d': 'storageTexture',
  47922. 'texture_storage_2d': 'storageTexture',
  47923. 'texture_storage_2d_array': 'storageTexture',
  47924. 'texture_storage_3d': 'storageTexture'
  47925. };
  47926. const parse = ( source ) => {
  47927. source = source.trim();
  47928. const declaration = source.match( declarationRegexp );
  47929. if ( declaration !== null && declaration.length === 4 ) {
  47930. const inputsCode = declaration[ 2 ];
  47931. const propsMatches = [];
  47932. let match = null;
  47933. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  47934. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  47935. }
  47936. // Process matches to correctly pair names and types
  47937. const inputs = [];
  47938. for ( let i = 0; i < propsMatches.length; i ++ ) {
  47939. const { name, type } = propsMatches[ i ];
  47940. let resolvedType = type;
  47941. if ( resolvedType.startsWith( 'ptr' ) ) {
  47942. resolvedType = 'pointer';
  47943. } else {
  47944. if ( resolvedType.startsWith( 'texture' ) ) {
  47945. resolvedType = type.split( '<' )[ 0 ];
  47946. }
  47947. resolvedType = wgslTypeLib$1[ resolvedType ];
  47948. }
  47949. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  47950. }
  47951. const blockCode = source.substring( declaration[ 0 ].length );
  47952. const outputType = declaration[ 3 ] || 'void';
  47953. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  47954. const type = wgslTypeLib$1[ outputType ] || outputType;
  47955. return {
  47956. type,
  47957. inputs,
  47958. name,
  47959. inputsCode,
  47960. blockCode,
  47961. outputType
  47962. };
  47963. } else {
  47964. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  47965. }
  47966. };
  47967. /**
  47968. * This class represents a WSL node function.
  47969. *
  47970. * @augments NodeFunction
  47971. */
  47972. class WGSLNodeFunction extends NodeFunction {
  47973. /**
  47974. * Constructs a new WGSL node function.
  47975. *
  47976. * @param {string} source - The WGSL source.
  47977. */
  47978. constructor( source ) {
  47979. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  47980. super( type, inputs, name );
  47981. this.inputsCode = inputsCode;
  47982. this.blockCode = blockCode;
  47983. this.outputType = outputType;
  47984. }
  47985. /**
  47986. * This method returns the WGSL code of the node function.
  47987. *
  47988. * @param {string} [name=this.name] - The function's name.
  47989. * @return {string} The shader code.
  47990. */
  47991. getCode( name = this.name ) {
  47992. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  47993. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  47994. }
  47995. }
  47996. /**
  47997. * A WGSL node parser.
  47998. *
  47999. * @augments NodeParser
  48000. */
  48001. class WGSLNodeParser extends NodeParser {
  48002. /**
  48003. * The method parses the given WGSL code an returns a node function.
  48004. *
  48005. * @param {string} source - The WGSL code.
  48006. * @return {WGSLNodeFunction} A node function.
  48007. */
  48008. parseFunction( source ) {
  48009. return new WGSLNodeFunction( source );
  48010. }
  48011. }
  48012. // GPUShaderStage is not defined in browsers not supporting WebGPU
  48013. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  48014. const accessNames = {
  48015. [ NodeAccess.READ_ONLY ]: 'read',
  48016. [ NodeAccess.WRITE_ONLY ]: 'write',
  48017. [ NodeAccess.READ_WRITE ]: 'read_write'
  48018. };
  48019. const wrapNames = {
  48020. [ RepeatWrapping ]: 'repeat',
  48021. [ ClampToEdgeWrapping ]: 'clamp',
  48022. [ MirroredRepeatWrapping ]: 'mirror'
  48023. };
  48024. const gpuShaderStageLib = {
  48025. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  48026. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  48027. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  48028. };
  48029. const supports = {
  48030. instance: true,
  48031. swizzleAssign: false,
  48032. storageBuffer: true
  48033. };
  48034. const wgslFnOpLib = {
  48035. '^^': 'tsl_xor'
  48036. };
  48037. const wgslTypeLib = {
  48038. float: 'f32',
  48039. int: 'i32',
  48040. uint: 'u32',
  48041. bool: 'bool',
  48042. color: 'vec3<f32>',
  48043. vec2: 'vec2<f32>',
  48044. ivec2: 'vec2<i32>',
  48045. uvec2: 'vec2<u32>',
  48046. bvec2: 'vec2<bool>',
  48047. vec3: 'vec3<f32>',
  48048. ivec3: 'vec3<i32>',
  48049. uvec3: 'vec3<u32>',
  48050. bvec3: 'vec3<bool>',
  48051. vec4: 'vec4<f32>',
  48052. ivec4: 'vec4<i32>',
  48053. uvec4: 'vec4<u32>',
  48054. bvec4: 'vec4<bool>',
  48055. mat2: 'mat2x2<f32>',
  48056. mat3: 'mat3x3<f32>',
  48057. mat4: 'mat4x4<f32>'
  48058. };
  48059. const wgslCodeCache = {};
  48060. const wgslPolyfill = {
  48061. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  48062. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  48063. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  48064. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  48065. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  48066. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  48067. 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 ); }' ),
  48068. 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 ); }' ),
  48069. 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 ); }' ),
  48070. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  48071. 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 ); }' ),
  48072. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  48073. biquadraticTexture: new CodeNode( /* wgsl */`
  48074. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  48075. let res = vec2f( iRes );
  48076. let uvScaled = coord * res;
  48077. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  48078. // https://www.shadertoy.com/view/WtyXRy
  48079. let uv = uvWrapping - 0.5;
  48080. let iuv = floor( uv );
  48081. let f = fract( uv );
  48082. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  48083. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  48084. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  48085. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  48086. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  48087. }
  48088. ` )
  48089. };
  48090. const wgslMethods = {
  48091. dFdx: 'dpdx',
  48092. dFdy: '- dpdy',
  48093. mod_float: 'tsl_mod_float',
  48094. mod_vec2: 'tsl_mod_vec2',
  48095. mod_vec3: 'tsl_mod_vec3',
  48096. mod_vec4: 'tsl_mod_vec4',
  48097. equals_bool: 'tsl_equals_bool',
  48098. equals_bvec2: 'tsl_equals_bvec2',
  48099. equals_bvec3: 'tsl_equals_bvec3',
  48100. equals_bvec4: 'tsl_equals_bvec4',
  48101. inversesqrt: 'inverseSqrt',
  48102. bitcast: 'bitcast<f32>'
  48103. };
  48104. // WebGPU issue: does not support pow() with negative base on Windows
  48105. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  48106. wgslPolyfill.pow_float = new CodeNode( 'fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }' );
  48107. wgslPolyfill.pow_vec2 = new CodeNode( 'fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }', [ wgslPolyfill.pow_float ] );
  48108. wgslPolyfill.pow_vec3 = new CodeNode( 'fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }', [ wgslPolyfill.pow_float ] );
  48109. wgslPolyfill.pow_vec4 = new CodeNode( 'fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }', [ wgslPolyfill.pow_float ] );
  48110. wgslMethods.pow_float = 'tsl_pow_float';
  48111. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  48112. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  48113. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  48114. }
  48115. //
  48116. let diagnostics = '';
  48117. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  48118. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  48119. }
  48120. /**
  48121. * A node builder targeting WGSL.
  48122. *
  48123. * This module generates WGSL shader code from node materials and also
  48124. * generates the respective bindings and vertex buffer definitions. These
  48125. * data are later used by the renderer to create render and compute pipelines
  48126. * for render objects.
  48127. *
  48128. * @augments NodeBuilder
  48129. */
  48130. class WGSLNodeBuilder extends NodeBuilder {
  48131. /**
  48132. * Constructs a new WGSL node builder renderer.
  48133. *
  48134. * @param {Object3D} object - The 3D object.
  48135. * @param {Renderer} renderer - The renderer.
  48136. */
  48137. constructor( object, renderer ) {
  48138. super( object, renderer, new WGSLNodeParser() );
  48139. /**
  48140. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  48141. * another dictionary which manages UBOs per group ('render','frame','object').
  48142. *
  48143. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  48144. */
  48145. this.uniformGroups = {};
  48146. /**
  48147. * A dictionary that holds for each shader stage a Map of builtins.
  48148. *
  48149. * @type {Object<string,Map<string,Object>>}
  48150. */
  48151. this.builtins = {};
  48152. /**
  48153. * A dictionary that holds for each shader stage a Set of directives.
  48154. *
  48155. * @type {Object<string,Set<string>>}
  48156. */
  48157. this.directives = {};
  48158. /**
  48159. * A map for managing scope arrays. Only relevant for when using
  48160. * {@link WorkgroupInfoNode} in context of compute shaders.
  48161. *
  48162. * @type {Map<string,Object>}
  48163. */
  48164. this.scopedArrays = new Map();
  48165. }
  48166. /**
  48167. * Generates the WGSL snippet for sampled textures.
  48168. *
  48169. * @private
  48170. * @param {Texture} texture - The texture.
  48171. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48172. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48173. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48174. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48175. * @return {string} The WGSL snippet.
  48176. */
  48177. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  48178. if ( shaderStage === 'fragment' ) {
  48179. if ( depthSnippet ) {
  48180. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  48181. } else {
  48182. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  48183. }
  48184. } else {
  48185. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  48186. }
  48187. }
  48188. /**
  48189. * Generates the WGSL snippet when sampling textures with explicit mip level.
  48190. *
  48191. * @private
  48192. * @param {Texture} texture - The texture.
  48193. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48194. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48195. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48196. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48197. * @return {string} The WGSL snippet.
  48198. */
  48199. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet ) {
  48200. if ( this.isUnfilterable( texture ) === false ) {
  48201. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  48202. } else if ( this.isFilteredTexture( texture ) ) {
  48203. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  48204. } else {
  48205. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  48206. }
  48207. }
  48208. /**
  48209. * Generates a wrap function used in context of textures.
  48210. *
  48211. * @param {Texture} texture - The texture to generate the function for.
  48212. * @return {string} The name of the generated function.
  48213. */
  48214. generateWrapFunction( texture ) {
  48215. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  48216. let nodeCode = wgslCodeCache[ functionName ];
  48217. if ( nodeCode === undefined ) {
  48218. const includes = [];
  48219. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  48220. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  48221. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  48222. const addWrapSnippet = ( wrap, axis ) => {
  48223. if ( wrap === RepeatWrapping ) {
  48224. includes.push( wgslPolyfill.repeatWrapping_float );
  48225. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  48226. } else if ( wrap === ClampToEdgeWrapping ) {
  48227. includes.push( wgslPolyfill.clampWrapping_float );
  48228. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  48229. } else if ( wrap === MirroredRepeatWrapping ) {
  48230. includes.push( wgslPolyfill.mirrorWrapping_float );
  48231. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  48232. } else {
  48233. code += `\t\tcoord.${ axis }`;
  48234. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  48235. }
  48236. };
  48237. addWrapSnippet( texture.wrapS, 'x' );
  48238. code += ',\n';
  48239. addWrapSnippet( texture.wrapT, 'y' );
  48240. if ( texture.isData3DTexture ) {
  48241. code += ',\n';
  48242. addWrapSnippet( texture.wrapR, 'z' );
  48243. }
  48244. code += '\n\t);\n\n}\n';
  48245. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  48246. }
  48247. nodeCode.build( this );
  48248. return functionName;
  48249. }
  48250. /**
  48251. * Generates the array declaration string.
  48252. *
  48253. * @param {string} type - The type.
  48254. * @param {?number} [count] - The count.
  48255. * @return {string} The generated value as a shader string.
  48256. */
  48257. generateArrayDeclaration( type, count ) {
  48258. return `array< ${ this.getType( type ) }, ${ count } >`;
  48259. }
  48260. /**
  48261. * Generates a WGSL variable that holds the texture dimension of the given texture.
  48262. * It also returns information about the number of layers (elements) of an arrayed
  48263. * texture as well as the cube face count of cube textures.
  48264. *
  48265. * @param {Texture} texture - The texture to generate the function for.
  48266. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  48267. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48268. * @return {string} The name of the dimension variable.
  48269. */
  48270. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  48271. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  48272. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  48273. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  48274. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  48275. let textureDimensionsParams;
  48276. let dimensionType;
  48277. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  48278. const isMultisampled = primarySamples > 1;
  48279. if ( texture.isData3DTexture ) {
  48280. dimensionType = 'vec3<u32>';
  48281. } else {
  48282. // Regular 2D textures, depth textures, etc.
  48283. dimensionType = 'vec2<u32>';
  48284. }
  48285. // Build parameters string based on texture type and multisampling
  48286. if ( isMultisampled || texture.isStorageTexture ) {
  48287. textureDimensionsParams = textureProperty;
  48288. } else {
  48289. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  48290. }
  48291. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  48292. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  48293. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  48294. textureData.arrayLayerCount = new VarNode(
  48295. new ExpressionNode(
  48296. `textureNumLayers(${textureProperty})`,
  48297. 'u32'
  48298. )
  48299. );
  48300. }
  48301. // For cube textures, we know it's always 6 faces
  48302. if ( texture.isTextureCube ) {
  48303. textureData.cubeFaceCount = new VarNode(
  48304. new ExpressionNode( '6u', 'u32' )
  48305. );
  48306. }
  48307. }
  48308. return textureDimensionNode.build( this );
  48309. }
  48310. /**
  48311. * Generates the WGSL snippet for a manual filtered texture.
  48312. *
  48313. * @param {Texture} texture - The texture.
  48314. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48315. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48316. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48317. * @return {string} The WGSL snippet.
  48318. */
  48319. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  48320. this._include( 'biquadraticTexture' );
  48321. const wrapFunction = this.generateWrapFunction( texture );
  48322. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  48323. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  48324. }
  48325. /**
  48326. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  48327. * Since it's a lookup, no sampling or filtering is applied.
  48328. *
  48329. * @param {Texture} texture - The texture.
  48330. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48331. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48332. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48333. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48334. * @return {string} The WGSL snippet.
  48335. */
  48336. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  48337. const wrapFunction = this.generateWrapFunction( texture );
  48338. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  48339. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  48340. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  48341. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  48342. }
  48343. /**
  48344. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  48345. *
  48346. * @param {Texture} texture - The texture.
  48347. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48348. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48349. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48350. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48351. * @return {string} The WGSL snippet.
  48352. */
  48353. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  48354. let snippet;
  48355. if ( depthSnippet ) {
  48356. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  48357. } else {
  48358. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  48359. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  48360. snippet += '.x';
  48361. }
  48362. }
  48363. return snippet;
  48364. }
  48365. /**
  48366. * Generates the WGSL snippet that writes a single texel to a texture.
  48367. *
  48368. * @param {Texture} texture - The texture.
  48369. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48370. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48371. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48372. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  48373. * @return {string} The WGSL snippet.
  48374. */
  48375. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  48376. let snippet;
  48377. if ( depthSnippet ) {
  48378. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  48379. } else {
  48380. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  48381. }
  48382. return snippet;
  48383. }
  48384. /**
  48385. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  48386. *
  48387. * @param {Texture} texture - The texture.
  48388. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  48389. */
  48390. isSampleCompare( texture ) {
  48391. return texture.isDepthTexture === true && texture.compareFunction !== null;
  48392. }
  48393. /**
  48394. * Returns `true` if the given texture is unfilterable.
  48395. *
  48396. * @param {Texture} texture - The texture.
  48397. * @return {boolean} Whether the given texture is unfilterable or not.
  48398. */
  48399. isUnfilterable( texture ) {
  48400. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  48401. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  48402. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  48403. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  48404. }
  48405. /**
  48406. * Generates the WGSL snippet for sampling/loading the given texture.
  48407. *
  48408. * @param {Texture} texture - The texture.
  48409. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48410. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48411. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48412. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48413. * @return {string} The WGSL snippet.
  48414. */
  48415. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  48416. let snippet = null;
  48417. if ( this.isUnfilterable( texture ) ) {
  48418. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  48419. } else {
  48420. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  48421. }
  48422. return snippet;
  48423. }
  48424. /**
  48425. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  48426. *
  48427. * @param {Texture} texture - The texture.
  48428. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48429. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48430. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  48431. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48432. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48433. * @return {string} The WGSL snippet.
  48434. */
  48435. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  48436. if ( shaderStage === 'fragment' ) {
  48437. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  48438. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  48439. } else {
  48440. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  48441. }
  48442. }
  48443. /**
  48444. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  48445. * against a reference value.
  48446. *
  48447. * @param {Texture} texture - The texture.
  48448. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48449. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48450. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  48451. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48452. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48453. * @return {string} The WGSL snippet.
  48454. */
  48455. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  48456. if ( shaderStage === 'fragment' ) {
  48457. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  48458. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  48459. }
  48460. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  48461. } else {
  48462. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  48463. }
  48464. }
  48465. /**
  48466. * Generates the WGSL snippet when sampling textures with explicit mip level.
  48467. *
  48468. * @param {Texture} texture - The texture.
  48469. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48470. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48471. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  48472. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48473. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48474. * @return {string} The WGSL snippet.
  48475. */
  48476. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet ) {
  48477. if ( this.isUnfilterable( texture ) === false ) {
  48478. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  48479. } else if ( this.isFilteredTexture( texture ) ) {
  48480. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  48481. } else {
  48482. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  48483. }
  48484. }
  48485. /**
  48486. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  48487. *
  48488. * @param {Texture} texture - The texture.
  48489. * @param {string} textureProperty - The name of the texture uniform in the shader.
  48490. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  48491. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  48492. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  48493. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48494. * @return {string} The WGSL snippet.
  48495. */
  48496. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  48497. if ( shaderStage === 'fragment' ) {
  48498. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  48499. } else {
  48500. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  48501. }
  48502. }
  48503. /**
  48504. * Returns a WGSL snippet that represents the property name of the given node.
  48505. *
  48506. * @param {Node} node - The node.
  48507. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48508. * @return {string} The property name.
  48509. */
  48510. getPropertyName( node, shaderStage = this.shaderStage ) {
  48511. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  48512. if ( shaderStage === 'vertex' ) {
  48513. return `varyings.${ node.name }`;
  48514. }
  48515. } else if ( node.isNodeUniform === true ) {
  48516. const name = node.name;
  48517. const type = node.type;
  48518. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  48519. return name;
  48520. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  48521. if ( this.isCustomStruct( node ) ) {
  48522. return name;
  48523. }
  48524. return name + '.value';
  48525. } else {
  48526. return node.groupNode.name + '.' + name;
  48527. }
  48528. }
  48529. return super.getPropertyName( node );
  48530. }
  48531. /**
  48532. * Returns the output struct name.
  48533. *
  48534. * @return {string} The name of the output struct.
  48535. */
  48536. getOutputStructName() {
  48537. return 'output';
  48538. }
  48539. /**
  48540. * Returns the native shader operator name for a given generic name.
  48541. *
  48542. * @param {string} op - The operator name to resolve.
  48543. * @return {?string} The resolved operator name.
  48544. */
  48545. getFunctionOperator( op ) {
  48546. const fnOp = wgslFnOpLib[ op ];
  48547. if ( fnOp !== undefined ) {
  48548. this._include( fnOp );
  48549. return fnOp;
  48550. }
  48551. return null;
  48552. }
  48553. /**
  48554. * Returns the node access for the given node and shader stage.
  48555. *
  48556. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  48557. * @param {string} shaderStage - The shader stage.
  48558. * @return {string} The node access.
  48559. */
  48560. getNodeAccess( node, shaderStage ) {
  48561. if ( shaderStage !== 'compute' ) {
  48562. if ( node.isAtomic === true ) {
  48563. console.warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  48564. return NodeAccess.READ_WRITE;
  48565. }
  48566. return NodeAccess.READ_ONLY;
  48567. }
  48568. return node.access;
  48569. }
  48570. /**
  48571. * Returns A WGSL snippet representing the storage access.
  48572. *
  48573. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  48574. * @param {string} shaderStage - The shader stage.
  48575. * @return {string} The WGSL snippet representing the storage access.
  48576. */
  48577. getStorageAccess( node, shaderStage ) {
  48578. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  48579. }
  48580. /**
  48581. * This method is one of the more important ones since it's responsible
  48582. * for generating a matching binding instance for the given uniform node.
  48583. *
  48584. * These bindings are later used in the renderer to create bind groups
  48585. * and layouts.
  48586. *
  48587. * @param {UniformNode} node - The uniform node.
  48588. * @param {string} type - The node data type.
  48589. * @param {string} shaderStage - The shader stage.
  48590. * @param {?string} [name=null] - An optional uniform name.
  48591. * @return {NodeUniform} The node uniform object.
  48592. */
  48593. getUniformFromNode( node, type, shaderStage, name = null ) {
  48594. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  48595. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  48596. if ( nodeData.uniformGPU === undefined ) {
  48597. let uniformGPU;
  48598. const group = node.groupNode;
  48599. const groupName = group.name;
  48600. const bindings = this.getBindGroupArray( groupName, shaderStage );
  48601. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  48602. let texture = null;
  48603. const access = this.getNodeAccess( node, shaderStage );
  48604. if ( type === 'texture' || type === 'storageTexture' ) {
  48605. if ( node.value.is3DTexture === true ) {
  48606. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  48607. } else {
  48608. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  48609. }
  48610. } else if ( type === 'cubeTexture' ) {
  48611. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  48612. } else if ( type === 'texture3D' ) {
  48613. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  48614. }
  48615. texture.store = node.isStorageTextureNode === true;
  48616. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  48617. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  48618. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  48619. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  48620. bindings.push( sampler, texture );
  48621. uniformGPU = [ sampler, texture ];
  48622. } else {
  48623. bindings.push( texture );
  48624. uniformGPU = [ texture ];
  48625. }
  48626. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  48627. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  48628. const buffer = new bufferClass( node, group );
  48629. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  48630. bindings.push( buffer );
  48631. uniformGPU = buffer;
  48632. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  48633. } else {
  48634. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  48635. let uniformsGroup = uniformsStage[ groupName ];
  48636. if ( uniformsGroup === undefined ) {
  48637. uniformsGroup = new NodeUniformsGroup( groupName, group );
  48638. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  48639. uniformsStage[ groupName ] = uniformsGroup;
  48640. bindings.push( uniformsGroup );
  48641. }
  48642. uniformGPU = this.getNodeUniform( uniformNode, type );
  48643. uniformsGroup.addUniform( uniformGPU );
  48644. }
  48645. nodeData.uniformGPU = uniformGPU;
  48646. }
  48647. return uniformNode;
  48648. }
  48649. /**
  48650. * This method should be used whenever builtins are required in nodes.
  48651. * The internal builtins data structure will make sure builtins are
  48652. * defined in the WGSL source.
  48653. *
  48654. * @param {string} name - The builtin name.
  48655. * @param {string} property - The property name.
  48656. * @param {string} type - The node data type.
  48657. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48658. * @return {string} The property name.
  48659. */
  48660. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  48661. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  48662. if ( map.has( name ) === false ) {
  48663. map.set( name, {
  48664. name,
  48665. property,
  48666. type
  48667. } );
  48668. }
  48669. return property;
  48670. }
  48671. /**
  48672. * Returns `true` if the given builtin is defined in the given shader stage.
  48673. *
  48674. * @param {string} name - The builtin name.
  48675. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  48676. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  48677. */
  48678. hasBuiltin( name, shaderStage = this.shaderStage ) {
  48679. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  48680. }
  48681. /**
  48682. * Returns the vertex index builtin.
  48683. *
  48684. * @return {string} The vertex index.
  48685. */
  48686. getVertexIndex() {
  48687. if ( this.shaderStage === 'vertex' ) {
  48688. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  48689. }
  48690. return 'vertexIndex';
  48691. }
  48692. /**
  48693. * Builds the given shader node.
  48694. *
  48695. * @param {ShaderNodeInternal} shaderNode - The shader node.
  48696. * @return {string} The WGSL function code.
  48697. */
  48698. buildFunctionCode( shaderNode ) {
  48699. const layout = shaderNode.layout;
  48700. const flowData = this.flowShaderNode( shaderNode );
  48701. const parameters = [];
  48702. for ( const input of layout.inputs ) {
  48703. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  48704. }
  48705. //
  48706. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  48707. ${ flowData.vars }
  48708. ${ flowData.code }
  48709. `;
  48710. if ( flowData.result ) {
  48711. code += `\treturn ${ flowData.result };\n`;
  48712. }
  48713. code += '\n}\n';
  48714. //
  48715. return code;
  48716. }
  48717. /**
  48718. * Returns the instance index builtin.
  48719. *
  48720. * @return {string} The instance index.
  48721. */
  48722. getInstanceIndex() {
  48723. if ( this.shaderStage === 'vertex' ) {
  48724. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  48725. }
  48726. return 'instanceIndex';
  48727. }
  48728. /**
  48729. * Returns the invocation local index builtin.
  48730. *
  48731. * @return {string} The invocation local index.
  48732. */
  48733. getInvocationLocalIndex() {
  48734. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  48735. }
  48736. /**
  48737. * Returns the subgroup size builtin.
  48738. *
  48739. * @return {string} The subgroup size.
  48740. */
  48741. getSubgroupSize() {
  48742. this.enableSubGroups();
  48743. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  48744. }
  48745. /**
  48746. * Returns the invocation subgroup index builtin.
  48747. *
  48748. * @return {string} The invocation subgroup index.
  48749. */
  48750. getInvocationSubgroupIndex() {
  48751. this.enableSubGroups();
  48752. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  48753. }
  48754. /**
  48755. * Returns the subgroup index builtin.
  48756. *
  48757. * @return {string} The subgroup index.
  48758. */
  48759. getSubgroupIndex() {
  48760. this.enableSubGroups();
  48761. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  48762. }
  48763. /**
  48764. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  48765. *
  48766. * @return {null} Null.
  48767. */
  48768. getDrawIndex() {
  48769. return null;
  48770. }
  48771. /**
  48772. * Returns the front facing builtin.
  48773. *
  48774. * @return {string} The front facing builtin.
  48775. */
  48776. getFrontFacing() {
  48777. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  48778. }
  48779. /**
  48780. * Returns the frag coord builtin.
  48781. *
  48782. * @return {string} The frag coord builtin.
  48783. */
  48784. getFragCoord() {
  48785. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  48786. }
  48787. /**
  48788. * Returns the frag depth builtin.
  48789. *
  48790. * @return {string} The frag depth builtin.
  48791. */
  48792. getFragDepth() {
  48793. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  48794. }
  48795. /**
  48796. * Returns the clip distances builtin.
  48797. *
  48798. * @return {string} The clip distances builtin.
  48799. */
  48800. getClipDistance() {
  48801. return 'varyings.hw_clip_distances';
  48802. }
  48803. /**
  48804. * Whether to flip texture data along its vertical axis or not.
  48805. *
  48806. * @return {boolean} Returns always `false` in context of WGSL.
  48807. */
  48808. isFlipY() {
  48809. return false;
  48810. }
  48811. /**
  48812. * Enables the given directive for the given shader stage.
  48813. *
  48814. * @param {string} name - The directive name.
  48815. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  48816. */
  48817. enableDirective( name, shaderStage = this.shaderStage ) {
  48818. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  48819. stage.add( name );
  48820. }
  48821. /**
  48822. * Returns the directives of the given shader stage as a WGSL string.
  48823. *
  48824. * @param {string} shaderStage - The shader stage.
  48825. * @return {string} A WGSL snippet that enables the directives of the given stage.
  48826. */
  48827. getDirectives( shaderStage ) {
  48828. const snippets = [];
  48829. const directives = this.directives[ shaderStage ];
  48830. if ( directives !== undefined ) {
  48831. for ( const directive of directives ) {
  48832. snippets.push( `enable ${directive};` );
  48833. }
  48834. }
  48835. return snippets.join( '\n' );
  48836. }
  48837. /**
  48838. * Enables the 'subgroups' directive.
  48839. */
  48840. enableSubGroups() {
  48841. this.enableDirective( 'subgroups' );
  48842. }
  48843. /**
  48844. * Enables the 'subgroups-f16' directive.
  48845. */
  48846. enableSubgroupsF16() {
  48847. this.enableDirective( 'subgroups-f16' );
  48848. }
  48849. /**
  48850. * Enables the 'clip_distances' directive.
  48851. */
  48852. enableClipDistances() {
  48853. this.enableDirective( 'clip_distances' );
  48854. }
  48855. /**
  48856. * Enables the 'f16' directive.
  48857. */
  48858. enableShaderF16() {
  48859. this.enableDirective( 'f16' );
  48860. }
  48861. /**
  48862. * Enables the 'dual_source_blending' directive.
  48863. */
  48864. enableDualSourceBlending() {
  48865. this.enableDirective( 'dual_source_blending' );
  48866. }
  48867. /**
  48868. * Enables hardware clipping.
  48869. *
  48870. * @param {string} planeCount - The clipping plane count.
  48871. */
  48872. enableHardwareClipping( planeCount ) {
  48873. this.enableClipDistances();
  48874. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  48875. }
  48876. /**
  48877. * Returns the builtins of the given shader stage as a WGSL string.
  48878. *
  48879. * @param {string} shaderStage - The shader stage.
  48880. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  48881. */
  48882. getBuiltins( shaderStage ) {
  48883. const snippets = [];
  48884. const builtins = this.builtins[ shaderStage ];
  48885. if ( builtins !== undefined ) {
  48886. for ( const { name, property, type } of builtins.values() ) {
  48887. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  48888. }
  48889. }
  48890. return snippets.join( ',\n\t' );
  48891. }
  48892. /**
  48893. * This method should be used when a new scoped buffer is used in context of
  48894. * compute shaders. It adds the array to the internal data structure which is
  48895. * later used to generate the respective WGSL.
  48896. *
  48897. * @param {string} name - The array name.
  48898. * @param {string} scope - The scope.
  48899. * @param {string} bufferType - The buffer type.
  48900. * @param {string} bufferCount - The buffer count.
  48901. * @return {string} The array name.
  48902. */
  48903. getScopedArray( name, scope, bufferType, bufferCount ) {
  48904. if ( this.scopedArrays.has( name ) === false ) {
  48905. this.scopedArrays.set( name, {
  48906. name,
  48907. scope,
  48908. bufferType,
  48909. bufferCount
  48910. } );
  48911. }
  48912. return name;
  48913. }
  48914. /**
  48915. * Returns the scoped arrays of the given shader stage as a WGSL string.
  48916. *
  48917. * @param {string} shaderStage - The shader stage.
  48918. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  48919. * Returns `undefined` when used in the vertex or fragment stage.
  48920. */
  48921. getScopedArrays( shaderStage ) {
  48922. if ( shaderStage !== 'compute' ) {
  48923. return;
  48924. }
  48925. const snippets = [];
  48926. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  48927. const type = this.getType( bufferType );
  48928. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  48929. }
  48930. return snippets.join( '\n' );
  48931. }
  48932. /**
  48933. * Returns the shader attributes of the given shader stage as a WGSL string.
  48934. *
  48935. * @param {string} shaderStage - The shader stage.
  48936. * @return {string} The WGSL snippet that defines the shader attributes.
  48937. */
  48938. getAttributes( shaderStage ) {
  48939. const snippets = [];
  48940. if ( shaderStage === 'compute' ) {
  48941. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  48942. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  48943. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  48944. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  48945. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  48946. this.enableDirective( 'subgroups', shaderStage );
  48947. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  48948. }
  48949. }
  48950. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  48951. const builtins = this.getBuiltins( 'attribute' );
  48952. if ( builtins ) snippets.push( builtins );
  48953. const attributes = this.getAttributesArray();
  48954. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  48955. const attribute = attributes[ index ];
  48956. const name = attribute.name;
  48957. const type = this.getType( attribute.type );
  48958. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  48959. }
  48960. }
  48961. return snippets.join( ',\n\t' );
  48962. }
  48963. /**
  48964. * Returns the members of the given struct type node as a WGSL string.
  48965. *
  48966. * @param {StructTypeNode} struct - The struct type node.
  48967. * @return {string} The WGSL snippet that defines the struct members.
  48968. */
  48969. getStructMembers( struct ) {
  48970. const snippets = [];
  48971. for ( const member of struct.members ) {
  48972. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  48973. let type = this.getType( member.type );
  48974. if ( member.atomic ) {
  48975. type = 'atomic< ' + type + ' >';
  48976. }
  48977. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  48978. }
  48979. if ( struct.output ) {
  48980. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  48981. }
  48982. return snippets.join( ',\n' );
  48983. }
  48984. /**
  48985. * Returns the structs of the given shader stage as a WGSL string.
  48986. *
  48987. * @param {string} shaderStage - The shader stage.
  48988. * @return {string} The WGSL snippet that defines the structs.
  48989. */
  48990. getStructs( shaderStage ) {
  48991. let result = '';
  48992. const structs = this.structs[ shaderStage ];
  48993. if ( structs.length > 0 ) {
  48994. const snippets = [];
  48995. for ( const struct of structs ) {
  48996. let snippet = `struct ${ struct.name } {\n`;
  48997. snippet += this.getStructMembers( struct );
  48998. snippet += '\n};';
  48999. snippets.push( snippet );
  49000. }
  49001. result = '\n' + snippets.join( '\n\n' ) + '\n';
  49002. }
  49003. return result;
  49004. }
  49005. /**
  49006. * Returns a WGSL string representing a variable.
  49007. *
  49008. * @param {string} type - The variable's type.
  49009. * @param {string} name - The variable's name.
  49010. * @param {?number} [count=null] - The array length.
  49011. * @return {string} The WGSL snippet that defines a variable.
  49012. */
  49013. getVar( type, name, count = null ) {
  49014. let snippet = `var ${ name } : `;
  49015. if ( count !== null ) {
  49016. snippet += this.generateArrayDeclaration( type, count );
  49017. } else {
  49018. snippet += this.getType( type );
  49019. }
  49020. return snippet;
  49021. }
  49022. /**
  49023. * Returns the variables of the given shader stage as a WGSL string.
  49024. *
  49025. * @param {string} shaderStage - The shader stage.
  49026. * @return {string} The WGSL snippet that defines the variables.
  49027. */
  49028. getVars( shaderStage ) {
  49029. const snippets = [];
  49030. const vars = this.vars[ shaderStage ];
  49031. if ( vars !== undefined ) {
  49032. for ( const variable of vars ) {
  49033. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  49034. }
  49035. }
  49036. return `\n${ snippets.join( '\n' ) }\n`;
  49037. }
  49038. /**
  49039. * Returns the varyings of the given shader stage as a WGSL string.
  49040. *
  49041. * @param {string} shaderStage - The shader stage.
  49042. * @return {string} The WGSL snippet that defines the varyings.
  49043. */
  49044. getVaryings( shaderStage ) {
  49045. const snippets = [];
  49046. if ( shaderStage === 'vertex' ) {
  49047. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  49048. }
  49049. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  49050. const varyings = this.varyings;
  49051. const vars = this.vars[ shaderStage ];
  49052. for ( let index = 0; index < varyings.length; index ++ ) {
  49053. const varying = varyings[ index ];
  49054. if ( varying.needsInterpolation ) {
  49055. let attributesSnippet = `@location( ${index} )`;
  49056. if ( varying.interpolationType ) {
  49057. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  49058. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  49059. // Otherwise, optimize interpolation when sensible
  49060. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  49061. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  49062. }
  49063. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  49064. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  49065. vars.push( varying );
  49066. }
  49067. }
  49068. }
  49069. const builtins = this.getBuiltins( shaderStage );
  49070. if ( builtins ) snippets.push( builtins );
  49071. const code = snippets.join( ',\n\t' );
  49072. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  49073. }
  49074. isCustomStruct( nodeUniform ) {
  49075. const attribute = nodeUniform.value;
  49076. const bufferNode = nodeUniform.node;
  49077. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  49078. const isStructArray =
  49079. ( bufferNode.value && bufferNode.value.array ) &&
  49080. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  49081. return isAttributeStructType && ! isStructArray;
  49082. }
  49083. /**
  49084. * Returns the uniforms of the given shader stage as a WGSL string.
  49085. *
  49086. * @param {string} shaderStage - The shader stage.
  49087. * @return {string} The WGSL snippet that defines the uniforms.
  49088. */
  49089. getUniforms( shaderStage ) {
  49090. const uniforms = this.uniforms[ shaderStage ];
  49091. const bindingSnippets = [];
  49092. const bufferSnippets = [];
  49093. const structSnippets = [];
  49094. const uniformGroups = {};
  49095. for ( const uniform of uniforms ) {
  49096. const groupName = uniform.groupNode.name;
  49097. const uniformIndexes = this.bindingsIndexes[ groupName ];
  49098. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  49099. const texture = uniform.node.value;
  49100. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  49101. if ( this.isSampleCompare( texture ) ) {
  49102. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  49103. } else {
  49104. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  49105. }
  49106. }
  49107. let textureType;
  49108. let multisampled = '';
  49109. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  49110. if ( primarySamples > 1 ) {
  49111. multisampled = '_multisampled';
  49112. }
  49113. if ( texture.isCubeTexture === true ) {
  49114. textureType = 'texture_cube<f32>';
  49115. } else if ( texture.isDepthTexture === true ) {
  49116. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  49117. textureType = `texture${ multisampled }_2d<f32>`;
  49118. } else {
  49119. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  49120. }
  49121. } else if ( uniform.node.isStorageTextureNode === true ) {
  49122. const format = getFormat( texture );
  49123. const access = this.getStorageAccess( uniform.node, shaderStage );
  49124. const is3D = uniform.node.value.is3DTexture;
  49125. const isArrayTexture = uniform.node.value.isArrayTexture;
  49126. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  49127. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  49128. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  49129. textureType = 'texture_2d_array<f32>';
  49130. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  49131. textureType = 'texture_3d<f32>';
  49132. } else {
  49133. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  49134. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  49135. }
  49136. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  49137. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  49138. const bufferNode = uniform.node;
  49139. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  49140. const bufferCount = bufferNode.bufferCount;
  49141. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  49142. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  49143. if ( this.isCustomStruct( uniform ) ) {
  49144. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  49145. } else {
  49146. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  49147. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  49148. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  49149. }
  49150. } else {
  49151. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  49152. const groupName = uniform.groupNode.name;
  49153. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  49154. index: uniformIndexes.binding ++,
  49155. id: uniformIndexes.group,
  49156. snippets: []
  49157. } );
  49158. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  49159. }
  49160. }
  49161. for ( const name in uniformGroups ) {
  49162. const group = uniformGroups[ name ];
  49163. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  49164. }
  49165. let code = bindingSnippets.join( '\n' );
  49166. code += bufferSnippets.join( '\n' );
  49167. code += structSnippets.join( '\n' );
  49168. return code;
  49169. }
  49170. /**
  49171. * Controls the code build of the shader stages.
  49172. */
  49173. buildCode() {
  49174. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  49175. this.sortBindingGroups();
  49176. for ( const shaderStage in shadersData ) {
  49177. this.shaderStage = shaderStage;
  49178. const stageData = shadersData[ shaderStage ];
  49179. stageData.uniforms = this.getUniforms( shaderStage );
  49180. stageData.attributes = this.getAttributes( shaderStage );
  49181. stageData.varyings = this.getVaryings( shaderStage );
  49182. stageData.structs = this.getStructs( shaderStage );
  49183. stageData.vars = this.getVars( shaderStage );
  49184. stageData.codes = this.getCodes( shaderStage );
  49185. stageData.directives = this.getDirectives( shaderStage );
  49186. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  49187. //
  49188. let flow = '// code\n\n';
  49189. flow += this.flowCode[ shaderStage ];
  49190. const flowNodes = this.flowNodes[ shaderStage ];
  49191. const mainNode = flowNodes[ flowNodes.length - 1 ];
  49192. const outputNode = mainNode.outputNode;
  49193. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  49194. for ( const node of flowNodes ) {
  49195. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  49196. const slotName = node.name;
  49197. if ( slotName ) {
  49198. if ( flow.length > 0 ) flow += '\n';
  49199. flow += `\t// flow -> ${ slotName }\n`;
  49200. }
  49201. flow += `${ flowSlotData.code }\n\t`;
  49202. if ( node === mainNode && shaderStage !== 'compute' ) {
  49203. flow += '// result\n\n\t';
  49204. if ( shaderStage === 'vertex' ) {
  49205. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  49206. } else if ( shaderStage === 'fragment' ) {
  49207. if ( isOutputStruct ) {
  49208. stageData.returnType = outputNode.getNodeType( this );
  49209. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  49210. flow += `return ${ flowSlotData.result };`;
  49211. } else {
  49212. let structSnippet = '\t@location(0) color: vec4<f32>';
  49213. const builtins = this.getBuiltins( 'output' );
  49214. if ( builtins ) structSnippet += ',\n\t' + builtins;
  49215. stageData.returnType = 'OutputStruct';
  49216. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  49217. stageData.structs += '\nvar<private> output : OutputStruct;';
  49218. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  49219. }
  49220. }
  49221. }
  49222. }
  49223. stageData.flow = flow;
  49224. }
  49225. this.shaderStage = null;
  49226. if ( this.material !== null ) {
  49227. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  49228. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  49229. } else {
  49230. // Early strictly validated in computeNode
  49231. const workgroupSize = this.object.workgroupSize;
  49232. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  49233. }
  49234. }
  49235. /**
  49236. * Returns the native shader method name for a given generic name.
  49237. *
  49238. * @param {string} method - The method name to resolve.
  49239. * @param {?string} [output=null] - An optional output.
  49240. * @return {string} The resolved WGSL method name.
  49241. */
  49242. getMethod( method, output = null ) {
  49243. let wgslMethod;
  49244. if ( output !== null ) {
  49245. wgslMethod = this._getWGSLMethod( method + '_' + output );
  49246. }
  49247. if ( wgslMethod === undefined ) {
  49248. wgslMethod = this._getWGSLMethod( method );
  49249. }
  49250. return wgslMethod || method;
  49251. }
  49252. /**
  49253. * Returns the native snippet for a ternary operation.
  49254. *
  49255. * @param {string} condSnippet - The condition determining which expression gets resolved.
  49256. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  49257. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  49258. * @return {string} The resolved method name.
  49259. */
  49260. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  49261. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  49262. }
  49263. /**
  49264. * Returns the WGSL type of the given node data type.
  49265. *
  49266. * @param {string} type - The node data type.
  49267. * @return {string} The WGSL type.
  49268. */
  49269. getType( type ) {
  49270. return wgslTypeLib[ type ] || type;
  49271. }
  49272. /**
  49273. * Whether the requested feature is available or not.
  49274. *
  49275. * @param {string} name - The requested feature.
  49276. * @return {boolean} Whether the requested feature is supported or not.
  49277. */
  49278. isAvailable( name ) {
  49279. let result = supports[ name ];
  49280. if ( result === undefined ) {
  49281. if ( name === 'float32Filterable' ) {
  49282. result = this.renderer.hasFeature( 'float32-filterable' );
  49283. } else if ( name === 'clipDistance' ) {
  49284. result = this.renderer.hasFeature( 'clip-distances' );
  49285. }
  49286. supports[ name ] = result;
  49287. }
  49288. return result;
  49289. }
  49290. /**
  49291. * Returns the native shader method name for a given generic name.
  49292. *
  49293. * @private
  49294. * @param {string} method - The method name to resolve.
  49295. * @return {string} The resolved WGSL method name.
  49296. */
  49297. _getWGSLMethod( method ) {
  49298. if ( wgslPolyfill[ method ] !== undefined ) {
  49299. this._include( method );
  49300. }
  49301. return wgslMethods[ method ];
  49302. }
  49303. /**
  49304. * Includes the given method name into the current
  49305. * function node.
  49306. *
  49307. * @private
  49308. * @param {string} name - The method name to include.
  49309. * @return {CodeNode} The respective code node.
  49310. */
  49311. _include( name ) {
  49312. const codeNode = wgslPolyfill[ name ];
  49313. codeNode.build( this );
  49314. if ( this.currentFunctionNode !== null ) {
  49315. this.currentFunctionNode.includes.push( codeNode );
  49316. }
  49317. return codeNode;
  49318. }
  49319. /**
  49320. * Returns a WGSL vertex shader based on the given shader data.
  49321. *
  49322. * @private
  49323. * @param {Object} shaderData - The shader data.
  49324. * @return {string} The vertex shader.
  49325. */
  49326. _getWGSLVertexCode( shaderData ) {
  49327. return `${ this.getSignature() }
  49328. // directives
  49329. ${shaderData.directives}
  49330. // structs
  49331. ${shaderData.structs}
  49332. // uniforms
  49333. ${shaderData.uniforms}
  49334. // varyings
  49335. ${shaderData.varyings}
  49336. var<private> varyings : VaryingsStruct;
  49337. // codes
  49338. ${shaderData.codes}
  49339. @vertex
  49340. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  49341. // vars
  49342. ${shaderData.vars}
  49343. // flow
  49344. ${shaderData.flow}
  49345. return varyings;
  49346. }
  49347. `;
  49348. }
  49349. /**
  49350. * Returns a WGSL fragment shader based on the given shader data.
  49351. *
  49352. * @private
  49353. * @param {Object} shaderData - The shader data.
  49354. * @return {string} The vertex shader.
  49355. */
  49356. _getWGSLFragmentCode( shaderData ) {
  49357. return `${ this.getSignature() }
  49358. // global
  49359. ${ diagnostics }
  49360. // structs
  49361. ${shaderData.structs}
  49362. // uniforms
  49363. ${shaderData.uniforms}
  49364. // codes
  49365. ${shaderData.codes}
  49366. @fragment
  49367. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  49368. // vars
  49369. ${shaderData.vars}
  49370. // flow
  49371. ${shaderData.flow}
  49372. }
  49373. `;
  49374. }
  49375. /**
  49376. * Returns a WGSL compute shader based on the given shader data.
  49377. *
  49378. * @private
  49379. * @param {Object} shaderData - The shader data.
  49380. * @param {string} workgroupSize - The workgroup size.
  49381. * @return {string} The vertex shader.
  49382. */
  49383. _getWGSLComputeCode( shaderData, workgroupSize ) {
  49384. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  49385. return `${ this.getSignature() }
  49386. // directives
  49387. ${ shaderData.directives }
  49388. // system
  49389. var<private> instanceIndex : u32;
  49390. // locals
  49391. ${ shaderData.scopedArrays }
  49392. // structs
  49393. ${ shaderData.structs }
  49394. // uniforms
  49395. ${ shaderData.uniforms }
  49396. // codes
  49397. ${ shaderData.codes }
  49398. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  49399. fn main( ${ shaderData.attributes } ) {
  49400. // system
  49401. instanceIndex = globalId.x
  49402. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  49403. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  49404. // vars
  49405. ${ shaderData.vars }
  49406. // flow
  49407. ${ shaderData.flow }
  49408. }
  49409. `;
  49410. }
  49411. /**
  49412. * Returns a WGSL struct based on the given name and variables.
  49413. *
  49414. * @private
  49415. * @param {string} name - The struct name.
  49416. * @param {string} vars - The struct variables.
  49417. * @return {string} The WGSL snippet representing a struct.
  49418. */
  49419. _getWGSLStruct( name, vars ) {
  49420. return `
  49421. struct ${name} {
  49422. ${vars}
  49423. };`;
  49424. }
  49425. /**
  49426. * Returns a WGSL struct binding.
  49427. *
  49428. * @private
  49429. * @param {string} name - The struct name.
  49430. * @param {string} vars - The struct variables.
  49431. * @param {string} access - The access.
  49432. * @param {number} [binding=0] - The binding index.
  49433. * @param {number} [group=0] - The group index.
  49434. * @return {string} The WGSL snippet representing a struct binding.
  49435. */
  49436. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  49437. const structName = name + 'Struct';
  49438. const structSnippet = this._getWGSLStruct( structName, vars );
  49439. return `${structSnippet}
  49440. @binding( ${ binding } ) @group( ${ group } )
  49441. var<${access}> ${ name } : ${ structName };`;
  49442. }
  49443. }
  49444. /**
  49445. * A WebGPU backend utility module with common helpers.
  49446. *
  49447. * @private
  49448. */
  49449. class WebGPUUtils {
  49450. /**
  49451. * Constructs a new utility object.
  49452. *
  49453. * @param {WebGPUBackend} backend - The WebGPU backend.
  49454. */
  49455. constructor( backend ) {
  49456. /**
  49457. * A reference to the WebGPU backend.
  49458. *
  49459. * @type {WebGPUBackend}
  49460. */
  49461. this.backend = backend;
  49462. }
  49463. /**
  49464. * Returns the depth/stencil GPU format for the given render context.
  49465. *
  49466. * @param {RenderContext} renderContext - The render context.
  49467. * @return {string} The depth/stencil GPU texture format.
  49468. */
  49469. getCurrentDepthStencilFormat( renderContext ) {
  49470. let format;
  49471. if ( renderContext.depthTexture !== null ) {
  49472. format = this.getTextureFormatGPU( renderContext.depthTexture );
  49473. } else if ( renderContext.depth && renderContext.stencil ) {
  49474. format = GPUTextureFormat.Depth24PlusStencil8;
  49475. } else if ( renderContext.depth ) {
  49476. format = GPUTextureFormat.Depth24Plus;
  49477. }
  49478. return format;
  49479. }
  49480. /**
  49481. * Returns the GPU format for the given texture.
  49482. *
  49483. * @param {Texture} texture - The texture.
  49484. * @return {string} The GPU texture format.
  49485. */
  49486. getTextureFormatGPU( texture ) {
  49487. return this.backend.get( texture ).format;
  49488. }
  49489. /**
  49490. * Returns an object that defines the multi-sampling state of the given texture.
  49491. *
  49492. * @param {Texture} texture - The texture.
  49493. * @return {Object} The multi-sampling state.
  49494. */
  49495. getTextureSampleData( texture ) {
  49496. let samples;
  49497. if ( texture.isFramebufferTexture ) {
  49498. samples = 1;
  49499. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  49500. const renderer = this.backend.renderer;
  49501. const renderTarget = renderer.getRenderTarget();
  49502. samples = renderTarget ? renderTarget.samples : renderer.samples;
  49503. } else if ( texture.renderTarget ) {
  49504. samples = texture.renderTarget.samples;
  49505. }
  49506. samples = samples || 1;
  49507. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  49508. const primarySamples = isMSAA ? 1 : samples;
  49509. return { samples, primarySamples, isMSAA };
  49510. }
  49511. /**
  49512. * Returns the default color attachment's GPU format of the current render context.
  49513. *
  49514. * @param {RenderContext} renderContext - The render context.
  49515. * @return {string} The GPU texture format of the default color attachment.
  49516. */
  49517. getCurrentColorFormat( renderContext ) {
  49518. let format;
  49519. if ( renderContext.textures !== null ) {
  49520. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  49521. } else {
  49522. format = this.getPreferredCanvasFormat(); // default context format
  49523. }
  49524. return format;
  49525. }
  49526. /**
  49527. * Returns the output color space of the current render context.
  49528. *
  49529. * @param {RenderContext} renderContext - The render context.
  49530. * @return {string} The output color space.
  49531. */
  49532. getCurrentColorSpace( renderContext ) {
  49533. if ( renderContext.textures !== null ) {
  49534. return renderContext.textures[ 0 ].colorSpace;
  49535. }
  49536. return this.backend.renderer.outputColorSpace;
  49537. }
  49538. /**
  49539. * Returns GPU primitive topology for the given object and material.
  49540. *
  49541. * @param {Object3D} object - The 3D object.
  49542. * @param {Material} material - The material.
  49543. * @return {string} The GPU primitive topology.
  49544. */
  49545. getPrimitiveTopology( object, material ) {
  49546. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  49547. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  49548. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  49549. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  49550. }
  49551. /**
  49552. * Returns a modified sample count from the given sample count value.
  49553. *
  49554. * That is required since WebGPU only supports either 1 or 4.
  49555. *
  49556. * @param {number} sampleCount - The input sample count.
  49557. * @return {number} The (potentially updated) output sample count.
  49558. */
  49559. getSampleCount( sampleCount ) {
  49560. return sampleCount >= 4 ? 4 : 1;
  49561. }
  49562. /**
  49563. * Returns the sample count of the given render context.
  49564. *
  49565. * @param {RenderContext} renderContext - The render context.
  49566. * @return {number} The sample count.
  49567. */
  49568. getSampleCountRenderContext( renderContext ) {
  49569. if ( renderContext.textures !== null ) {
  49570. return this.getSampleCount( renderContext.sampleCount );
  49571. }
  49572. return this.getSampleCount( this.backend.renderer.samples );
  49573. }
  49574. /**
  49575. * Returns the preferred canvas format.
  49576. *
  49577. * There is a separate method for this so it's possible to
  49578. * honor edge cases for specific devices.
  49579. *
  49580. * @return {string} The GPU texture format of the canvas.
  49581. */
  49582. getPreferredCanvasFormat() {
  49583. const outputType = this.backend.parameters.outputType;
  49584. if ( outputType === undefined ) {
  49585. return navigator.gpu.getPreferredCanvasFormat();
  49586. } else if ( outputType === UnsignedByteType ) {
  49587. return GPUTextureFormat.BGRA8Unorm;
  49588. } else if ( outputType === HalfFloatType ) {
  49589. return GPUTextureFormat.RGBA16Float;
  49590. } else {
  49591. throw new Error( 'Unsupported outputType' );
  49592. }
  49593. }
  49594. }
  49595. const typedArraysToVertexFormatPrefix = new Map( [
  49596. [ Int8Array, [ 'sint8', 'snorm8' ]],
  49597. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  49598. [ Int16Array, [ 'sint16', 'snorm16' ]],
  49599. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  49600. [ Int32Array, [ 'sint32', 'snorm32' ]],
  49601. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  49602. [ Float32Array, [ 'float32', ]],
  49603. ] );
  49604. if ( typeof Float16Array !== 'undefined' ) {
  49605. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  49606. }
  49607. const typedAttributeToVertexFormatPrefix = new Map( [
  49608. [ Float16BufferAttribute, [ 'float16', ]],
  49609. ] );
  49610. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  49611. [ Int32Array, 'sint32' ],
  49612. [ Int16Array, 'sint32' ], // patch for INT16
  49613. [ Uint32Array, 'uint32' ],
  49614. [ Uint16Array, 'uint32' ], // patch for UINT16
  49615. [ Float32Array, 'float32' ]
  49616. ] );
  49617. /**
  49618. * A WebGPU backend utility module for managing shader attributes.
  49619. *
  49620. * @private
  49621. */
  49622. class WebGPUAttributeUtils {
  49623. /**
  49624. * Constructs a new utility object.
  49625. *
  49626. * @param {WebGPUBackend} backend - The WebGPU backend.
  49627. */
  49628. constructor( backend ) {
  49629. /**
  49630. * A reference to the WebGPU backend.
  49631. *
  49632. * @type {WebGPUBackend}
  49633. */
  49634. this.backend = backend;
  49635. }
  49636. /**
  49637. * Creates the GPU buffer for the given buffer attribute.
  49638. *
  49639. * @param {BufferAttribute} attribute - The buffer attribute.
  49640. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  49641. */
  49642. createAttribute( attribute, usage ) {
  49643. const bufferAttribute = this._getBufferAttribute( attribute );
  49644. const backend = this.backend;
  49645. const bufferData = backend.get( bufferAttribute );
  49646. let buffer = bufferData.buffer;
  49647. if ( buffer === undefined ) {
  49648. const device = backend.device;
  49649. let array = bufferAttribute.array;
  49650. // patch for INT16 and UINT16
  49651. if ( attribute.normalized === false ) {
  49652. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  49653. array = new Int32Array( array );
  49654. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  49655. array = new Uint32Array( array );
  49656. if ( usage & GPUBufferUsage.INDEX ) {
  49657. for ( let i = 0; i < array.length; i ++ ) {
  49658. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  49659. }
  49660. }
  49661. }
  49662. }
  49663. bufferAttribute.array = array;
  49664. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  49665. array = new array.constructor( bufferAttribute.count * 4 );
  49666. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  49667. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  49668. }
  49669. // Update BufferAttribute
  49670. bufferAttribute.itemSize = 4;
  49671. bufferAttribute.array = array;
  49672. bufferData._force3to4BytesAlignment = true;
  49673. }
  49674. // ensure 4 byte alignment
  49675. const byteLength = array.byteLength;
  49676. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  49677. buffer = device.createBuffer( {
  49678. label: bufferAttribute.name,
  49679. size: size,
  49680. usage: usage,
  49681. mappedAtCreation: true
  49682. } );
  49683. new array.constructor( buffer.getMappedRange() ).set( array );
  49684. buffer.unmap();
  49685. bufferData.buffer = buffer;
  49686. }
  49687. }
  49688. /**
  49689. * Updates the GPU buffer of the given buffer attribute.
  49690. *
  49691. * @param {BufferAttribute} attribute - The buffer attribute.
  49692. */
  49693. updateAttribute( attribute ) {
  49694. const bufferAttribute = this._getBufferAttribute( attribute );
  49695. const backend = this.backend;
  49696. const device = backend.device;
  49697. const bufferData = backend.get( bufferAttribute );
  49698. const buffer = backend.get( bufferAttribute ).buffer;
  49699. let array = bufferAttribute.array;
  49700. // if storage buffer ensure 4 byte alignment
  49701. if ( bufferData._force3to4BytesAlignment === true ) {
  49702. array = new array.constructor( bufferAttribute.count * 4 );
  49703. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  49704. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  49705. }
  49706. bufferAttribute.array = array;
  49707. }
  49708. const isTypedArray = this._isTypedArray( array );
  49709. const updateRanges = bufferAttribute.updateRanges;
  49710. if ( updateRanges.length === 0 ) {
  49711. // Not using update ranges
  49712. device.queue.writeBuffer(
  49713. buffer,
  49714. 0,
  49715. array,
  49716. 0
  49717. );
  49718. } else {
  49719. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  49720. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  49721. const range = updateRanges[ i ];
  49722. let dataOffset, size;
  49723. if ( bufferData._force3to4BytesAlignment === true ) {
  49724. const vertexStart = Math.floor( range.start / 3 );
  49725. const vertexCount = Math.ceil( range.count / 3 );
  49726. dataOffset = vertexStart * 4 * byteOffsetFactor;
  49727. size = vertexCount * 4 * byteOffsetFactor;
  49728. } else {
  49729. dataOffset = range.start * byteOffsetFactor;
  49730. size = range.count * byteOffsetFactor;
  49731. }
  49732. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  49733. device.queue.writeBuffer(
  49734. buffer,
  49735. bufferOffset,
  49736. array,
  49737. dataOffset,
  49738. size
  49739. );
  49740. }
  49741. bufferAttribute.clearUpdateRanges();
  49742. }
  49743. }
  49744. /**
  49745. * This method creates the vertex buffer layout data which are
  49746. * require when creating a render pipeline for the given render object.
  49747. *
  49748. * @param {RenderObject} renderObject - The render object.
  49749. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  49750. */
  49751. createShaderVertexBuffers( renderObject ) {
  49752. const attributes = renderObject.getAttributes();
  49753. const vertexBuffers = new Map();
  49754. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  49755. const geometryAttribute = attributes[ slot ];
  49756. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  49757. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  49758. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  49759. if ( vertexBufferLayout === undefined ) {
  49760. let arrayStride, stepMode;
  49761. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  49762. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  49763. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  49764. } else {
  49765. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  49766. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  49767. }
  49768. // patch for INT16 and UINT16
  49769. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  49770. arrayStride = 4;
  49771. }
  49772. vertexBufferLayout = {
  49773. arrayStride,
  49774. attributes: [],
  49775. stepMode
  49776. };
  49777. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  49778. }
  49779. const format = this._getVertexFormat( geometryAttribute );
  49780. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  49781. vertexBufferLayout.attributes.push( {
  49782. shaderLocation: slot,
  49783. offset,
  49784. format
  49785. } );
  49786. }
  49787. return Array.from( vertexBuffers.values() );
  49788. }
  49789. /**
  49790. * Destroys the GPU buffer of the given buffer attribute.
  49791. *
  49792. * @param {BufferAttribute} attribute - The buffer attribute.
  49793. */
  49794. destroyAttribute( attribute ) {
  49795. const backend = this.backend;
  49796. const data = backend.get( this._getBufferAttribute( attribute ) );
  49797. data.buffer.destroy();
  49798. backend.delete( attribute );
  49799. }
  49800. /**
  49801. * This method performs a readback operation by moving buffer data from
  49802. * a storage buffer attribute from the GPU to the CPU.
  49803. *
  49804. * @async
  49805. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  49806. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  49807. */
  49808. async getArrayBufferAsync( attribute ) {
  49809. const backend = this.backend;
  49810. const device = backend.device;
  49811. const data = backend.get( this._getBufferAttribute( attribute ) );
  49812. const bufferGPU = data.buffer;
  49813. const size = bufferGPU.size;
  49814. const readBufferGPU = device.createBuffer( {
  49815. label: `${ attribute.name }_readback`,
  49816. size,
  49817. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  49818. } );
  49819. const cmdEncoder = device.createCommandEncoder( {
  49820. label: `readback_encoder_${ attribute.name }`
  49821. } );
  49822. cmdEncoder.copyBufferToBuffer(
  49823. bufferGPU,
  49824. 0,
  49825. readBufferGPU,
  49826. 0,
  49827. size
  49828. );
  49829. const gpuCommands = cmdEncoder.finish();
  49830. device.queue.submit( [ gpuCommands ] );
  49831. await readBufferGPU.mapAsync( GPUMapMode.READ );
  49832. const arrayBuffer = readBufferGPU.getMappedRange();
  49833. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  49834. readBufferGPU.unmap();
  49835. return dstBuffer.buffer;
  49836. }
  49837. /**
  49838. * Returns the vertex format of the given buffer attribute.
  49839. *
  49840. * @private
  49841. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  49842. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  49843. */
  49844. _getVertexFormat( geometryAttribute ) {
  49845. const { itemSize, normalized } = geometryAttribute;
  49846. const ArrayType = geometryAttribute.array.constructor;
  49847. const AttributeType = geometryAttribute.constructor;
  49848. let format;
  49849. if ( itemSize === 1 ) {
  49850. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  49851. } else {
  49852. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  49853. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  49854. if ( prefix ) {
  49855. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  49856. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  49857. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  49858. if ( paddedItemSize % 1 ) {
  49859. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  49860. }
  49861. format = `${prefix}x${paddedItemSize}`;
  49862. }
  49863. }
  49864. if ( ! format ) {
  49865. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  49866. }
  49867. return format;
  49868. }
  49869. /**
  49870. * Returns `true` if the given array is a typed array.
  49871. *
  49872. * @private
  49873. * @param {any} array - The array.
  49874. * @return {boolean} Whether the given array is a typed array or not.
  49875. */
  49876. _isTypedArray( array ) {
  49877. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  49878. }
  49879. /**
  49880. * Utility method for handling interleaved buffer attributes correctly.
  49881. * To process them, their `InterleavedBuffer` is returned.
  49882. *
  49883. * @private
  49884. * @param {BufferAttribute} attribute - The attribute.
  49885. * @return {BufferAttribute|InterleavedBuffer}
  49886. */
  49887. _getBufferAttribute( attribute ) {
  49888. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  49889. return attribute;
  49890. }
  49891. }
  49892. /**
  49893. * A WebGPU backend utility module for managing bindings.
  49894. *
  49895. * When reading the documentation it's helpful to keep in mind that
  49896. * all class definitions starting with 'GPU*' are modules from the
  49897. * WebGPU API. So for example `BindGroup` is a class from the engine
  49898. * whereas `GPUBindGroup` is a class from WebGPU.
  49899. *
  49900. * @private
  49901. */
  49902. class WebGPUBindingUtils {
  49903. /**
  49904. * Constructs a new utility object.
  49905. *
  49906. * @param {WebGPUBackend} backend - The WebGPU backend.
  49907. */
  49908. constructor( backend ) {
  49909. /**
  49910. * A reference to the WebGPU backend.
  49911. *
  49912. * @type {WebGPUBackend}
  49913. */
  49914. this.backend = backend;
  49915. /**
  49916. * A cache for managing bind group layouts.
  49917. *
  49918. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  49919. */
  49920. this.bindGroupLayoutCache = new WeakMap();
  49921. }
  49922. /**
  49923. * Creates a GPU bind group layout for the given bind group.
  49924. *
  49925. * @param {BindGroup} bindGroup - The bind group.
  49926. * @return {GPUBindGroupLayout} The GPU bind group layout.
  49927. */
  49928. createBindingsLayout( bindGroup ) {
  49929. const backend = this.backend;
  49930. const device = backend.device;
  49931. const entries = [];
  49932. let index = 0;
  49933. for ( const binding of bindGroup.bindings ) {
  49934. const bindingGPU = {
  49935. binding: index ++,
  49936. visibility: binding.visibility
  49937. };
  49938. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  49939. const buffer = {}; // GPUBufferBindingLayout
  49940. if ( binding.isStorageBuffer ) {
  49941. if ( binding.visibility & 4 ) {
  49942. // compute
  49943. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  49944. buffer.type = GPUBufferBindingType.Storage;
  49945. } else {
  49946. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  49947. }
  49948. } else {
  49949. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  49950. }
  49951. }
  49952. bindingGPU.buffer = buffer;
  49953. } else if ( binding.isSampledTexture && binding.store ) {
  49954. const storageTexture = {}; // GPUStorageTextureBindingLayout
  49955. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  49956. const access = binding.access;
  49957. if ( access === NodeAccess.READ_WRITE ) {
  49958. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  49959. } else if ( access === NodeAccess.WRITE_ONLY ) {
  49960. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  49961. } else {
  49962. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  49963. }
  49964. if ( binding.texture.isArrayTexture ) {
  49965. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  49966. } else if ( binding.texture.is3DTexture ) {
  49967. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  49968. }
  49969. bindingGPU.storageTexture = storageTexture;
  49970. } else if ( binding.isSampledTexture ) {
  49971. const texture = {}; // GPUTextureBindingLayout
  49972. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  49973. if ( primarySamples > 1 ) {
  49974. texture.multisampled = true;
  49975. if ( ! binding.texture.isDepthTexture ) {
  49976. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  49977. }
  49978. }
  49979. if ( binding.texture.isDepthTexture ) {
  49980. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  49981. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  49982. } else {
  49983. texture.sampleType = GPUTextureSampleType.Depth;
  49984. }
  49985. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  49986. const type = binding.texture.type;
  49987. if ( type === IntType ) {
  49988. texture.sampleType = GPUTextureSampleType.SInt;
  49989. } else if ( type === UnsignedIntType ) {
  49990. texture.sampleType = GPUTextureSampleType.UInt;
  49991. } else if ( type === FloatType ) {
  49992. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  49993. texture.sampleType = GPUTextureSampleType.Float;
  49994. } else {
  49995. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  49996. }
  49997. }
  49998. }
  49999. if ( binding.isSampledCubeTexture ) {
  50000. texture.viewDimension = GPUTextureViewDimension.Cube;
  50001. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  50002. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  50003. } else if ( binding.isSampledTexture3D ) {
  50004. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  50005. }
  50006. bindingGPU.texture = texture;
  50007. } else if ( binding.isSampler ) {
  50008. const sampler = {}; // GPUSamplerBindingLayout
  50009. if ( binding.texture.isDepthTexture ) {
  50010. if ( binding.texture.compareFunction !== null ) {
  50011. sampler.type = GPUSamplerBindingType.Comparison;
  50012. } else if ( backend.compatibilityMode ) {
  50013. sampler.type = GPUSamplerBindingType.NonFiltering;
  50014. }
  50015. }
  50016. bindingGPU.sampler = sampler;
  50017. } else {
  50018. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  50019. }
  50020. entries.push( bindingGPU );
  50021. }
  50022. return device.createBindGroupLayout( { entries } );
  50023. }
  50024. /**
  50025. * Creates bindings from the given bind group definition.
  50026. *
  50027. * @param {BindGroup} bindGroup - The bind group.
  50028. * @param {Array<BindGroup>} bindings - Array of bind groups.
  50029. * @param {number} cacheIndex - The cache index.
  50030. * @param {number} version - The version.
  50031. */
  50032. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  50033. const { backend, bindGroupLayoutCache } = this;
  50034. const bindingsData = backend.get( bindGroup );
  50035. // setup (static) binding layout and (dynamic) binding group
  50036. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  50037. if ( bindLayoutGPU === undefined ) {
  50038. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  50039. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  50040. }
  50041. let bindGroupGPU;
  50042. if ( cacheIndex > 0 ) {
  50043. if ( bindingsData.groups === undefined ) {
  50044. bindingsData.groups = [];
  50045. bindingsData.versions = [];
  50046. }
  50047. if ( bindingsData.versions[ cacheIndex ] === version ) {
  50048. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  50049. }
  50050. }
  50051. if ( bindGroupGPU === undefined ) {
  50052. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  50053. if ( cacheIndex > 0 ) {
  50054. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  50055. bindingsData.versions[ cacheIndex ] = version;
  50056. }
  50057. }
  50058. bindingsData.group = bindGroupGPU;
  50059. bindingsData.layout = bindLayoutGPU;
  50060. }
  50061. /**
  50062. * Updates a buffer binding.
  50063. *
  50064. * @param {Buffer} binding - The buffer binding to update.
  50065. */
  50066. updateBinding( binding ) {
  50067. const backend = this.backend;
  50068. const device = backend.device;
  50069. const buffer = binding.buffer;
  50070. const bufferGPU = backend.get( binding ).buffer;
  50071. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  50072. }
  50073. /**
  50074. * Creates a GPU bind group for the camera index.
  50075. *
  50076. * @param {Uint32Array} data - The index data.
  50077. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  50078. * @return {GPUBindGroup} The GPU bind group.
  50079. */
  50080. createBindGroupIndex( data, layout ) {
  50081. const backend = this.backend;
  50082. const device = backend.device;
  50083. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  50084. const index = data[ 0 ];
  50085. const buffer = device.createBuffer( {
  50086. label: 'bindingCameraIndex_' + index,
  50087. size: 16, // uint(4) * 4
  50088. usage: usage
  50089. } );
  50090. device.queue.writeBuffer( buffer, 0, data, 0 );
  50091. const entries = [ { binding: 0, resource: { buffer } } ];
  50092. return device.createBindGroup( {
  50093. label: 'bindGroupCameraIndex_' + index,
  50094. layout,
  50095. entries
  50096. } );
  50097. }
  50098. /**
  50099. * Creates a GPU bind group for the given bind group and GPU layout.
  50100. *
  50101. * @param {BindGroup} bindGroup - The bind group.
  50102. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  50103. * @return {GPUBindGroup} The GPU bind group.
  50104. */
  50105. createBindGroup( bindGroup, layoutGPU ) {
  50106. const backend = this.backend;
  50107. const device = backend.device;
  50108. let bindingPoint = 0;
  50109. const entriesGPU = [];
  50110. for ( const binding of bindGroup.bindings ) {
  50111. if ( binding.isUniformBuffer ) {
  50112. const bindingData = backend.get( binding );
  50113. if ( bindingData.buffer === undefined ) {
  50114. const byteLength = binding.byteLength;
  50115. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  50116. const bufferGPU = device.createBuffer( {
  50117. label: 'bindingBuffer_' + binding.name,
  50118. size: byteLength,
  50119. usage: usage
  50120. } );
  50121. bindingData.buffer = bufferGPU;
  50122. }
  50123. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  50124. } else if ( binding.isStorageBuffer ) {
  50125. const bindingData = backend.get( binding );
  50126. if ( bindingData.buffer === undefined ) {
  50127. const attribute = binding.attribute;
  50128. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  50129. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  50130. bindingData.buffer = backend.get( attribute ).buffer;
  50131. }
  50132. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  50133. } else if ( binding.isSampledTexture ) {
  50134. const textureData = backend.get( binding.texture );
  50135. let resourceGPU;
  50136. if ( textureData.externalTexture !== undefined ) {
  50137. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  50138. } else {
  50139. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  50140. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  50141. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  50142. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  50143. }
  50144. propertyName += `-${ mipLevelCount }`;
  50145. resourceGPU = textureData[ propertyName ];
  50146. if ( resourceGPU === undefined ) {
  50147. const aspectGPU = GPUTextureAspect.All;
  50148. let dimensionViewGPU;
  50149. if ( binding.isSampledCubeTexture ) {
  50150. dimensionViewGPU = GPUTextureViewDimension.Cube;
  50151. } else if ( binding.isSampledTexture3D ) {
  50152. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  50153. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  50154. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  50155. } else {
  50156. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  50157. }
  50158. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  50159. }
  50160. }
  50161. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  50162. } else if ( binding.isSampler ) {
  50163. const textureGPU = backend.get( binding.texture );
  50164. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  50165. }
  50166. bindingPoint ++;
  50167. }
  50168. return device.createBindGroup( {
  50169. label: 'bindGroup_' + bindGroup.name,
  50170. layout: layoutGPU,
  50171. entries: entriesGPU
  50172. } );
  50173. }
  50174. }
  50175. /**
  50176. * A WebGPU backend utility module for managing pipelines.
  50177. *
  50178. * @private
  50179. */
  50180. class WebGPUPipelineUtils {
  50181. /**
  50182. * Constructs a new utility object.
  50183. *
  50184. * @param {WebGPUBackend} backend - The WebGPU backend.
  50185. */
  50186. constructor( backend ) {
  50187. /**
  50188. * A reference to the WebGPU backend.
  50189. *
  50190. * @type {WebGPUBackend}
  50191. */
  50192. this.backend = backend;
  50193. /**
  50194. * A Weak Map that tracks the active pipeline for render or compute passes.
  50195. *
  50196. * @private
  50197. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  50198. */
  50199. this._activePipelines = new WeakMap();
  50200. }
  50201. /**
  50202. * Sets the given pipeline for the given pass. The method makes sure to only set the
  50203. * pipeline when necessary.
  50204. *
  50205. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  50206. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  50207. */
  50208. setPipeline( pass, pipeline ) {
  50209. const currentPipeline = this._activePipelines.get( pass );
  50210. if ( currentPipeline !== pipeline ) {
  50211. pass.setPipeline( pipeline );
  50212. this._activePipelines.set( pass, pipeline );
  50213. }
  50214. }
  50215. /**
  50216. * Returns the sample count derived from the given render context.
  50217. *
  50218. * @private
  50219. * @param {RenderContext} renderContext - The render context.
  50220. * @return {number} The sample count.
  50221. */
  50222. _getSampleCount( renderContext ) {
  50223. return this.backend.utils.getSampleCountRenderContext( renderContext );
  50224. }
  50225. /**
  50226. * Creates a render pipeline for the given render object.
  50227. *
  50228. * @param {RenderObject} renderObject - The render object.
  50229. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  50230. */
  50231. createRenderPipeline( renderObject, promises ) {
  50232. const { object, material, geometry, pipeline } = renderObject;
  50233. const { vertexProgram, fragmentProgram } = pipeline;
  50234. const backend = this.backend;
  50235. const device = backend.device;
  50236. const utils = backend.utils;
  50237. const pipelineData = backend.get( pipeline );
  50238. // bind group layouts
  50239. const bindGroupLayouts = [];
  50240. for ( const bindGroup of renderObject.getBindings() ) {
  50241. const bindingsData = backend.get( bindGroup );
  50242. bindGroupLayouts.push( bindingsData.layout );
  50243. }
  50244. // vertex buffers
  50245. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  50246. // blending
  50247. let blending;
  50248. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  50249. blending = this._getBlending( material );
  50250. }
  50251. // stencil
  50252. let stencilFront = {};
  50253. if ( material.stencilWrite === true ) {
  50254. stencilFront = {
  50255. compare: this._getStencilCompare( material ),
  50256. failOp: this._getStencilOperation( material.stencilFail ),
  50257. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  50258. passOp: this._getStencilOperation( material.stencilZPass )
  50259. };
  50260. }
  50261. const colorWriteMask = this._getColorWriteMask( material );
  50262. const targets = [];
  50263. if ( renderObject.context.textures !== null ) {
  50264. const textures = renderObject.context.textures;
  50265. for ( let i = 0; i < textures.length; i ++ ) {
  50266. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  50267. targets.push( {
  50268. format: colorFormat,
  50269. blend: blending,
  50270. writeMask: colorWriteMask
  50271. } );
  50272. }
  50273. } else {
  50274. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  50275. targets.push( {
  50276. format: colorFormat,
  50277. blend: blending,
  50278. writeMask: colorWriteMask
  50279. } );
  50280. }
  50281. const vertexModule = backend.get( vertexProgram ).module;
  50282. const fragmentModule = backend.get( fragmentProgram ).module;
  50283. const primitiveState = this._getPrimitiveState( object, geometry, material );
  50284. const depthCompare = this._getDepthCompare( material );
  50285. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  50286. const sampleCount = this._getSampleCount( renderObject.context );
  50287. const pipelineDescriptor = {
  50288. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  50289. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  50290. fragment: Object.assign( {}, fragmentModule, { targets } ),
  50291. primitive: primitiveState,
  50292. multisample: {
  50293. count: sampleCount,
  50294. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  50295. },
  50296. layout: device.createPipelineLayout( {
  50297. bindGroupLayouts
  50298. } )
  50299. };
  50300. const depthStencil = {};
  50301. const renderDepth = renderObject.context.depth;
  50302. const renderStencil = renderObject.context.stencil;
  50303. if ( renderDepth === true || renderStencil === true ) {
  50304. if ( renderDepth === true ) {
  50305. depthStencil.format = depthStencilFormat;
  50306. depthStencil.depthWriteEnabled = material.depthWrite;
  50307. depthStencil.depthCompare = depthCompare;
  50308. }
  50309. if ( renderStencil === true ) {
  50310. depthStencil.stencilFront = stencilFront;
  50311. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  50312. depthStencil.stencilReadMask = material.stencilFuncMask;
  50313. depthStencil.stencilWriteMask = material.stencilWriteMask;
  50314. }
  50315. if ( material.polygonOffset === true ) {
  50316. depthStencil.depthBias = material.polygonOffsetUnits;
  50317. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  50318. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  50319. }
  50320. pipelineDescriptor.depthStencil = depthStencil;
  50321. }
  50322. if ( promises === null ) {
  50323. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  50324. } else {
  50325. const p = new Promise( ( resolve /*, reject*/ ) => {
  50326. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  50327. pipelineData.pipeline = pipeline;
  50328. resolve();
  50329. } );
  50330. } );
  50331. promises.push( p );
  50332. }
  50333. }
  50334. /**
  50335. * Creates GPU render bundle encoder for the given render context.
  50336. *
  50337. * @param {RenderContext} renderContext - The render context.
  50338. * @param {?string} [label='renderBundleEncoder'] - The label.
  50339. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  50340. */
  50341. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  50342. const backend = this.backend;
  50343. const { utils, device } = backend;
  50344. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  50345. const colorFormat = utils.getCurrentColorFormat( renderContext );
  50346. const sampleCount = this._getSampleCount( renderContext );
  50347. const descriptor = {
  50348. label: label,
  50349. colorFormats: [ colorFormat ],
  50350. depthStencilFormat,
  50351. sampleCount
  50352. };
  50353. return device.createRenderBundleEncoder( descriptor );
  50354. }
  50355. /**
  50356. * Creates a compute pipeline for the given compute node.
  50357. *
  50358. * @param {ComputePipeline} pipeline - The compute pipeline.
  50359. * @param {Array<BindGroup>} bindings - The bindings.
  50360. */
  50361. createComputePipeline( pipeline, bindings ) {
  50362. const backend = this.backend;
  50363. const device = backend.device;
  50364. const computeProgram = backend.get( pipeline.computeProgram ).module;
  50365. const pipelineGPU = backend.get( pipeline );
  50366. // bind group layouts
  50367. const bindGroupLayouts = [];
  50368. for ( const bindingsGroup of bindings ) {
  50369. const bindingsData = backend.get( bindingsGroup );
  50370. bindGroupLayouts.push( bindingsData.layout );
  50371. }
  50372. pipelineGPU.pipeline = device.createComputePipeline( {
  50373. compute: computeProgram,
  50374. layout: device.createPipelineLayout( {
  50375. bindGroupLayouts
  50376. } )
  50377. } );
  50378. }
  50379. /**
  50380. * Returns the blending state as a descriptor object required
  50381. * for the pipeline creation.
  50382. *
  50383. * @private
  50384. * @param {Material} material - The material.
  50385. * @return {Object} The blending state.
  50386. */
  50387. _getBlending( material ) {
  50388. let color, alpha;
  50389. const blending = material.blending;
  50390. const blendSrc = material.blendSrc;
  50391. const blendDst = material.blendDst;
  50392. const blendEquation = material.blendEquation;
  50393. if ( blending === CustomBlending ) {
  50394. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  50395. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  50396. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  50397. color = {
  50398. srcFactor: this._getBlendFactor( blendSrc ),
  50399. dstFactor: this._getBlendFactor( blendDst ),
  50400. operation: this._getBlendOperation( blendEquation )
  50401. };
  50402. alpha = {
  50403. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  50404. dstFactor: this._getBlendFactor( blendDstAlpha ),
  50405. operation: this._getBlendOperation( blendEquationAlpha )
  50406. };
  50407. } else {
  50408. const premultipliedAlpha = material.premultipliedAlpha;
  50409. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  50410. color = {
  50411. srcFactor: srcRGB,
  50412. dstFactor: dstRGB,
  50413. operation: GPUBlendOperation.Add
  50414. };
  50415. alpha = {
  50416. srcFactor: srcAlpha,
  50417. dstFactor: dstAlpha,
  50418. operation: GPUBlendOperation.Add
  50419. };
  50420. };
  50421. if ( premultipliedAlpha ) {
  50422. switch ( blending ) {
  50423. case NormalBlending:
  50424. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  50425. break;
  50426. case AdditiveBlending:
  50427. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  50428. break;
  50429. case SubtractiveBlending:
  50430. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  50431. break;
  50432. case MultiplyBlending:
  50433. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  50434. break;
  50435. }
  50436. } else {
  50437. switch ( blending ) {
  50438. case NormalBlending:
  50439. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  50440. break;
  50441. case AdditiveBlending:
  50442. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  50443. break;
  50444. case SubtractiveBlending:
  50445. console.error( 'THREE.WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  50446. break;
  50447. case MultiplyBlending:
  50448. console.error( 'THREE.WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  50449. break;
  50450. }
  50451. }
  50452. }
  50453. if ( color !== undefined && alpha !== undefined ) {
  50454. return { color, alpha };
  50455. } else {
  50456. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  50457. }
  50458. }
  50459. /**
  50460. * Returns the GPU blend factor which is required for the pipeline creation.
  50461. *
  50462. * @private
  50463. * @param {number} blend - The blend factor as a three.js constant.
  50464. * @return {string} The GPU blend factor.
  50465. */
  50466. _getBlendFactor( blend ) {
  50467. let blendFactor;
  50468. switch ( blend ) {
  50469. case ZeroFactor:
  50470. blendFactor = GPUBlendFactor.Zero;
  50471. break;
  50472. case OneFactor:
  50473. blendFactor = GPUBlendFactor.One;
  50474. break;
  50475. case SrcColorFactor:
  50476. blendFactor = GPUBlendFactor.Src;
  50477. break;
  50478. case OneMinusSrcColorFactor:
  50479. blendFactor = GPUBlendFactor.OneMinusSrc;
  50480. break;
  50481. case SrcAlphaFactor:
  50482. blendFactor = GPUBlendFactor.SrcAlpha;
  50483. break;
  50484. case OneMinusSrcAlphaFactor:
  50485. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  50486. break;
  50487. case DstColorFactor:
  50488. blendFactor = GPUBlendFactor.Dst;
  50489. break;
  50490. case OneMinusDstColorFactor:
  50491. blendFactor = GPUBlendFactor.OneMinusDst;
  50492. break;
  50493. case DstAlphaFactor:
  50494. blendFactor = GPUBlendFactor.DstAlpha;
  50495. break;
  50496. case OneMinusDstAlphaFactor:
  50497. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  50498. break;
  50499. case SrcAlphaSaturateFactor:
  50500. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  50501. break;
  50502. case BlendColorFactor:
  50503. blendFactor = GPUBlendFactor.Constant;
  50504. break;
  50505. case OneMinusBlendColorFactor:
  50506. blendFactor = GPUBlendFactor.OneMinusConstant;
  50507. break;
  50508. default:
  50509. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  50510. }
  50511. return blendFactor;
  50512. }
  50513. /**
  50514. * Returns the GPU stencil compare function which is required for the pipeline creation.
  50515. *
  50516. * @private
  50517. * @param {Material} material - The material.
  50518. * @return {string} The GPU stencil compare function.
  50519. */
  50520. _getStencilCompare( material ) {
  50521. let stencilCompare;
  50522. const stencilFunc = material.stencilFunc;
  50523. switch ( stencilFunc ) {
  50524. case NeverStencilFunc:
  50525. stencilCompare = GPUCompareFunction.Never;
  50526. break;
  50527. case AlwaysStencilFunc:
  50528. stencilCompare = GPUCompareFunction.Always;
  50529. break;
  50530. case LessStencilFunc:
  50531. stencilCompare = GPUCompareFunction.Less;
  50532. break;
  50533. case LessEqualStencilFunc:
  50534. stencilCompare = GPUCompareFunction.LessEqual;
  50535. break;
  50536. case EqualStencilFunc:
  50537. stencilCompare = GPUCompareFunction.Equal;
  50538. break;
  50539. case GreaterEqualStencilFunc:
  50540. stencilCompare = GPUCompareFunction.GreaterEqual;
  50541. break;
  50542. case GreaterStencilFunc:
  50543. stencilCompare = GPUCompareFunction.Greater;
  50544. break;
  50545. case NotEqualStencilFunc:
  50546. stencilCompare = GPUCompareFunction.NotEqual;
  50547. break;
  50548. default:
  50549. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  50550. }
  50551. return stencilCompare;
  50552. }
  50553. /**
  50554. * Returns the GPU stencil operation which is required for the pipeline creation.
  50555. *
  50556. * @private
  50557. * @param {number} op - A three.js constant defining the stencil operation.
  50558. * @return {string} The GPU stencil operation.
  50559. */
  50560. _getStencilOperation( op ) {
  50561. let stencilOperation;
  50562. switch ( op ) {
  50563. case KeepStencilOp:
  50564. stencilOperation = GPUStencilOperation.Keep;
  50565. break;
  50566. case ZeroStencilOp:
  50567. stencilOperation = GPUStencilOperation.Zero;
  50568. break;
  50569. case ReplaceStencilOp:
  50570. stencilOperation = GPUStencilOperation.Replace;
  50571. break;
  50572. case InvertStencilOp:
  50573. stencilOperation = GPUStencilOperation.Invert;
  50574. break;
  50575. case IncrementStencilOp:
  50576. stencilOperation = GPUStencilOperation.IncrementClamp;
  50577. break;
  50578. case DecrementStencilOp:
  50579. stencilOperation = GPUStencilOperation.DecrementClamp;
  50580. break;
  50581. case IncrementWrapStencilOp:
  50582. stencilOperation = GPUStencilOperation.IncrementWrap;
  50583. break;
  50584. case DecrementWrapStencilOp:
  50585. stencilOperation = GPUStencilOperation.DecrementWrap;
  50586. break;
  50587. default:
  50588. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  50589. }
  50590. return stencilOperation;
  50591. }
  50592. /**
  50593. * Returns the GPU blend operation which is required for the pipeline creation.
  50594. *
  50595. * @private
  50596. * @param {number} blendEquation - A three.js constant defining the blend equation.
  50597. * @return {string} The GPU blend operation.
  50598. */
  50599. _getBlendOperation( blendEquation ) {
  50600. let blendOperation;
  50601. switch ( blendEquation ) {
  50602. case AddEquation:
  50603. blendOperation = GPUBlendOperation.Add;
  50604. break;
  50605. case SubtractEquation:
  50606. blendOperation = GPUBlendOperation.Subtract;
  50607. break;
  50608. case ReverseSubtractEquation:
  50609. blendOperation = GPUBlendOperation.ReverseSubtract;
  50610. break;
  50611. case MinEquation:
  50612. blendOperation = GPUBlendOperation.Min;
  50613. break;
  50614. case MaxEquation:
  50615. blendOperation = GPUBlendOperation.Max;
  50616. break;
  50617. default:
  50618. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  50619. }
  50620. return blendOperation;
  50621. }
  50622. /**
  50623. * Returns the primitive state as a descriptor object required
  50624. * for the pipeline creation.
  50625. *
  50626. * @private
  50627. * @param {Object3D} object - The 3D object.
  50628. * @param {BufferGeometry} geometry - The geometry.
  50629. * @param {Material} material - The material.
  50630. * @return {Object} The primitive state.
  50631. */
  50632. _getPrimitiveState( object, geometry, material ) {
  50633. const descriptor = {};
  50634. const utils = this.backend.utils;
  50635. descriptor.topology = utils.getPrimitiveTopology( object, material );
  50636. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  50637. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  50638. }
  50639. switch ( material.side ) {
  50640. case FrontSide:
  50641. descriptor.frontFace = GPUFrontFace.CCW;
  50642. descriptor.cullMode = GPUCullMode.Back;
  50643. break;
  50644. case BackSide:
  50645. descriptor.frontFace = GPUFrontFace.CCW;
  50646. descriptor.cullMode = GPUCullMode.Front;
  50647. break;
  50648. case DoubleSide:
  50649. descriptor.frontFace = GPUFrontFace.CCW;
  50650. descriptor.cullMode = GPUCullMode.None;
  50651. break;
  50652. default:
  50653. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  50654. break;
  50655. }
  50656. return descriptor;
  50657. }
  50658. /**
  50659. * Returns the GPU color write mask which is required for the pipeline creation.
  50660. *
  50661. * @private
  50662. * @param {Material} material - The material.
  50663. * @return {number} The GPU color write mask.
  50664. */
  50665. _getColorWriteMask( material ) {
  50666. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  50667. }
  50668. /**
  50669. * Returns the GPU depth compare function which is required for the pipeline creation.
  50670. *
  50671. * @private
  50672. * @param {Material} material - The material.
  50673. * @return {string} The GPU depth compare function.
  50674. */
  50675. _getDepthCompare( material ) {
  50676. let depthCompare;
  50677. if ( material.depthTest === false ) {
  50678. depthCompare = GPUCompareFunction.Always;
  50679. } else {
  50680. const depthFunc = material.depthFunc;
  50681. switch ( depthFunc ) {
  50682. case NeverDepth:
  50683. depthCompare = GPUCompareFunction.Never;
  50684. break;
  50685. case AlwaysDepth:
  50686. depthCompare = GPUCompareFunction.Always;
  50687. break;
  50688. case LessDepth:
  50689. depthCompare = GPUCompareFunction.Less;
  50690. break;
  50691. case LessEqualDepth:
  50692. depthCompare = GPUCompareFunction.LessEqual;
  50693. break;
  50694. case EqualDepth:
  50695. depthCompare = GPUCompareFunction.Equal;
  50696. break;
  50697. case GreaterEqualDepth:
  50698. depthCompare = GPUCompareFunction.GreaterEqual;
  50699. break;
  50700. case GreaterDepth:
  50701. depthCompare = GPUCompareFunction.Greater;
  50702. break;
  50703. case NotEqualDepth:
  50704. depthCompare = GPUCompareFunction.NotEqual;
  50705. break;
  50706. default:
  50707. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  50708. }
  50709. }
  50710. return depthCompare;
  50711. }
  50712. }
  50713. /**
  50714. * Manages a pool of WebGPU timestamp queries for performance measurement.
  50715. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  50716. *
  50717. * @augments TimestampQueryPool
  50718. */
  50719. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  50720. /**
  50721. * Creates a new WebGPU timestamp query pool.
  50722. *
  50723. * @param {GPUDevice} device - The WebGPU device to create queries on.
  50724. * @param {string} type - The type identifier for this query pool.
  50725. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  50726. */
  50727. constructor( device, type, maxQueries = 2048 ) {
  50728. super( maxQueries );
  50729. this.device = device;
  50730. this.type = type;
  50731. this.querySet = this.device.createQuerySet( {
  50732. type: 'timestamp',
  50733. count: this.maxQueries,
  50734. label: `queryset_global_timestamp_${type}`
  50735. } );
  50736. const bufferSize = this.maxQueries * 8;
  50737. this.resolveBuffer = this.device.createBuffer( {
  50738. label: `buffer_timestamp_resolve_${type}`,
  50739. size: bufferSize,
  50740. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  50741. } );
  50742. this.resultBuffer = this.device.createBuffer( {
  50743. label: `buffer_timestamp_result_${type}`,
  50744. size: bufferSize,
  50745. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  50746. } );
  50747. }
  50748. /**
  50749. * Allocates a pair of queries for a given render context.
  50750. *
  50751. * @param {Object} renderContext - The render context to allocate queries for.
  50752. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  50753. */
  50754. allocateQueriesForContext( renderContext ) {
  50755. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  50756. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  50757. 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() } ).` );
  50758. return null;
  50759. }
  50760. const baseOffset = this.currentQueryIndex;
  50761. this.currentQueryIndex += 2;
  50762. this.queryOffsets.set( renderContext.id, baseOffset );
  50763. return baseOffset;
  50764. }
  50765. /**
  50766. * Asynchronously resolves all pending queries and returns the total duration.
  50767. * If there's already a pending resolve operation, returns that promise instead.
  50768. *
  50769. * @async
  50770. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  50771. */
  50772. async resolveQueriesAsync() {
  50773. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  50774. return this.lastValue;
  50775. }
  50776. if ( this.pendingResolve ) {
  50777. return this.pendingResolve;
  50778. }
  50779. this.pendingResolve = this._resolveQueries();
  50780. try {
  50781. const result = await this.pendingResolve;
  50782. return result;
  50783. } finally {
  50784. this.pendingResolve = null;
  50785. }
  50786. }
  50787. /**
  50788. * Internal method to resolve queries and calculate total duration.
  50789. *
  50790. * @async
  50791. * @private
  50792. * @returns {Promise<number>} The total duration in milliseconds.
  50793. */
  50794. async _resolveQueries() {
  50795. if ( this.isDisposed ) {
  50796. return this.lastValue;
  50797. }
  50798. try {
  50799. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  50800. return this.lastValue;
  50801. }
  50802. const currentOffsets = new Map( this.queryOffsets );
  50803. const queryCount = this.currentQueryIndex;
  50804. const bytesUsed = queryCount * 8;
  50805. // Reset state before GPU work
  50806. this.currentQueryIndex = 0;
  50807. this.queryOffsets.clear();
  50808. const commandEncoder = this.device.createCommandEncoder();
  50809. commandEncoder.resolveQuerySet(
  50810. this.querySet,
  50811. 0,
  50812. queryCount,
  50813. this.resolveBuffer,
  50814. 0
  50815. );
  50816. commandEncoder.copyBufferToBuffer(
  50817. this.resolveBuffer,
  50818. 0,
  50819. this.resultBuffer,
  50820. 0,
  50821. bytesUsed
  50822. );
  50823. const commandBuffer = commandEncoder.finish();
  50824. this.device.queue.submit( [ commandBuffer ] );
  50825. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  50826. return this.lastValue;
  50827. }
  50828. // Create and track the mapping operation
  50829. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  50830. if ( this.isDisposed ) {
  50831. if ( this.resultBuffer.mapState === 'mapped' ) {
  50832. this.resultBuffer.unmap();
  50833. }
  50834. return this.lastValue;
  50835. }
  50836. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  50837. let totalDuration = 0;
  50838. for ( const [ , baseOffset ] of currentOffsets ) {
  50839. const startTime = times[ baseOffset ];
  50840. const endTime = times[ baseOffset + 1 ];
  50841. const duration = Number( endTime - startTime ) / 1e6;
  50842. totalDuration += duration;
  50843. }
  50844. this.resultBuffer.unmap();
  50845. this.lastValue = totalDuration;
  50846. return totalDuration;
  50847. } catch ( error ) {
  50848. console.error( 'Error resolving queries:', error );
  50849. if ( this.resultBuffer.mapState === 'mapped' ) {
  50850. this.resultBuffer.unmap();
  50851. }
  50852. return this.lastValue;
  50853. }
  50854. }
  50855. /**
  50856. * Dispose of the query pool.
  50857. *
  50858. * @async
  50859. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  50860. */
  50861. async dispose() {
  50862. if ( this.isDisposed ) {
  50863. return;
  50864. }
  50865. this.isDisposed = true;
  50866. // Wait for pending resolve operation
  50867. if ( this.pendingResolve ) {
  50868. try {
  50869. await this.pendingResolve;
  50870. } catch ( error ) {
  50871. console.error( 'Error waiting for pending resolve:', error );
  50872. }
  50873. }
  50874. // Ensure buffer is unmapped before destroying
  50875. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  50876. try {
  50877. this.resultBuffer.unmap();
  50878. } catch ( error ) {
  50879. console.error( 'Error unmapping buffer:', error );
  50880. }
  50881. }
  50882. // Destroy resources
  50883. if ( this.querySet ) {
  50884. this.querySet.destroy();
  50885. this.querySet = null;
  50886. }
  50887. if ( this.resolveBuffer ) {
  50888. this.resolveBuffer.destroy();
  50889. this.resolveBuffer = null;
  50890. }
  50891. if ( this.resultBuffer ) {
  50892. this.resultBuffer.destroy();
  50893. this.resultBuffer = null;
  50894. }
  50895. this.queryOffsets.clear();
  50896. this.pendingResolve = null;
  50897. }
  50898. }
  50899. /*// debugger tools
  50900. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  50901. //*/
  50902. /**
  50903. * A backend implementation targeting WebGPU.
  50904. *
  50905. * @private
  50906. * @augments Backend
  50907. */
  50908. class WebGPUBackend extends Backend {
  50909. /**
  50910. * WebGPUBackend options.
  50911. *
  50912. * @typedef {Object} WebGPUBackend~Options
  50913. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  50914. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  50915. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  50916. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  50917. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  50918. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  50919. * @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.
  50920. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  50921. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  50922. * @property {string} [powerPreference=undefined] - The power preference.
  50923. * @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.
  50924. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  50925. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  50926. */
  50927. /**
  50928. * Constructs a new WebGPU backend.
  50929. *
  50930. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  50931. */
  50932. constructor( parameters = {} ) {
  50933. super( parameters );
  50934. /**
  50935. * This flag can be used for type testing.
  50936. *
  50937. * @type {boolean}
  50938. * @readonly
  50939. * @default true
  50940. */
  50941. this.isWebGPUBackend = true;
  50942. // some parameters require default values other than "undefined"
  50943. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  50944. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  50945. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  50946. /**
  50947. * Indicates whether the backend is in compatibility mode or not.
  50948. * @type {boolean}
  50949. * @default false
  50950. */
  50951. this.compatibilityMode = this.parameters.compatibilityMode;
  50952. /**
  50953. * A reference to the device.
  50954. *
  50955. * @type {?GPUDevice}
  50956. * @default null
  50957. */
  50958. this.device = null;
  50959. /**
  50960. * A reference to the context.
  50961. *
  50962. * @type {?GPUCanvasContext}
  50963. * @default null
  50964. */
  50965. this.context = null;
  50966. /**
  50967. * A reference to the color attachment of the default framebuffer.
  50968. *
  50969. * @type {?GPUTexture}
  50970. * @default null
  50971. */
  50972. this.colorBuffer = null;
  50973. /**
  50974. * A reference to the default render pass descriptor.
  50975. *
  50976. * @type {?Object}
  50977. * @default null
  50978. */
  50979. this.defaultRenderPassdescriptor = null;
  50980. /**
  50981. * A reference to a backend module holding common utility functions.
  50982. *
  50983. * @type {WebGPUUtils}
  50984. */
  50985. this.utils = new WebGPUUtils( this );
  50986. /**
  50987. * A reference to a backend module holding shader attribute-related
  50988. * utility functions.
  50989. *
  50990. * @type {WebGPUAttributeUtils}
  50991. */
  50992. this.attributeUtils = new WebGPUAttributeUtils( this );
  50993. /**
  50994. * A reference to a backend module holding shader binding-related
  50995. * utility functions.
  50996. *
  50997. * @type {WebGPUBindingUtils}
  50998. */
  50999. this.bindingUtils = new WebGPUBindingUtils( this );
  51000. /**
  51001. * A reference to a backend module holding shader pipeline-related
  51002. * utility functions.
  51003. *
  51004. * @type {WebGPUPipelineUtils}
  51005. */
  51006. this.pipelineUtils = new WebGPUPipelineUtils( this );
  51007. /**
  51008. * A reference to a backend module holding shader texture-related
  51009. * utility functions.
  51010. *
  51011. * @type {WebGPUTextureUtils}
  51012. */
  51013. this.textureUtils = new WebGPUTextureUtils( this );
  51014. /**
  51015. * A map that manages the resolve buffers for occlusion queries.
  51016. *
  51017. * @type {Map<number,GPUBuffer>}
  51018. */
  51019. this.occludedResolveCache = new Map();
  51020. }
  51021. /**
  51022. * Initializes the backend so it is ready for usage.
  51023. *
  51024. * @async
  51025. * @param {Renderer} renderer - The renderer.
  51026. * @return {Promise} A Promise that resolves when the backend has been initialized.
  51027. */
  51028. async init( renderer ) {
  51029. await super.init( renderer );
  51030. //
  51031. const parameters = this.parameters;
  51032. // create the device if it is not passed with parameters
  51033. let device;
  51034. if ( parameters.device === undefined ) {
  51035. const adapterOptions = {
  51036. powerPreference: parameters.powerPreference,
  51037. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  51038. };
  51039. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  51040. if ( adapter === null ) {
  51041. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  51042. }
  51043. // feature support
  51044. const features = Object.values( GPUFeatureName );
  51045. const supportedFeatures = [];
  51046. for ( const name of features ) {
  51047. if ( adapter.features.has( name ) ) {
  51048. supportedFeatures.push( name );
  51049. }
  51050. }
  51051. const deviceDescriptor = {
  51052. requiredFeatures: supportedFeatures,
  51053. requiredLimits: parameters.requiredLimits
  51054. };
  51055. device = await adapter.requestDevice( deviceDescriptor );
  51056. } else {
  51057. device = parameters.device;
  51058. }
  51059. device.lost.then( ( info ) => {
  51060. const deviceLossInfo = {
  51061. api: 'WebGPU',
  51062. message: info.message || 'Unknown reason',
  51063. reason: info.reason || null,
  51064. originalEvent: info
  51065. };
  51066. renderer.onDeviceLost( deviceLossInfo );
  51067. } );
  51068. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  51069. this.device = device;
  51070. this.context = context;
  51071. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  51072. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  51073. this.context.configure( {
  51074. device: this.device,
  51075. format: this.utils.getPreferredCanvasFormat(),
  51076. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  51077. alphaMode: alphaMode
  51078. } );
  51079. this.updateSize();
  51080. }
  51081. /**
  51082. * The coordinate system of the backend.
  51083. *
  51084. * @type {number}
  51085. * @readonly
  51086. */
  51087. get coordinateSystem() {
  51088. return WebGPUCoordinateSystem;
  51089. }
  51090. /**
  51091. * This method performs a readback operation by moving buffer data from
  51092. * a storage buffer attribute from the GPU to the CPU.
  51093. *
  51094. * @async
  51095. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  51096. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  51097. */
  51098. async getArrayBufferAsync( attribute ) {
  51099. return await this.attributeUtils.getArrayBufferAsync( attribute );
  51100. }
  51101. /**
  51102. * Returns the backend's rendering context.
  51103. *
  51104. * @return {GPUCanvasContext} The rendering context.
  51105. */
  51106. getContext() {
  51107. return this.context;
  51108. }
  51109. /**
  51110. * Returns the default render pass descriptor.
  51111. *
  51112. * In WebGPU, the default framebuffer must be configured
  51113. * like custom framebuffers so the backend needs a render
  51114. * pass descriptor even when rendering directly to screen.
  51115. *
  51116. * @private
  51117. * @return {Object} The render pass descriptor.
  51118. */
  51119. _getDefaultRenderPassDescriptor() {
  51120. let descriptor = this.defaultRenderPassdescriptor;
  51121. if ( descriptor === null ) {
  51122. const renderer = this.renderer;
  51123. descriptor = {
  51124. colorAttachments: [ {
  51125. view: null
  51126. } ],
  51127. };
  51128. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  51129. descriptor.depthStencilAttachment = {
  51130. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  51131. };
  51132. }
  51133. const colorAttachment = descriptor.colorAttachments[ 0 ];
  51134. if ( this.renderer.samples > 0 ) {
  51135. colorAttachment.view = this.colorBuffer.createView();
  51136. } else {
  51137. colorAttachment.resolveTarget = undefined;
  51138. }
  51139. this.defaultRenderPassdescriptor = descriptor;
  51140. }
  51141. const colorAttachment = descriptor.colorAttachments[ 0 ];
  51142. if ( this.renderer.samples > 0 ) {
  51143. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  51144. } else {
  51145. colorAttachment.view = this.context.getCurrentTexture().createView();
  51146. }
  51147. return descriptor;
  51148. }
  51149. /**
  51150. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  51151. *
  51152. * @param {RenderContext} renderContext - The render context.
  51153. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  51154. *
  51155. * @private
  51156. */
  51157. _isRenderCameraDepthArray( renderContext ) {
  51158. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  51159. }
  51160. /**
  51161. * Returns the render pass descriptor for the given render context.
  51162. *
  51163. * @private
  51164. * @param {RenderContext} renderContext - The render context.
  51165. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  51166. * @return {Object} The render pass descriptor.
  51167. */
  51168. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  51169. const renderTarget = renderContext.renderTarget;
  51170. const renderTargetData = this.get( renderTarget );
  51171. let descriptors = renderTargetData.descriptors;
  51172. if ( descriptors === undefined ||
  51173. renderTargetData.width !== renderTarget.width ||
  51174. renderTargetData.height !== renderTarget.height ||
  51175. renderTargetData.dimensions !== renderTarget.dimensions ||
  51176. renderTargetData.activeMipmapLevel !== renderContext.activeMipmapLevel ||
  51177. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  51178. renderTargetData.samples !== renderTarget.samples
  51179. ) {
  51180. descriptors = {};
  51181. renderTargetData.descriptors = descriptors;
  51182. // dispose
  51183. const onDispose = () => {
  51184. renderTarget.removeEventListener( 'dispose', onDispose );
  51185. this.delete( renderTarget );
  51186. };
  51187. if ( renderTarget.hasEventListener( 'dispose', onDispose ) === false ) {
  51188. renderTarget.addEventListener( 'dispose', onDispose );
  51189. }
  51190. }
  51191. const cacheKey = renderContext.getCacheKey();
  51192. let descriptorBase = descriptors[ cacheKey ];
  51193. if ( descriptorBase === undefined ) {
  51194. const textures = renderContext.textures;
  51195. const textureViews = [];
  51196. let sliceIndex;
  51197. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  51198. for ( let i = 0; i < textures.length; i ++ ) {
  51199. const textureData = this.get( textures[ i ] );
  51200. const viewDescriptor = {
  51201. label: `colorAttachment_${ i }`,
  51202. baseMipLevel: renderContext.activeMipmapLevel,
  51203. mipLevelCount: 1,
  51204. baseArrayLayer: renderContext.activeCubeFace,
  51205. arrayLayerCount: 1,
  51206. dimension: GPUTextureViewDimension.TwoD
  51207. };
  51208. if ( renderTarget.isRenderTarget3D ) {
  51209. sliceIndex = renderContext.activeCubeFace;
  51210. viewDescriptor.baseArrayLayer = 0;
  51211. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  51212. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  51213. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  51214. if ( isRenderCameraDepthArray === true ) {
  51215. const cameras = renderContext.camera.cameras;
  51216. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  51217. const layerViewDescriptor = {
  51218. ...viewDescriptor,
  51219. baseArrayLayer: layer,
  51220. arrayLayerCount: 1,
  51221. dimension: GPUTextureViewDimension.TwoD
  51222. };
  51223. const textureView = textureData.texture.createView( layerViewDescriptor );
  51224. textureViews.push( {
  51225. view: textureView,
  51226. resolveTarget: undefined,
  51227. depthSlice: undefined
  51228. } );
  51229. }
  51230. } else {
  51231. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  51232. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  51233. }
  51234. }
  51235. if ( isRenderCameraDepthArray !== true ) {
  51236. const textureView = textureData.texture.createView( viewDescriptor );
  51237. let view, resolveTarget;
  51238. if ( textureData.msaaTexture !== undefined ) {
  51239. view = textureData.msaaTexture.createView();
  51240. resolveTarget = textureView;
  51241. } else {
  51242. view = textureView;
  51243. resolveTarget = undefined;
  51244. }
  51245. textureViews.push( {
  51246. view,
  51247. resolveTarget,
  51248. depthSlice: sliceIndex
  51249. } );
  51250. }
  51251. }
  51252. descriptorBase = { textureViews };
  51253. if ( renderContext.depth ) {
  51254. const depthTextureData = this.get( renderContext.depthTexture );
  51255. const options = {};
  51256. if ( renderContext.depthTexture.isArrayTexture ) {
  51257. options.dimension = GPUTextureViewDimension.TwoD;
  51258. options.arrayLayerCount = 1;
  51259. options.baseArrayLayer = renderContext.activeCubeFace;
  51260. }
  51261. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  51262. }
  51263. descriptors[ cacheKey ] = descriptorBase;
  51264. renderTargetData.width = renderTarget.width;
  51265. renderTargetData.height = renderTarget.height;
  51266. renderTargetData.samples = renderTarget.samples;
  51267. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  51268. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  51269. renderTargetData.dimensions = renderTarget.dimensions;
  51270. }
  51271. const descriptor = {
  51272. colorAttachments: []
  51273. };
  51274. // Apply dynamic properties to cached views
  51275. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  51276. const viewInfo = descriptorBase.textureViews[ i ];
  51277. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  51278. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  51279. clearValue = colorAttachmentsConfig.clearValue;
  51280. }
  51281. descriptor.colorAttachments.push( {
  51282. view: viewInfo.view,
  51283. depthSlice: viewInfo.depthSlice,
  51284. resolveTarget: viewInfo.resolveTarget,
  51285. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  51286. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  51287. clearValue: clearValue
  51288. } );
  51289. }
  51290. if ( descriptorBase.depthStencilView ) {
  51291. descriptor.depthStencilAttachment = {
  51292. view: descriptorBase.depthStencilView
  51293. };
  51294. }
  51295. return descriptor;
  51296. }
  51297. /**
  51298. * This method is executed at the beginning of a render call and prepares
  51299. * the WebGPU state for upcoming render calls
  51300. *
  51301. * @param {RenderContext} renderContext - The render context.
  51302. */
  51303. beginRender( renderContext ) {
  51304. const renderContextData = this.get( renderContext );
  51305. const device = this.device;
  51306. const occlusionQueryCount = renderContext.occlusionQueryCount;
  51307. let occlusionQuerySet;
  51308. if ( occlusionQueryCount > 0 ) {
  51309. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  51310. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  51311. // Get a reference to the array of objects with queries. The renderContextData property
  51312. // can be changed by another render pass before the buffer.mapAsyc() completes.
  51313. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  51314. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  51315. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  51316. //
  51317. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  51318. renderContextData.occlusionQuerySet = occlusionQuerySet;
  51319. renderContextData.occlusionQueryIndex = 0;
  51320. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  51321. renderContextData.lastOcclusionObject = null;
  51322. }
  51323. let descriptor;
  51324. if ( renderContext.textures === null ) {
  51325. descriptor = this._getDefaultRenderPassDescriptor();
  51326. } else {
  51327. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  51328. }
  51329. this.initTimestampQuery( renderContext, descriptor );
  51330. descriptor.occlusionQuerySet = occlusionQuerySet;
  51331. const depthStencilAttachment = descriptor.depthStencilAttachment;
  51332. if ( renderContext.textures !== null ) {
  51333. const colorAttachments = descriptor.colorAttachments;
  51334. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  51335. const colorAttachment = colorAttachments[ i ];
  51336. if ( renderContext.clearColor ) {
  51337. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  51338. colorAttachment.loadOp = GPULoadOp.Clear;
  51339. } else {
  51340. colorAttachment.loadOp = GPULoadOp.Load;
  51341. }
  51342. colorAttachment.storeOp = GPUStoreOp.Store;
  51343. }
  51344. } else {
  51345. const colorAttachment = descriptor.colorAttachments[ 0 ];
  51346. if ( renderContext.clearColor ) {
  51347. colorAttachment.clearValue = renderContext.clearColorValue;
  51348. colorAttachment.loadOp = GPULoadOp.Clear;
  51349. } else {
  51350. colorAttachment.loadOp = GPULoadOp.Load;
  51351. }
  51352. colorAttachment.storeOp = GPUStoreOp.Store;
  51353. }
  51354. //
  51355. if ( renderContext.depth ) {
  51356. if ( renderContext.clearDepth ) {
  51357. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  51358. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  51359. } else {
  51360. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  51361. }
  51362. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  51363. }
  51364. if ( renderContext.stencil ) {
  51365. if ( renderContext.clearStencil ) {
  51366. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  51367. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  51368. } else {
  51369. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  51370. }
  51371. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  51372. }
  51373. //
  51374. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  51375. // shadow arrays - prepare bundle encoders for each camera in an array camera
  51376. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  51377. const cameras = renderContext.camera.cameras;
  51378. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  51379. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  51380. } else {
  51381. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  51382. }
  51383. // Create bundle encoders for each layer
  51384. renderContextData.bundleEncoders = [];
  51385. renderContextData.bundleSets = [];
  51386. // Create separate bundle encoders for each camera in the array
  51387. for ( let i = 0; i < cameras.length; i ++ ) {
  51388. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  51389. renderContext,
  51390. 'renderBundleArrayCamera_' + i
  51391. );
  51392. // Initialize state tracking for this bundle
  51393. const bundleSets = {
  51394. attributes: {},
  51395. bindingGroups: [],
  51396. pipeline: null,
  51397. index: null
  51398. };
  51399. renderContextData.bundleEncoders.push( bundleEncoder );
  51400. renderContextData.bundleSets.push( bundleSets );
  51401. }
  51402. // We'll complete the bundles in finishRender
  51403. renderContextData.currentPass = null;
  51404. } else {
  51405. const currentPass = encoder.beginRenderPass( descriptor );
  51406. renderContextData.currentPass = currentPass;
  51407. if ( renderContext.viewport ) {
  51408. this.updateViewport( renderContext );
  51409. }
  51410. if ( renderContext.scissor ) {
  51411. const { x, y, width, height } = renderContext.scissorValue;
  51412. currentPass.setScissorRect( x, y, width, height );
  51413. }
  51414. }
  51415. //
  51416. renderContextData.descriptor = descriptor;
  51417. renderContextData.encoder = encoder;
  51418. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  51419. renderContextData.renderBundles = [];
  51420. }
  51421. /**
  51422. * This method creates layer descriptors for each camera in an array camera
  51423. * to prepare for rendering to a depth array texture.
  51424. *
  51425. * @param {RenderContext} renderContext - The render context.
  51426. * @param {Object} renderContextData - The render context data.
  51427. * @param {Object} descriptor - The render pass descriptor.
  51428. * @param {ArrayCamera} cameras - The array camera.
  51429. *
  51430. * @private
  51431. */
  51432. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  51433. const depthStencilAttachment = descriptor.depthStencilAttachment;
  51434. renderContextData.layerDescriptors = [];
  51435. const depthTextureData = this.get( renderContext.depthTexture );
  51436. if ( ! depthTextureData.viewCache ) {
  51437. depthTextureData.viewCache = [];
  51438. }
  51439. for ( let i = 0; i < cameras.length; i ++ ) {
  51440. const layerDescriptor = {
  51441. ...descriptor,
  51442. colorAttachments: [ {
  51443. ...descriptor.colorAttachments[ 0 ],
  51444. view: descriptor.colorAttachments[ i ].view
  51445. } ]
  51446. };
  51447. if ( descriptor.depthStencilAttachment ) {
  51448. const layerIndex = i;
  51449. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  51450. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  51451. dimension: GPUTextureViewDimension.TwoD,
  51452. baseArrayLayer: i,
  51453. arrayLayerCount: 1
  51454. } );
  51455. }
  51456. layerDescriptor.depthStencilAttachment = {
  51457. view: depthTextureData.viewCache[ layerIndex ],
  51458. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  51459. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  51460. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  51461. };
  51462. if ( renderContext.stencil ) {
  51463. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  51464. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  51465. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  51466. }
  51467. } else {
  51468. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  51469. }
  51470. renderContextData.layerDescriptors.push( layerDescriptor );
  51471. }
  51472. }
  51473. /**
  51474. * This method updates the layer descriptors for each camera in an array camera
  51475. * to prepare for rendering to a depth array texture.
  51476. *
  51477. * @param {RenderContext} renderContext - The render context.
  51478. * @param {Object} renderContextData - The render context data.
  51479. * @param {ArrayCamera} cameras - The array camera.
  51480. *
  51481. */
  51482. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  51483. for ( let i = 0; i < cameras.length; i ++ ) {
  51484. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  51485. if ( layerDescriptor.depthStencilAttachment ) {
  51486. const depthAttachment = layerDescriptor.depthStencilAttachment;
  51487. if ( renderContext.depth ) {
  51488. if ( renderContext.clearDepth ) {
  51489. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  51490. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  51491. } else {
  51492. depthAttachment.depthLoadOp = GPULoadOp.Load;
  51493. }
  51494. }
  51495. if ( renderContext.stencil ) {
  51496. if ( renderContext.clearStencil ) {
  51497. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  51498. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  51499. } else {
  51500. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  51501. }
  51502. }
  51503. }
  51504. }
  51505. }
  51506. /**
  51507. * This method is executed at the end of a render call and finalizes work
  51508. * after draw calls.
  51509. *
  51510. * @param {RenderContext} renderContext - The render context.
  51511. */
  51512. finishRender( renderContext ) {
  51513. const renderContextData = this.get( renderContext );
  51514. const occlusionQueryCount = renderContext.occlusionQueryCount;
  51515. if ( renderContextData.renderBundles.length > 0 ) {
  51516. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  51517. }
  51518. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  51519. renderContextData.currentPass.endOcclusionQuery();
  51520. }
  51521. // shadow arrays - Execute bundles for each layer
  51522. const encoder = renderContextData.encoder;
  51523. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  51524. const bundles = [];
  51525. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  51526. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  51527. bundles.push( bundleEncoder.finish() );
  51528. }
  51529. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  51530. if ( i < bundles.length ) {
  51531. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  51532. const renderPass = encoder.beginRenderPass( layerDescriptor );
  51533. if ( renderContext.viewport ) {
  51534. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  51535. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  51536. }
  51537. if ( renderContext.scissor ) {
  51538. const { x, y, width, height } = renderContext.scissorValue;
  51539. renderPass.setScissorRect( x, y, width, height );
  51540. }
  51541. renderPass.executeBundles( [ bundles[ i ] ] );
  51542. renderPass.end();
  51543. }
  51544. }
  51545. } else if ( renderContextData.currentPass ) {
  51546. renderContextData.currentPass.end();
  51547. }
  51548. if ( occlusionQueryCount > 0 ) {
  51549. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  51550. //
  51551. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  51552. if ( queryResolveBuffer === undefined ) {
  51553. queryResolveBuffer = this.device.createBuffer(
  51554. {
  51555. size: bufferSize,
  51556. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  51557. }
  51558. );
  51559. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  51560. }
  51561. //
  51562. const readBuffer = this.device.createBuffer(
  51563. {
  51564. size: bufferSize,
  51565. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  51566. }
  51567. );
  51568. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  51569. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  51570. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  51571. renderContextData.occlusionQueryBuffer = readBuffer;
  51572. //
  51573. this.resolveOccludedAsync( renderContext );
  51574. }
  51575. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  51576. //
  51577. if ( renderContext.textures !== null ) {
  51578. const textures = renderContext.textures;
  51579. for ( let i = 0; i < textures.length; i ++ ) {
  51580. const texture = textures[ i ];
  51581. if ( texture.generateMipmaps === true ) {
  51582. this.textureUtils.generateMipmaps( texture );
  51583. }
  51584. }
  51585. }
  51586. }
  51587. /**
  51588. * Returns `true` if the given 3D object is fully occluded by other
  51589. * 3D objects in the scene.
  51590. *
  51591. * @param {RenderContext} renderContext - The render context.
  51592. * @param {Object3D} object - The 3D object to test.
  51593. * @return {boolean} Whether the 3D object is fully occluded or not.
  51594. */
  51595. isOccluded( renderContext, object ) {
  51596. const renderContextData = this.get( renderContext );
  51597. return renderContextData.occluded && renderContextData.occluded.has( object );
  51598. }
  51599. /**
  51600. * This method processes the result of occlusion queries and writes it
  51601. * into render context data.
  51602. *
  51603. * @async
  51604. * @param {RenderContext} renderContext - The render context.
  51605. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  51606. */
  51607. async resolveOccludedAsync( renderContext ) {
  51608. const renderContextData = this.get( renderContext );
  51609. // handle occlusion query results
  51610. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  51611. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  51612. const occluded = new WeakSet();
  51613. renderContextData.currentOcclusionQueryObjects = null;
  51614. renderContextData.currentOcclusionQueryBuffer = null;
  51615. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  51616. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  51617. const results = new BigUint64Array( buffer );
  51618. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  51619. if ( results[ i ] === BigInt( 0 ) ) {
  51620. occluded.add( currentOcclusionQueryObjects[ i ] );
  51621. }
  51622. }
  51623. currentOcclusionQueryBuffer.destroy();
  51624. renderContextData.occluded = occluded;
  51625. }
  51626. }
  51627. /**
  51628. * Updates the viewport with the values from the given render context.
  51629. *
  51630. * @param {RenderContext} renderContext - The render context.
  51631. */
  51632. updateViewport( renderContext ) {
  51633. const { currentPass } = this.get( renderContext );
  51634. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  51635. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  51636. }
  51637. /**
  51638. * Returns the clear color and alpha into a single
  51639. * color object.
  51640. *
  51641. * @return {Color4} The clear color.
  51642. */
  51643. getClearColor() {
  51644. const clearColor = super.getClearColor();
  51645. // only premultiply alpha when alphaMode is "premultiplied"
  51646. if ( this.renderer.alpha === true ) {
  51647. clearColor.r *= clearColor.a;
  51648. clearColor.g *= clearColor.a;
  51649. clearColor.b *= clearColor.a;
  51650. }
  51651. return clearColor;
  51652. }
  51653. /**
  51654. * Performs a clear operation.
  51655. *
  51656. * @param {boolean} color - Whether the color buffer should be cleared or not.
  51657. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  51658. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  51659. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  51660. */
  51661. clear( color, depth, stencil, renderTargetContext = null ) {
  51662. const device = this.device;
  51663. const renderer = this.renderer;
  51664. let colorAttachments = [];
  51665. let depthStencilAttachment;
  51666. let clearValue;
  51667. let supportsDepth;
  51668. let supportsStencil;
  51669. if ( color ) {
  51670. const clearColor = this.getClearColor();
  51671. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  51672. }
  51673. if ( renderTargetContext === null ) {
  51674. supportsDepth = renderer.depth;
  51675. supportsStencil = renderer.stencil;
  51676. const descriptor = this._getDefaultRenderPassDescriptor();
  51677. if ( color ) {
  51678. colorAttachments = descriptor.colorAttachments;
  51679. const colorAttachment = colorAttachments[ 0 ];
  51680. colorAttachment.clearValue = clearValue;
  51681. colorAttachment.loadOp = GPULoadOp.Clear;
  51682. colorAttachment.storeOp = GPUStoreOp.Store;
  51683. }
  51684. if ( supportsDepth || supportsStencil ) {
  51685. depthStencilAttachment = descriptor.depthStencilAttachment;
  51686. }
  51687. } else {
  51688. supportsDepth = renderTargetContext.depth;
  51689. supportsStencil = renderTargetContext.stencil;
  51690. const clearConfig = {
  51691. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  51692. clearValue: color ? clearValue : undefined
  51693. };
  51694. if ( supportsDepth ) {
  51695. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  51696. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  51697. clearConfig.depthStoreOp = GPUStoreOp.Store;
  51698. }
  51699. if ( supportsStencil ) {
  51700. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  51701. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  51702. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  51703. }
  51704. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  51705. colorAttachments = descriptor.colorAttachments;
  51706. depthStencilAttachment = descriptor.depthStencilAttachment;
  51707. }
  51708. if ( supportsDepth && depthStencilAttachment ) {
  51709. if ( depth ) {
  51710. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  51711. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  51712. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  51713. } else {
  51714. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  51715. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  51716. }
  51717. }
  51718. //
  51719. if ( supportsStencil && depthStencilAttachment ) {
  51720. if ( stencil ) {
  51721. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  51722. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  51723. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  51724. } else {
  51725. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  51726. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  51727. }
  51728. }
  51729. //
  51730. const encoder = device.createCommandEncoder( { label: 'clear' } );
  51731. const currentPass = encoder.beginRenderPass( {
  51732. colorAttachments,
  51733. depthStencilAttachment
  51734. } );
  51735. currentPass.end();
  51736. device.queue.submit( [ encoder.finish() ] );
  51737. }
  51738. // compute
  51739. /**
  51740. * This method is executed at the beginning of a compute call and
  51741. * prepares the state for upcoming compute tasks.
  51742. *
  51743. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  51744. */
  51745. beginCompute( computeGroup ) {
  51746. const groupGPU = this.get( computeGroup );
  51747. const descriptor = {
  51748. label: 'computeGroup_' + computeGroup.id
  51749. };
  51750. this.initTimestampQuery( computeGroup, descriptor );
  51751. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  51752. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  51753. }
  51754. /**
  51755. * Executes a compute command for the given compute node.
  51756. *
  51757. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  51758. * @param {Node} computeNode - The compute node.
  51759. * @param {Array<BindGroup>} bindings - The bindings.
  51760. * @param {ComputePipeline} pipeline - The compute pipeline.
  51761. * @param {Array<number>|number} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  51762. */
  51763. compute( computeGroup, computeNode, bindings, pipeline, dispatchSizeOrCount = null ) {
  51764. const computeNodeData = this.get( computeNode );
  51765. const { passEncoderGPU } = this.get( computeGroup );
  51766. // pipeline
  51767. const pipelineGPU = this.get( pipeline ).pipeline;
  51768. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  51769. // bind groups
  51770. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  51771. const bindGroup = bindings[ i ];
  51772. const bindingsData = this.get( bindGroup );
  51773. passEncoderGPU.setBindGroup( i, bindingsData.group );
  51774. }
  51775. let dispatchSize;
  51776. if ( dispatchSizeOrCount === null ) {
  51777. dispatchSizeOrCount = computeNode.count;
  51778. }
  51779. if ( typeof dispatchSizeOrCount === 'number' ) {
  51780. // If a single number is given, we calculate the dispatch size based on the workgroup size
  51781. const count = dispatchSizeOrCount;
  51782. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  51783. // cache dispatch size to avoid recalculating it every time
  51784. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  51785. computeNodeData.count = count;
  51786. const workgroupSize = computeNode.workgroupSize;
  51787. let size = workgroupSize[ 0 ];
  51788. for ( let i = 1; i < workgroupSize.length; i ++ )
  51789. size *= workgroupSize[ i ];
  51790. const dispatchCount = Math.ceil( count / size );
  51791. //
  51792. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  51793. dispatchSize = [ dispatchCount, 1, 1 ];
  51794. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  51795. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  51796. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  51797. }
  51798. computeNodeData.dispatchSize = dispatchSize;
  51799. }
  51800. dispatchSize = computeNodeData.dispatchSize;
  51801. } else {
  51802. dispatchSize = dispatchSizeOrCount;
  51803. }
  51804. //
  51805. passEncoderGPU.dispatchWorkgroups(
  51806. dispatchSize[ 0 ],
  51807. dispatchSize[ 1 ] || 1,
  51808. dispatchSize[ 2 ] || 1
  51809. );
  51810. }
  51811. /**
  51812. * This method is executed at the end of a compute call and
  51813. * finalizes work after compute tasks.
  51814. *
  51815. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  51816. */
  51817. finishCompute( computeGroup ) {
  51818. const groupData = this.get( computeGroup );
  51819. groupData.passEncoderGPU.end();
  51820. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  51821. }
  51822. /**
  51823. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  51824. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  51825. *
  51826. * @async
  51827. * @return {Promise} A Promise that resolves when synchronization has been finished.
  51828. */
  51829. async waitForGPU() {
  51830. await this.device.queue.onSubmittedWorkDone();
  51831. }
  51832. // render object
  51833. /**
  51834. * Executes a draw command for the given render object.
  51835. *
  51836. * @param {RenderObject} renderObject - The render object to draw.
  51837. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  51838. */
  51839. draw( renderObject, info ) {
  51840. const { object, material, context, pipeline } = renderObject;
  51841. const bindings = renderObject.getBindings();
  51842. const renderContextData = this.get( context );
  51843. const pipelineGPU = this.get( pipeline ).pipeline;
  51844. const index = renderObject.getIndex();
  51845. const hasIndex = ( index !== null );
  51846. const drawParams = renderObject.getDrawParameters();
  51847. if ( drawParams === null ) return;
  51848. // pipeline
  51849. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  51850. // pipeline
  51851. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  51852. currentSets.pipeline = pipelineGPU;
  51853. // bind groups
  51854. const currentBindingGroups = currentSets.bindingGroups;
  51855. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  51856. const bindGroup = bindings[ i ];
  51857. const bindingsData = this.get( bindGroup );
  51858. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  51859. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  51860. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  51861. }
  51862. }
  51863. // attributes
  51864. // index
  51865. if ( hasIndex === true ) {
  51866. if ( currentSets.index !== index ) {
  51867. const buffer = this.get( index ).buffer;
  51868. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  51869. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  51870. currentSets.index = index;
  51871. }
  51872. }
  51873. // vertex buffers
  51874. const vertexBuffers = renderObject.getVertexBuffers();
  51875. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  51876. const vertexBuffer = vertexBuffers[ i ];
  51877. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  51878. const buffer = this.get( vertexBuffer ).buffer;
  51879. passEncoderGPU.setVertexBuffer( i, buffer );
  51880. currentSets.attributes[ i ] = vertexBuffer;
  51881. }
  51882. }
  51883. // stencil
  51884. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  51885. passEncoderGPU.setStencilReference( material.stencilRef );
  51886. renderContextData.currentStencilRef = material.stencilRef;
  51887. }
  51888. };
  51889. // Define draw function
  51890. const draw = ( passEncoderGPU, currentSets ) => {
  51891. setPipelineAndBindings( passEncoderGPU, currentSets );
  51892. if ( object.isBatchedMesh === true ) {
  51893. const starts = object._multiDrawStarts;
  51894. const counts = object._multiDrawCounts;
  51895. const drawCount = object._multiDrawCount;
  51896. const drawInstances = object._multiDrawInstances;
  51897. if ( drawInstances !== null ) {
  51898. // @deprecated, r174
  51899. warnOnce( 'THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  51900. }
  51901. for ( let i = 0; i < drawCount; i ++ ) {
  51902. const count = drawInstances ? drawInstances[ i ] : 1;
  51903. const firstInstance = count > 1 ? 0 : i;
  51904. if ( hasIndex === true ) {
  51905. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  51906. } else {
  51907. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  51908. }
  51909. info.update( object, counts[ i ], count );
  51910. }
  51911. } else if ( hasIndex === true ) {
  51912. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  51913. const indirect = renderObject.getIndirect();
  51914. if ( indirect !== null ) {
  51915. const buffer = this.get( indirect ).buffer;
  51916. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  51917. } else {
  51918. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  51919. }
  51920. info.update( object, indexCount, instanceCount );
  51921. } else {
  51922. const { vertexCount, instanceCount, firstVertex } = drawParams;
  51923. const indirect = renderObject.getIndirect();
  51924. if ( indirect !== null ) {
  51925. const buffer = this.get( indirect ).buffer;
  51926. passEncoderGPU.drawIndirect( buffer, 0 );
  51927. } else {
  51928. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  51929. }
  51930. info.update( object, vertexCount, instanceCount );
  51931. }
  51932. };
  51933. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  51934. const cameraData = this.get( renderObject.camera );
  51935. const cameras = renderObject.camera.cameras;
  51936. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  51937. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  51938. const bindingsData = this.get( cameraIndex );
  51939. const indexesGPU = [];
  51940. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  51941. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  51942. data[ 0 ] = i;
  51943. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  51944. indexesGPU.push( bindGroupIndex );
  51945. }
  51946. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  51947. }
  51948. const pixelRatio = this.renderer.getPixelRatio();
  51949. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  51950. const subCamera = cameras[ i ];
  51951. if ( object.layers.test( subCamera.layers ) ) {
  51952. const vp = subCamera.viewport;
  51953. let pass = renderContextData.currentPass;
  51954. let sets = renderContextData.currentSets;
  51955. if ( renderContextData.bundleEncoders ) {
  51956. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  51957. const bundleSets = renderContextData.bundleSets[ i ];
  51958. pass = bundleEncoder;
  51959. sets = bundleSets;
  51960. }
  51961. if ( vp ) {
  51962. pass.setViewport(
  51963. Math.floor( vp.x * pixelRatio ),
  51964. Math.floor( vp.y * pixelRatio ),
  51965. Math.floor( vp.width * pixelRatio ),
  51966. Math.floor( vp.height * pixelRatio ),
  51967. context.viewportValue.minDepth,
  51968. context.viewportValue.maxDepth
  51969. );
  51970. }
  51971. // Set camera index binding for this layer
  51972. if ( cameraIndex && cameraData.indexesGPU ) {
  51973. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  51974. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  51975. }
  51976. draw( pass, sets );
  51977. }
  51978. }
  51979. } else {
  51980. // Regular single camera rendering
  51981. if ( renderContextData.currentPass ) {
  51982. // Handle occlusion queries
  51983. if ( renderContextData.occlusionQuerySet !== undefined ) {
  51984. const lastObject = renderContextData.lastOcclusionObject;
  51985. if ( lastObject !== object ) {
  51986. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  51987. renderContextData.currentPass.endOcclusionQuery();
  51988. renderContextData.occlusionQueryIndex ++;
  51989. }
  51990. if ( object.occlusionTest === true ) {
  51991. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  51992. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  51993. }
  51994. renderContextData.lastOcclusionObject = object;
  51995. }
  51996. }
  51997. draw( renderContextData.currentPass, renderContextData.currentSets );
  51998. }
  51999. }
  52000. }
  52001. // cache key
  52002. /**
  52003. * Returns `true` if the render pipeline requires an update.
  52004. *
  52005. * @param {RenderObject} renderObject - The render object.
  52006. * @return {boolean} Whether the render pipeline requires an update or not.
  52007. */
  52008. needsRenderUpdate( renderObject ) {
  52009. const data = this.get( renderObject );
  52010. const { object, material } = renderObject;
  52011. const utils = this.utils;
  52012. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  52013. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  52014. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  52015. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  52016. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  52017. let needsUpdate = false;
  52018. if ( data.material !== material || data.materialVersion !== material.version ||
  52019. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  52020. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  52021. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  52022. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  52023. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  52024. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  52025. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  52026. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  52027. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  52028. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  52029. data.primitiveTopology !== primitiveTopology ||
  52030. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  52031. ) {
  52032. data.material = material; data.materialVersion = material.version;
  52033. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  52034. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  52035. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  52036. data.colorWrite = material.colorWrite;
  52037. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  52038. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  52039. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  52040. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  52041. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  52042. data.sampleCount = sampleCount;
  52043. data.colorSpace = colorSpace;
  52044. data.colorFormat = colorFormat;
  52045. data.depthStencilFormat = depthStencilFormat;
  52046. data.primitiveTopology = primitiveTopology;
  52047. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  52048. needsUpdate = true;
  52049. }
  52050. return needsUpdate;
  52051. }
  52052. /**
  52053. * Returns a cache key that is used to identify render pipelines.
  52054. *
  52055. * @param {RenderObject} renderObject - The render object.
  52056. * @return {string} The cache key.
  52057. */
  52058. getRenderCacheKey( renderObject ) {
  52059. const { object, material } = renderObject;
  52060. const utils = this.utils;
  52061. const renderContext = renderObject.context;
  52062. return [
  52063. material.transparent, material.blending, material.premultipliedAlpha,
  52064. material.blendSrc, material.blendDst, material.blendEquation,
  52065. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  52066. material.colorWrite,
  52067. material.depthWrite, material.depthTest, material.depthFunc,
  52068. material.stencilWrite, material.stencilFunc,
  52069. material.stencilFail, material.stencilZFail, material.stencilZPass,
  52070. material.stencilFuncMask, material.stencilWriteMask,
  52071. material.side,
  52072. utils.getSampleCountRenderContext( renderContext ),
  52073. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  52074. utils.getPrimitiveTopology( object, material ),
  52075. renderObject.getGeometryCacheKey(),
  52076. renderObject.clippingContextCacheKey
  52077. ].join();
  52078. }
  52079. // textures
  52080. /**
  52081. * Creates a GPU sampler for the given texture.
  52082. *
  52083. * @param {Texture} texture - The texture to create the sampler for.
  52084. */
  52085. createSampler( texture ) {
  52086. this.textureUtils.createSampler( texture );
  52087. }
  52088. /**
  52089. * Destroys the GPU sampler for the given texture.
  52090. *
  52091. * @param {Texture} texture - The texture to destroy the sampler for.
  52092. */
  52093. destroySampler( texture ) {
  52094. this.textureUtils.destroySampler( texture );
  52095. }
  52096. /**
  52097. * Creates a default texture for the given texture that can be used
  52098. * as a placeholder until the actual texture is ready for usage.
  52099. *
  52100. * @param {Texture} texture - The texture to create a default texture for.
  52101. */
  52102. createDefaultTexture( texture ) {
  52103. this.textureUtils.createDefaultTexture( texture );
  52104. }
  52105. /**
  52106. * Defines a texture on the GPU for the given texture object.
  52107. *
  52108. * @param {Texture} texture - The texture.
  52109. * @param {Object} [options={}] - Optional configuration parameter.
  52110. */
  52111. createTexture( texture, options ) {
  52112. this.textureUtils.createTexture( texture, options );
  52113. }
  52114. /**
  52115. * Uploads the updated texture data to the GPU.
  52116. *
  52117. * @param {Texture} texture - The texture.
  52118. * @param {Object} [options={}] - Optional configuration parameter.
  52119. */
  52120. updateTexture( texture, options ) {
  52121. this.textureUtils.updateTexture( texture, options );
  52122. }
  52123. /**
  52124. * Generates mipmaps for the given texture.
  52125. *
  52126. * @param {Texture} texture - The texture.
  52127. */
  52128. generateMipmaps( texture ) {
  52129. this.textureUtils.generateMipmaps( texture );
  52130. }
  52131. /**
  52132. * Destroys the GPU data for the given texture object.
  52133. *
  52134. * @param {Texture} texture - The texture.
  52135. */
  52136. destroyTexture( texture ) {
  52137. this.textureUtils.destroyTexture( texture );
  52138. }
  52139. /**
  52140. * Returns texture data as a typed array.
  52141. *
  52142. * @async
  52143. * @param {Texture} texture - The texture to copy.
  52144. * @param {number} x - The x coordinate of the copy origin.
  52145. * @param {number} y - The y coordinate of the copy origin.
  52146. * @param {number} width - The width of the copy.
  52147. * @param {number} height - The height of the copy.
  52148. * @param {number} faceIndex - The face index.
  52149. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  52150. */
  52151. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  52152. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  52153. }
  52154. /**
  52155. * Inits a time stamp query for the given render context.
  52156. *
  52157. * @param {RenderContext} renderContext - The render context.
  52158. * @param {Object} descriptor - The query descriptor.
  52159. */
  52160. initTimestampQuery( renderContext, descriptor ) {
  52161. if ( ! this.trackTimestamp ) return;
  52162. const type = renderContext.isComputeNode ? 'compute' : 'render';
  52163. if ( ! this.timestampQueryPool[ type ] ) {
  52164. // TODO: Variable maxQueries?
  52165. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  52166. }
  52167. const timestampQueryPool = this.timestampQueryPool[ type ];
  52168. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  52169. descriptor.timestampWrites = {
  52170. querySet: timestampQueryPool.querySet,
  52171. beginningOfPassWriteIndex: baseOffset,
  52172. endOfPassWriteIndex: baseOffset + 1,
  52173. };
  52174. }
  52175. // node builder
  52176. /**
  52177. * Returns a node builder for the given render object.
  52178. *
  52179. * @param {RenderObject} object - The render object.
  52180. * @param {Renderer} renderer - The renderer.
  52181. * @return {WGSLNodeBuilder} The node builder.
  52182. */
  52183. createNodeBuilder( object, renderer ) {
  52184. return new WGSLNodeBuilder( object, renderer );
  52185. }
  52186. // program
  52187. /**
  52188. * Creates a shader program from the given programmable stage.
  52189. *
  52190. * @param {ProgrammableStage} program - The programmable stage.
  52191. */
  52192. createProgram( program ) {
  52193. const programGPU = this.get( program );
  52194. programGPU.module = {
  52195. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  52196. entryPoint: 'main'
  52197. };
  52198. }
  52199. /**
  52200. * Destroys the shader program of the given programmable stage.
  52201. *
  52202. * @param {ProgrammableStage} program - The programmable stage.
  52203. */
  52204. destroyProgram( program ) {
  52205. this.delete( program );
  52206. }
  52207. // pipelines
  52208. /**
  52209. * Creates a render pipeline for the given render object.
  52210. *
  52211. * @param {RenderObject} renderObject - The render object.
  52212. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  52213. */
  52214. createRenderPipeline( renderObject, promises ) {
  52215. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  52216. }
  52217. /**
  52218. * Creates a compute pipeline for the given compute node.
  52219. *
  52220. * @param {ComputePipeline} computePipeline - The compute pipeline.
  52221. * @param {Array<BindGroup>} bindings - The bindings.
  52222. */
  52223. createComputePipeline( computePipeline, bindings ) {
  52224. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  52225. }
  52226. /**
  52227. * Prepares the state for encoding render bundles.
  52228. *
  52229. * @param {RenderContext} renderContext - The render context.
  52230. */
  52231. beginBundle( renderContext ) {
  52232. const renderContextData = this.get( renderContext );
  52233. renderContextData._currentPass = renderContextData.currentPass;
  52234. renderContextData._currentSets = renderContextData.currentSets;
  52235. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  52236. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  52237. }
  52238. /**
  52239. * After processing render bundles this method finalizes related work.
  52240. *
  52241. * @param {RenderContext} renderContext - The render context.
  52242. * @param {RenderBundle} bundle - The render bundle.
  52243. */
  52244. finishBundle( renderContext, bundle ) {
  52245. const renderContextData = this.get( renderContext );
  52246. const bundleEncoder = renderContextData.currentPass;
  52247. const bundleGPU = bundleEncoder.finish();
  52248. this.get( bundle ).bundleGPU = bundleGPU;
  52249. // restore render pass state
  52250. renderContextData.currentSets = renderContextData._currentSets;
  52251. renderContextData.currentPass = renderContextData._currentPass;
  52252. }
  52253. /**
  52254. * Adds a render bundle to the render context data.
  52255. *
  52256. * @param {RenderContext} renderContext - The render context.
  52257. * @param {RenderBundle} bundle - The render bundle to add.
  52258. */
  52259. addBundle( renderContext, bundle ) {
  52260. const renderContextData = this.get( renderContext );
  52261. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  52262. }
  52263. // bindings
  52264. /**
  52265. * Creates bindings from the given bind group definition.
  52266. *
  52267. * @param {BindGroup} bindGroup - The bind group.
  52268. * @param {Array<BindGroup>} bindings - Array of bind groups.
  52269. * @param {number} cacheIndex - The cache index.
  52270. * @param {number} version - The version.
  52271. */
  52272. createBindings( bindGroup, bindings, cacheIndex, version ) {
  52273. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  52274. }
  52275. /**
  52276. * Updates the given bind group definition.
  52277. *
  52278. * @param {BindGroup} bindGroup - The bind group.
  52279. * @param {Array<BindGroup>} bindings - Array of bind groups.
  52280. * @param {number} cacheIndex - The cache index.
  52281. * @param {number} version - The version.
  52282. */
  52283. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  52284. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  52285. }
  52286. /**
  52287. * Updates a buffer binding.
  52288. *
  52289. * @param {Buffer} binding - The buffer binding to update.
  52290. */
  52291. updateBinding( binding ) {
  52292. this.bindingUtils.updateBinding( binding );
  52293. }
  52294. // attributes
  52295. /**
  52296. * Creates the buffer of an indexed shader attribute.
  52297. *
  52298. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  52299. */
  52300. createIndexAttribute( attribute ) {
  52301. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  52302. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  52303. usage |= GPUBufferUsage.STORAGE;
  52304. }
  52305. this.attributeUtils.createAttribute( attribute, usage );
  52306. }
  52307. /**
  52308. * Creates the GPU buffer of a shader attribute.
  52309. *
  52310. * @param {BufferAttribute} attribute - The buffer attribute.
  52311. */
  52312. createAttribute( attribute ) {
  52313. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  52314. }
  52315. /**
  52316. * Creates the GPU buffer of a storage attribute.
  52317. *
  52318. * @param {BufferAttribute} attribute - The buffer attribute.
  52319. */
  52320. createStorageAttribute( attribute ) {
  52321. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  52322. }
  52323. /**
  52324. * Creates the GPU buffer of an indirect storage attribute.
  52325. *
  52326. * @param {BufferAttribute} attribute - The buffer attribute.
  52327. */
  52328. createIndirectStorageAttribute( attribute ) {
  52329. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  52330. }
  52331. /**
  52332. * Updates the GPU buffer of a shader attribute.
  52333. *
  52334. * @param {BufferAttribute} attribute - The buffer attribute to update.
  52335. */
  52336. updateAttribute( attribute ) {
  52337. this.attributeUtils.updateAttribute( attribute );
  52338. }
  52339. /**
  52340. * Destroys the GPU buffer of a shader attribute.
  52341. *
  52342. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  52343. */
  52344. destroyAttribute( attribute ) {
  52345. this.attributeUtils.destroyAttribute( attribute );
  52346. }
  52347. // canvas
  52348. /**
  52349. * Triggers an update of the default render pass descriptor.
  52350. */
  52351. updateSize() {
  52352. this.colorBuffer = this.textureUtils.getColorBuffer();
  52353. this.defaultRenderPassdescriptor = null;
  52354. }
  52355. // utils public
  52356. /**
  52357. * Returns the maximum anisotropy texture filtering value.
  52358. *
  52359. * @return {number} The maximum anisotropy texture filtering value.
  52360. */
  52361. getMaxAnisotropy() {
  52362. return 16;
  52363. }
  52364. /**
  52365. * Checks if the given feature is supported by the backend.
  52366. *
  52367. * @param {string} name - The feature's name.
  52368. * @return {boolean} Whether the feature is supported or not.
  52369. */
  52370. hasFeature( name ) {
  52371. return this.device.features.has( name );
  52372. }
  52373. /**
  52374. * Copies data of the given source texture to the given destination texture.
  52375. *
  52376. * @param {Texture} srcTexture - The source texture.
  52377. * @param {Texture} dstTexture - The destination texture.
  52378. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  52379. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  52380. * @param {number} [srcLevel=0] - The mipmap level to copy.
  52381. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  52382. */
  52383. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  52384. let dstX = 0;
  52385. let dstY = 0;
  52386. let dstZ = 0;
  52387. let srcX = 0;
  52388. let srcY = 0;
  52389. let srcZ = 0;
  52390. let srcWidth = srcTexture.image.width;
  52391. let srcHeight = srcTexture.image.height;
  52392. let srcDepth = 1;
  52393. if ( srcRegion !== null ) {
  52394. if ( srcRegion.isBox3 === true ) {
  52395. srcX = srcRegion.min.x;
  52396. srcY = srcRegion.min.y;
  52397. srcZ = srcRegion.min.z;
  52398. srcWidth = srcRegion.max.x - srcRegion.min.x;
  52399. srcHeight = srcRegion.max.y - srcRegion.min.y;
  52400. srcDepth = srcRegion.max.z - srcRegion.min.z;
  52401. } else {
  52402. // Assume it's a Box2
  52403. srcX = srcRegion.min.x;
  52404. srcY = srcRegion.min.y;
  52405. srcWidth = srcRegion.max.x - srcRegion.min.x;
  52406. srcHeight = srcRegion.max.y - srcRegion.min.y;
  52407. srcDepth = 1;
  52408. }
  52409. }
  52410. if ( dstPosition !== null ) {
  52411. dstX = dstPosition.x;
  52412. dstY = dstPosition.y;
  52413. dstZ = dstPosition.z || 0;
  52414. }
  52415. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  52416. const sourceGPU = this.get( srcTexture ).texture;
  52417. const destinationGPU = this.get( dstTexture ).texture;
  52418. encoder.copyTextureToTexture(
  52419. {
  52420. texture: sourceGPU,
  52421. mipLevel: srcLevel,
  52422. origin: { x: srcX, y: srcY, z: srcZ }
  52423. },
  52424. {
  52425. texture: destinationGPU,
  52426. mipLevel: dstLevel,
  52427. origin: { x: dstX, y: dstY, z: dstZ }
  52428. },
  52429. [
  52430. srcWidth,
  52431. srcHeight,
  52432. srcDepth
  52433. ]
  52434. );
  52435. this.device.queue.submit( [ encoder.finish() ] );
  52436. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  52437. this.textureUtils.generateMipmaps( dstTexture );
  52438. }
  52439. }
  52440. /**
  52441. * Copies the current bound framebuffer to the given texture.
  52442. *
  52443. * @param {Texture} texture - The destination texture.
  52444. * @param {RenderContext} renderContext - The render context.
  52445. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  52446. */
  52447. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  52448. const renderContextData = this.get( renderContext );
  52449. let sourceGPU = null;
  52450. if ( renderContext.renderTarget ) {
  52451. if ( texture.isDepthTexture ) {
  52452. sourceGPU = this.get( renderContext.depthTexture ).texture;
  52453. } else {
  52454. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  52455. }
  52456. } else {
  52457. if ( texture.isDepthTexture ) {
  52458. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  52459. } else {
  52460. sourceGPU = this.context.getCurrentTexture();
  52461. }
  52462. }
  52463. const destinationGPU = this.get( texture ).texture;
  52464. if ( sourceGPU.format !== destinationGPU.format ) {
  52465. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  52466. return;
  52467. }
  52468. let encoder;
  52469. if ( renderContextData.currentPass ) {
  52470. renderContextData.currentPass.end();
  52471. encoder = renderContextData.encoder;
  52472. } else {
  52473. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  52474. }
  52475. encoder.copyTextureToTexture(
  52476. {
  52477. texture: sourceGPU,
  52478. origin: [ rectangle.x, rectangle.y, 0 ],
  52479. },
  52480. {
  52481. texture: destinationGPU
  52482. },
  52483. [
  52484. rectangle.z,
  52485. rectangle.w
  52486. ]
  52487. );
  52488. if ( renderContextData.currentPass ) {
  52489. const { descriptor } = renderContextData;
  52490. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  52491. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  52492. }
  52493. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  52494. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  52495. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  52496. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  52497. if ( renderContext.viewport ) {
  52498. this.updateViewport( renderContext );
  52499. }
  52500. if ( renderContext.scissor ) {
  52501. const { x, y, width, height } = renderContext.scissorValue;
  52502. renderContextData.currentPass.setScissorRect( x, y, width, height );
  52503. }
  52504. } else {
  52505. this.device.queue.submit( [ encoder.finish() ] );
  52506. }
  52507. if ( texture.generateMipmaps ) {
  52508. this.textureUtils.generateMipmaps( texture );
  52509. }
  52510. }
  52511. }
  52512. /**
  52513. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  52514. *
  52515. * @augments SpotLight
  52516. */
  52517. class IESSpotLight extends SpotLight {
  52518. /**
  52519. * Constructs a new IES spot light.
  52520. *
  52521. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  52522. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  52523. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  52524. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  52525. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  52526. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  52527. */
  52528. constructor( color, intensity, distance, angle, penumbra, decay ) {
  52529. super( color, intensity, distance, angle, penumbra, decay );
  52530. /**
  52531. * TODO
  52532. *
  52533. * @type {?Texture}
  52534. * @default null
  52535. */
  52536. this.iesMap = null;
  52537. }
  52538. copy( source, recursive ) {
  52539. super.copy( source, recursive );
  52540. this.iesMap = source.iesMap;
  52541. return this;
  52542. }
  52543. }
  52544. /**
  52545. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  52546. *
  52547. * @augments SpotLight
  52548. */
  52549. class ProjectorLight extends SpotLight {
  52550. /**
  52551. * Constructs a new projector light.
  52552. *
  52553. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  52554. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  52555. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  52556. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  52557. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  52558. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  52559. */
  52560. constructor( color, intensity, distance, angle, penumbra, decay ) {
  52561. super( color, intensity, distance, angle, penumbra, decay );
  52562. /**
  52563. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  52564. *
  52565. * @type {number}
  52566. * @default null
  52567. */
  52568. this.aspect = null;
  52569. }
  52570. copy( source, recursive ) {
  52571. super.copy( source, recursive );
  52572. this.aspect = source.aspect;
  52573. return this;
  52574. }
  52575. }
  52576. /**
  52577. * This version of a node library represents a basic version
  52578. * just focusing on lights and tone mapping techniques.
  52579. *
  52580. * @private
  52581. * @augments NodeLibrary
  52582. */
  52583. class BasicNodeLibrary extends NodeLibrary {
  52584. /**
  52585. * Constructs a new basic node library.
  52586. */
  52587. constructor() {
  52588. super();
  52589. this.addLight( PointLightNode, PointLight );
  52590. this.addLight( DirectionalLightNode, DirectionalLight );
  52591. this.addLight( RectAreaLightNode, RectAreaLight );
  52592. this.addLight( SpotLightNode, SpotLight );
  52593. this.addLight( AmbientLightNode, AmbientLight );
  52594. this.addLight( HemisphereLightNode, HemisphereLight );
  52595. this.addLight( LightProbeNode, LightProbe );
  52596. this.addLight( IESSpotLightNode, IESSpotLight );
  52597. this.addLight( ProjectorLightNode, ProjectorLight );
  52598. this.addToneMapping( linearToneMapping, LinearToneMapping );
  52599. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  52600. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  52601. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  52602. this.addToneMapping( agxToneMapping, AgXToneMapping );
  52603. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  52604. }
  52605. }
  52606. /**
  52607. * This alternative version of {@link WebGPURenderer} only supports node materials.
  52608. * So classes like `MeshBasicMaterial` are not compatible.
  52609. *
  52610. * @private
  52611. * @augments Renderer
  52612. */
  52613. class WebGPURenderer extends Renderer {
  52614. /**
  52615. * Constructs a new WebGPU renderer.
  52616. *
  52617. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  52618. */
  52619. constructor( parameters = {} ) {
  52620. let BackendClass;
  52621. if ( parameters.forceWebGL ) {
  52622. BackendClass = WebGLBackend;
  52623. } else {
  52624. BackendClass = WebGPUBackend;
  52625. parameters.getFallback = () => {
  52626. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  52627. return new WebGLBackend( parameters );
  52628. };
  52629. }
  52630. const backend = new BackendClass( parameters );
  52631. super( backend, parameters );
  52632. /**
  52633. * The generic default value is overwritten with the
  52634. * standard node library for type mapping. Material
  52635. * mapping is not supported with this version.
  52636. *
  52637. * @type {BasicNodeLibrary}
  52638. */
  52639. this.library = new BasicNodeLibrary();
  52640. /**
  52641. * This flag can be used for type testing.
  52642. *
  52643. * @type {boolean}
  52644. * @readonly
  52645. * @default true
  52646. */
  52647. this.isWebGPURenderer = true;
  52648. }
  52649. }
  52650. /**
  52651. * A specialized group which enables applications access to the
  52652. * Render Bundle API of WebGPU. The group with all its descendant nodes
  52653. * are considered as one render bundle and processed as such by
  52654. * the renderer.
  52655. *
  52656. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  52657. * With a WebGL backend, the group can technically be rendered but without
  52658. * any performance improvements.
  52659. *
  52660. * @augments Group
  52661. */
  52662. class BundleGroup extends Group {
  52663. /**
  52664. * Constructs a new bundle group.
  52665. */
  52666. constructor() {
  52667. super();
  52668. /**
  52669. * This flag can be used for type testing.
  52670. *
  52671. * @type {boolean}
  52672. * @readonly
  52673. * @default true
  52674. */
  52675. this.isBundleGroup = true;
  52676. /**
  52677. * This property is only relevant for detecting types
  52678. * during serialization/deserialization. It should always
  52679. * match the class name.
  52680. *
  52681. * @type {string}
  52682. * @readonly
  52683. * @default 'BundleGroup'
  52684. */
  52685. this.type = 'BundleGroup';
  52686. /**
  52687. * Whether the bundle is static or not. When set to `true`, the structure
  52688. * is assumed to be static and does not change. E.g. no new objects are
  52689. * added to the group
  52690. *
  52691. * If a change is required, an update can still be forced by setting the
  52692. * `needsUpdate` flag to `true`.
  52693. *
  52694. * @type {boolean}
  52695. * @default true
  52696. */
  52697. this.static = true;
  52698. /**
  52699. * The bundle group's version.
  52700. *
  52701. * @type {number}
  52702. * @readonly
  52703. * @default 0
  52704. */
  52705. this.version = 0;
  52706. }
  52707. /**
  52708. * Set this property to `true` when the bundle group has changed.
  52709. *
  52710. * @type {boolean}
  52711. * @default false
  52712. * @param {boolean} value
  52713. */
  52714. set needsUpdate( value ) {
  52715. if ( value === true ) this.version ++;
  52716. }
  52717. }
  52718. /**
  52719. * This module is responsible to manage the post processing setups in apps.
  52720. * You usually create a single instance of this class and use it to define
  52721. * the output of your post processing effect chain.
  52722. * ```js
  52723. * const postProcessing = new PostProcessing( renderer );
  52724. *
  52725. * const scenePass = pass( scene, camera );
  52726. *
  52727. * postProcessing.outputNode = scenePass;
  52728. * ```
  52729. *
  52730. * Note: This module can only be used with `WebGPURenderer`.
  52731. */
  52732. class PostProcessing {
  52733. /**
  52734. * Constructs a new post processing management module.
  52735. *
  52736. * @param {Renderer} renderer - A reference to the renderer.
  52737. * @param {Node<vec4>} outputNode - An optional output node.
  52738. */
  52739. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  52740. /**
  52741. * A reference to the renderer.
  52742. *
  52743. * @type {Renderer}
  52744. */
  52745. this.renderer = renderer;
  52746. /**
  52747. * A node which defines the final output of the post
  52748. * processing. This is usually the last node in a chain
  52749. * of effect nodes.
  52750. *
  52751. * @type {Node<vec4>}
  52752. */
  52753. this.outputNode = outputNode;
  52754. /**
  52755. * Whether the default output tone mapping and color
  52756. * space transformation should be enabled or not.
  52757. *
  52758. * It is enabled by default by it must be disabled when
  52759. * effects must be executed after tone mapping and color
  52760. * space conversion. A typical example is FXAA which
  52761. * requires sRGB input.
  52762. *
  52763. * When set to `false`, the app must control the output
  52764. * transformation with `RenderOutputNode`.
  52765. *
  52766. * ```js
  52767. * const outputPass = renderOutput( scenePass );
  52768. * ```
  52769. *
  52770. * @type {boolean}
  52771. */
  52772. this.outputColorTransform = true;
  52773. /**
  52774. * Must be set to `true` when the output node changes.
  52775. *
  52776. * @type {Node<vec4>}
  52777. */
  52778. this.needsUpdate = true;
  52779. const material = new NodeMaterial();
  52780. material.name = 'PostProcessing';
  52781. /**
  52782. * The full screen quad that is used to render
  52783. * the effects.
  52784. *
  52785. * @private
  52786. * @type {QuadMesh}
  52787. */
  52788. this._quadMesh = new QuadMesh( material );
  52789. /**
  52790. * The context of the post processing stack.
  52791. *
  52792. * @private
  52793. * @type {?Object}
  52794. * @default null
  52795. */
  52796. this._context = null;
  52797. }
  52798. /**
  52799. * When `PostProcessing` is used to apply post processing effects,
  52800. * the application must use this version of `render()` inside
  52801. * its animation loop (not the one from the renderer).
  52802. */
  52803. render() {
  52804. const renderer = this.renderer;
  52805. this._update();
  52806. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  52807. const toneMapping = renderer.toneMapping;
  52808. const outputColorSpace = renderer.outputColorSpace;
  52809. renderer.toneMapping = NoToneMapping;
  52810. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  52811. //
  52812. const currentXR = renderer.xr.enabled;
  52813. renderer.xr.enabled = false;
  52814. this._quadMesh.render( renderer );
  52815. renderer.xr.enabled = currentXR;
  52816. //
  52817. renderer.toneMapping = toneMapping;
  52818. renderer.outputColorSpace = outputColorSpace;
  52819. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  52820. }
  52821. /**
  52822. * Returns the current context of the post processing stack.
  52823. *
  52824. * @readonly
  52825. * @type {?Object}
  52826. */
  52827. get context() {
  52828. return this._context;
  52829. }
  52830. /**
  52831. * Frees internal resources.
  52832. */
  52833. dispose() {
  52834. this._quadMesh.material.dispose();
  52835. }
  52836. /**
  52837. * Updates the state of the module.
  52838. *
  52839. * @private
  52840. */
  52841. _update() {
  52842. if ( this.needsUpdate === true ) {
  52843. const renderer = this.renderer;
  52844. const toneMapping = renderer.toneMapping;
  52845. const outputColorSpace = renderer.outputColorSpace;
  52846. const context = {
  52847. postProcessing: this,
  52848. onBeforePostProcessing: null,
  52849. onAfterPostProcessing: null
  52850. };
  52851. let outputNode = this.outputNode;
  52852. if ( this.outputColorTransform === true ) {
  52853. outputNode = outputNode.context( context );
  52854. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  52855. } else {
  52856. context.toneMapping = toneMapping;
  52857. context.outputColorSpace = outputColorSpace;
  52858. outputNode = outputNode.context( context );
  52859. }
  52860. this._context = context;
  52861. this._quadMesh.material.fragmentNode = outputNode;
  52862. this._quadMesh.material.needsUpdate = true;
  52863. this.needsUpdate = false;
  52864. }
  52865. }
  52866. /**
  52867. * When `PostProcessing` is used to apply post processing effects,
  52868. * the application must use this version of `renderAsync()` inside
  52869. * its animation loop (not the one from the renderer).
  52870. *
  52871. * @async
  52872. * @return {Promise} A Promise that resolves when the render has been finished.
  52873. */
  52874. async renderAsync() {
  52875. this._update();
  52876. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  52877. const renderer = this.renderer;
  52878. const toneMapping = renderer.toneMapping;
  52879. const outputColorSpace = renderer.outputColorSpace;
  52880. renderer.toneMapping = NoToneMapping;
  52881. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  52882. //
  52883. const currentXR = renderer.xr.enabled;
  52884. renderer.xr.enabled = false;
  52885. await this._quadMesh.renderAsync( renderer );
  52886. renderer.xr.enabled = currentXR;
  52887. //
  52888. renderer.toneMapping = toneMapping;
  52889. renderer.outputColorSpace = outputColorSpace;
  52890. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  52891. }
  52892. }
  52893. /**
  52894. * This special type of texture is intended for compute shaders.
  52895. * It can be used to compute the data of a texture with a compute shader.
  52896. *
  52897. * Note: This type of texture can only be used with `WebGPURenderer`
  52898. * and a WebGPU backend.
  52899. *
  52900. * @augments Texture
  52901. */
  52902. class StorageTexture extends Texture {
  52903. /**
  52904. * Constructs a new storage texture.
  52905. *
  52906. * @param {number} [width=1] - The storage texture's width.
  52907. * @param {number} [height=1] - The storage texture's height.
  52908. */
  52909. constructor( width = 1, height = 1 ) {
  52910. super();
  52911. /**
  52912. * The image object which just represents the texture's dimension.
  52913. *
  52914. * @type {{width: number, height: number}}
  52915. */
  52916. this.image = { width, height };
  52917. /**
  52918. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  52919. *
  52920. * @type {number}
  52921. */
  52922. this.magFilter = LinearFilter;
  52923. /**
  52924. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  52925. *
  52926. * @type {number}
  52927. */
  52928. this.minFilter = LinearFilter;
  52929. /**
  52930. * This flag can be used for type testing.
  52931. *
  52932. * @type {boolean}
  52933. * @readonly
  52934. * @default true
  52935. */
  52936. this.isStorageTexture = true;
  52937. }
  52938. /**
  52939. * Sets the size of the storage texture.
  52940. *
  52941. * @param {number} width - The new width of the storage texture.
  52942. * @param {number} height - The new height of the storage texture.
  52943. */
  52944. setSize( width, height ) {
  52945. if ( this.image.width !== width || this.image.height !== height ) {
  52946. this.image.width = width;
  52947. this.image.height = height;
  52948. this.dispose();
  52949. }
  52950. }
  52951. }
  52952. /**
  52953. * This special type of buffer attribute is intended for compute shaders.
  52954. * It can be used to encode draw parameters for indirect draw calls.
  52955. *
  52956. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  52957. * and a WebGPU backend.
  52958. *
  52959. * @augments StorageBufferAttribute
  52960. */
  52961. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  52962. /**
  52963. * Constructs a new storage buffer attribute.
  52964. *
  52965. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  52966. * The subsequent parameter is then obsolete.
  52967. * @param {number} itemSize - The item size.
  52968. */
  52969. constructor( count, itemSize ) {
  52970. super( count, itemSize, Uint32Array );
  52971. /**
  52972. * This flag can be used for type testing.
  52973. *
  52974. * @type {boolean}
  52975. * @readonly
  52976. * @default true
  52977. */
  52978. this.isIndirectStorageBufferAttribute = true;
  52979. }
  52980. }
  52981. /**
  52982. * A loader for loading node objects in the three.js JSON Object/Scene format.
  52983. *
  52984. * @augments Loader
  52985. */
  52986. class NodeLoader extends Loader {
  52987. /**
  52988. * Constructs a new node loader.
  52989. *
  52990. * @param {LoadingManager} [manager] - A reference to a loading manager.
  52991. */
  52992. constructor( manager ) {
  52993. super( manager );
  52994. /**
  52995. * Represents a dictionary of textures.
  52996. *
  52997. * @type {Object<string,Texture>}
  52998. */
  52999. this.textures = {};
  53000. /**
  53001. * Represents a dictionary of node types.
  53002. *
  53003. * @type {Object<string,Node.constructor>}
  53004. */
  53005. this.nodes = {};
  53006. }
  53007. /**
  53008. * Loads the node definitions from the given URL.
  53009. *
  53010. * @param {string} url - The path/URL of the file to be loaded.
  53011. * @param {Function} onLoad - Will be called when load completes.
  53012. * @param {Function} onProgress - Will be called while load progresses.
  53013. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  53014. */
  53015. load( url, onLoad, onProgress, onError ) {
  53016. const loader = new FileLoader( this.manager );
  53017. loader.setPath( this.path );
  53018. loader.setRequestHeader( this.requestHeader );
  53019. loader.setWithCredentials( this.withCredentials );
  53020. loader.load( url, ( text ) => {
  53021. try {
  53022. onLoad( this.parse( JSON.parse( text ) ) );
  53023. } catch ( e ) {
  53024. if ( onError ) {
  53025. onError( e );
  53026. } else {
  53027. console.error( e );
  53028. }
  53029. this.manager.itemError( url );
  53030. }
  53031. }, onProgress, onError );
  53032. }
  53033. /**
  53034. * Parse the node dependencies for the loaded node.
  53035. *
  53036. * @param {Array<Object>} [json] - The JSON definition
  53037. * @return {Object<string,Node>} A dictionary with node dependencies.
  53038. */
  53039. parseNodes( json ) {
  53040. const nodes = {};
  53041. if ( json !== undefined ) {
  53042. for ( const nodeJSON of json ) {
  53043. const { uuid, type } = nodeJSON;
  53044. nodes[ uuid ] = this.createNodeFromType( type );
  53045. nodes[ uuid ].uuid = uuid;
  53046. }
  53047. const meta = { nodes, textures: this.textures };
  53048. for ( const nodeJSON of json ) {
  53049. nodeJSON.meta = meta;
  53050. const node = nodes[ nodeJSON.uuid ];
  53051. node.deserialize( nodeJSON );
  53052. delete nodeJSON.meta;
  53053. }
  53054. }
  53055. return nodes;
  53056. }
  53057. /**
  53058. * Parses the node from the given JSON.
  53059. *
  53060. * @param {Object} json - The JSON definition
  53061. * @param {string} json.type - The node type.
  53062. * @param {string} json.uuid - The node UUID.
  53063. * @param {Array<Object>} [json.nodes] - The node dependencies.
  53064. * @param {Object} [json.meta] - The meta data.
  53065. * @return {Node} The parsed node.
  53066. */
  53067. parse( json ) {
  53068. const node = this.createNodeFromType( json.type );
  53069. node.uuid = json.uuid;
  53070. const nodes = this.parseNodes( json.nodes );
  53071. const meta = { nodes, textures: this.textures };
  53072. json.meta = meta;
  53073. node.deserialize( json );
  53074. delete json.meta;
  53075. return node;
  53076. }
  53077. /**
  53078. * Defines the dictionary of textures.
  53079. *
  53080. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  53081. * @return {NodeLoader} A reference to this loader.
  53082. */
  53083. setTextures( value ) {
  53084. this.textures = value;
  53085. return this;
  53086. }
  53087. /**
  53088. * Defines the dictionary of node types.
  53089. *
  53090. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  53091. * @return {NodeLoader} A reference to this loader.
  53092. */
  53093. setNodes( value ) {
  53094. this.nodes = value;
  53095. return this;
  53096. }
  53097. /**
  53098. * Creates a node object from the given type.
  53099. *
  53100. * @param {string} type - The node type.
  53101. * @return {Node} The created node instance.
  53102. */
  53103. createNodeFromType( type ) {
  53104. if ( this.nodes[ type ] === undefined ) {
  53105. console.error( 'THREE.NodeLoader: Node type not found:', type );
  53106. return float();
  53107. }
  53108. return nodeObject( new this.nodes[ type ]() );
  53109. }
  53110. }
  53111. /**
  53112. * A special type of material loader for loading node materials.
  53113. *
  53114. * @augments MaterialLoader
  53115. */
  53116. class NodeMaterialLoader extends MaterialLoader {
  53117. /**
  53118. * Constructs a new node material loader.
  53119. *
  53120. * @param {LoadingManager} [manager] - A reference to a loading manager.
  53121. */
  53122. constructor( manager ) {
  53123. super( manager );
  53124. /**
  53125. * Represents a dictionary of node types.
  53126. *
  53127. * @type {Object<string,Node.constructor>}
  53128. */
  53129. this.nodes = {};
  53130. /**
  53131. * Represents a dictionary of node material types.
  53132. *
  53133. * @type {Object<string,NodeMaterial.constructor>}
  53134. */
  53135. this.nodeMaterials = {};
  53136. }
  53137. /**
  53138. * Parses the node material from the given JSON.
  53139. *
  53140. * @param {Object} json - The JSON definition
  53141. * @return {NodeMaterial}. The parsed material.
  53142. */
  53143. parse( json ) {
  53144. const material = super.parse( json );
  53145. const nodes = this.nodes;
  53146. const inputNodes = json.inputNodes;
  53147. for ( const property in inputNodes ) {
  53148. const uuid = inputNodes[ property ];
  53149. material[ property ] = nodes[ uuid ];
  53150. }
  53151. return material;
  53152. }
  53153. /**
  53154. * Defines the dictionary of node types.
  53155. *
  53156. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  53157. * @return {NodeLoader} A reference to this loader.
  53158. */
  53159. setNodes( value ) {
  53160. this.nodes = value;
  53161. return this;
  53162. }
  53163. /**
  53164. * Defines the dictionary of node material types.
  53165. *
  53166. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  53167. * @return {NodeLoader} A reference to this loader.
  53168. */
  53169. setNodeMaterials( value ) {
  53170. this.nodeMaterials = value;
  53171. return this;
  53172. }
  53173. /**
  53174. * Creates a node material from the given type.
  53175. *
  53176. * @param {string} type - The node material type.
  53177. * @return {Node} The created node material instance.
  53178. */
  53179. createMaterialFromType( type ) {
  53180. const materialClass = this.nodeMaterials[ type ];
  53181. if ( materialClass !== undefined ) {
  53182. return new materialClass();
  53183. }
  53184. return super.createMaterialFromType( type );
  53185. }
  53186. }
  53187. /**
  53188. * A special type of object loader for loading 3D objects using
  53189. * node materials.
  53190. *
  53191. * @augments ObjectLoader
  53192. */
  53193. class NodeObjectLoader extends ObjectLoader {
  53194. /**
  53195. * Constructs a new node object loader.
  53196. *
  53197. * @param {LoadingManager} [manager] - A reference to a loading manager.
  53198. */
  53199. constructor( manager ) {
  53200. super( manager );
  53201. /**
  53202. * Represents a dictionary of node types.
  53203. *
  53204. * @type {Object<string,Node.constructor>}
  53205. */
  53206. this.nodes = {};
  53207. /**
  53208. * Represents a dictionary of node material types.
  53209. *
  53210. * @type {Object<string,NodeMaterial.constructor>}
  53211. */
  53212. this.nodeMaterials = {};
  53213. /**
  53214. * A reference to hold the `nodes` JSON property.
  53215. *
  53216. * @private
  53217. * @type {?Object[]}
  53218. */
  53219. this._nodesJSON = null;
  53220. }
  53221. /**
  53222. * Defines the dictionary of node types.
  53223. *
  53224. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  53225. * @return {NodeObjectLoader} A reference to this loader.
  53226. */
  53227. setNodes( value ) {
  53228. this.nodes = value;
  53229. return this;
  53230. }
  53231. /**
  53232. * Defines the dictionary of node material types.
  53233. *
  53234. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  53235. * @return {NodeObjectLoader} A reference to this loader.
  53236. */
  53237. setNodeMaterials( value ) {
  53238. this.nodeMaterials = value;
  53239. return this;
  53240. }
  53241. /**
  53242. * Parses the node objects from the given JSON.
  53243. *
  53244. * @param {Object} json - The JSON definition
  53245. * @param {Function} onLoad - The onLoad callback function.
  53246. * @return {Object3D}. The parsed 3D object.
  53247. */
  53248. parse( json, onLoad ) {
  53249. this._nodesJSON = json.nodes;
  53250. const data = super.parse( json, onLoad );
  53251. this._nodesJSON = null; // dispose
  53252. return data;
  53253. }
  53254. /**
  53255. * Parses the node objects from the given JSON and textures.
  53256. *
  53257. * @param {Object[]} json - The JSON definition
  53258. * @param {Object<string,Texture>} textures - The texture library.
  53259. * @return {Object<string,Node>}. The parsed nodes.
  53260. */
  53261. parseNodes( json, textures ) {
  53262. if ( json !== undefined ) {
  53263. const loader = new NodeLoader();
  53264. loader.setNodes( this.nodes );
  53265. loader.setTextures( textures );
  53266. return loader.parseNodes( json );
  53267. }
  53268. return {};
  53269. }
  53270. /**
  53271. * Parses the node objects from the given JSON and textures.
  53272. *
  53273. * @param {Object} json - The JSON definition
  53274. * @param {Object<string,Texture>} textures - The texture library.
  53275. * @return {Object<string,NodeMaterial>}. The parsed materials.
  53276. */
  53277. parseMaterials( json, textures ) {
  53278. const materials = {};
  53279. if ( json !== undefined ) {
  53280. const nodes = this.parseNodes( this._nodesJSON, textures );
  53281. const loader = new NodeMaterialLoader();
  53282. loader.setTextures( textures );
  53283. loader.setNodes( nodes );
  53284. loader.setNodeMaterials( this.nodeMaterials );
  53285. for ( let i = 0, l = json.length; i < l; i ++ ) {
  53286. const data = json[ i ];
  53287. materials[ data.uuid ] = loader.parse( data );
  53288. }
  53289. }
  53290. return materials;
  53291. }
  53292. }
  53293. /**
  53294. * In earlier three.js versions, clipping was defined globally
  53295. * on the renderer or on material level. This special version of
  53296. * `THREE.Group` allows to encode the clipping state into the scene
  53297. * graph. Meaning if you create an instance of this group, all
  53298. * descendant 3D objects will be affected by the respective clipping
  53299. * planes.
  53300. *
  53301. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  53302. *
  53303. * @augments Group
  53304. */
  53305. class ClippingGroup extends Group {
  53306. /**
  53307. * Constructs a new clipping group.
  53308. */
  53309. constructor() {
  53310. super();
  53311. /**
  53312. * This flag can be used for type testing.
  53313. *
  53314. * @type {boolean}
  53315. * @readonly
  53316. * @default true
  53317. */
  53318. this.isClippingGroup = true;
  53319. /**
  53320. * An array with clipping planes.
  53321. *
  53322. * @type {Array<Plane>}
  53323. */
  53324. this.clippingPlanes = [];
  53325. /**
  53326. * Whether clipping should be enabled or not.
  53327. *
  53328. * @type {boolean}
  53329. * @default true
  53330. */
  53331. this.enabled = true;
  53332. /**
  53333. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  53334. *
  53335. * @type {boolean}
  53336. * @default false
  53337. */
  53338. this.clipIntersection = false;
  53339. /**
  53340. * Whether shadows should be clipped or not.
  53341. *
  53342. * @type {boolean}
  53343. * @default false
  53344. */
  53345. this.clipShadows = false;
  53346. }
  53347. }
  53348. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, Camera, 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, InstanceNode, InstancedBufferAttribute, InstancedInterleavedBuffer, InstancedMeshNode, IntType, InterleavedBuffer, InterleavedBufferAttribute, InvertStencilOp, IrradianceNode, JoinNode, KeepStencilOp, LessCompare, LessDepth, LessEqualCompare, LessEqualDepth, LessEqualStencilFunc, LessStencilFunc, LightProbe, LightProbeNode, Lighting, LightingContextNode, LightingModel, LightingNode, LightsNode, Line2NodeMaterial, LineBasicMaterial, LineBasicNodeMaterial, LineDashedMaterial, LineDashedNodeMaterial, LinearFilter, LinearMipMapLinearFilter, LinearMipmapLinearFilter, LinearMipmapNearestFilter, LinearSRGBColorSpace, LinearToneMapping, LinearTransfer, Loader, LoopNode, MRTNode, Material, MaterialLoader, MaterialNode, MaterialReferenceNode, MathUtils, Matrix2, Matrix3, Matrix4, MaxEquation, MaxMipLevelNode, MemberNode, Mesh, MeshBasicMaterial, MeshBasicNodeMaterial, MeshLambertMaterial, MeshLambertNodeMaterial, MeshMatcapMaterial, MeshMatcapNodeMaterial, MeshNormalMaterial, MeshNormalNodeMaterial, MeshPhongMaterial, MeshPhongNodeMaterial, MeshPhysicalMaterial, MeshPhysicalNodeMaterial, MeshSSSNodeMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, MeshToonMaterial, MeshToonNodeMaterial, MinEquation, MirroredRepeatWrapping, MixOperation, ModelNode, MorphNode, MultiplyBlending, MultiplyOperation, NearestFilter, NearestMipmapLinearFilter, NearestMipmapNearestFilter, NeutralToneMapping, NeverCompare, NeverDepth, NeverStencilFunc, NoBlending, NoColorSpace, NoToneMapping, Node, NodeAccess, NodeAttribute, NodeBuilder, NodeCache, NodeCode, NodeFrame, NodeFunctionInput, NodeLoader, NodeMaterial, NodeMaterialLoader, NodeMaterialObserver, NodeObjectLoader, NodeShaderStage, NodeType, NodeUniform, NodeUpdateType, NodeUtils, NodeVar, NodeVarying, NormalBlending, NormalMapNode, NotEqualCompare, NotEqualDepth, NotEqualStencilFunc, Object3D, Object3DNode, ObjectLoader, ObjectSpaceNormalMap, OneFactor, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, OrthographicCamera, OutputStructNode, PCFShadowMap, PMREMGenerator, PMREMNode, ParameterNode, PassNode, PerspectiveCamera, PhongLightingModel, PhysicalLightingModel, Plane, PlaneGeometry, PointLight, PointLightNode, PointUVNode, PointsMaterial, PointsNodeMaterial, PostProcessing, PosterizeNode, ProjectorLight, ProjectorLightNode, PropertyNode, QuadMesh, Quaternion, RED_GREEN_RGTC2_Format, RED_RGTC1_Format, REVISION, RGBAFormat, RGBAIntegerFormat, RGBA_ASTC_10x10_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_BPTC_Format, RGBA_ETC2_EAC_Format, RGBA_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGBFormat, RGBIntegerFormat, RGB_ETC1_Format, RGB_ETC2_Format, RGB_PVRTC_2BPPV1_Format, RGB_PVRTC_4BPPV1_Format, RGB_S3TC_DXT1_Format, RGFormat, RGIntegerFormat, RTTNode, RangeNode, RectAreaLight, RectAreaLightNode, RedFormat, RedIntegerFormat, ReferenceNode, ReflectorNode, ReinhardToneMapping, RemapNode, RenderOutputNode, RenderTarget, RendererReferenceNode, RendererUtils, RepeatWrapping, ReplaceStencilOp, ReverseSubtractEquation, RotateNode, SIGNED_RED_GREEN_RGTC2_Format, SIGNED_RED_RGTC1_Format, SRGBColorSpace, SRGBTransfer, Scene, SceneNode, ScreenNode, ScriptableNode, ScriptableValueNode, SetNode, ShadowBaseNode, ShadowMaterial, ShadowNode, ShadowNodeMaterial, ShortType, SkinningNode, Sphere, SphereGeometry, SplitNode, SpotLight, SpotLightNode, SpriteMaterial, SpriteNodeMaterial, SpriteSheetUVNode, SrcAlphaFactor, SrcAlphaSaturateFactor, SrcColorFactor, StackNode, StaticDrawUsage, StorageArrayElementNode, StorageBufferAttribute, StorageBufferNode, StorageInstancedBufferAttribute, StorageTexture, StorageTextureNode, StructNode, StructTypeNode, SubBuildNode, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, 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, shaderStages, vectorComponents };
粤ICP备19079148号