three.webgpu.nodes.js 1.8 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886
  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, warnOnce, 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, createCanvasElement, ReverseSubtractEquation, SubtractEquation, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, CullFaceNone, CullFaceBack, CullFaceFront, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, UnsignedInt101111Type, AlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, GreaterEqualCompare, EqualCompare, LessEqualCompare, AlwaysCompare, NeverCompare, LinearTransfer, getByteLength, TimestampQuery, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExternalTexture, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, Timer, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } 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<Object>} 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. }
  476. for ( const { property, childNode } of getNodeChildren( object ) ) {
  477. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  478. }
  479. return cyrb53( values );
  480. }
  481. /**
  482. * This generator function can be used to iterate over the node children
  483. * of the given object.
  484. *
  485. * @generator
  486. * @param {Object} node - The object to be hashed.
  487. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  488. * @yields {Object} A result node holding the property, index (if available) and the child node.
  489. */
  490. function* getNodeChildren( node, toJSON = false ) {
  491. for ( const property of Object.getOwnPropertyNames( node ) ) {
  492. // Ignore private properties.
  493. if ( property.startsWith( '_' ) === true ) continue;
  494. const object = node[ property ];
  495. if ( Array.isArray( object ) === true ) {
  496. for ( let i = 0; i < object.length; i ++ ) {
  497. const child = object[ i ];
  498. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  499. yield { property, index: i, childNode: child };
  500. }
  501. }
  502. } else if ( object && object.isNode === true ) {
  503. yield { property, childNode: object };
  504. } else if ( object && Object.getPrototypeOf( object ) === Object.prototype ) {
  505. for ( const subProperty in object ) {
  506. // Ignore private properties.
  507. if ( subProperty.startsWith( '_' ) === true ) continue;
  508. const child = object[ subProperty ];
  509. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  510. yield { property, index: subProperty, childNode: child };
  511. }
  512. }
  513. }
  514. }
  515. }
  516. const typeFromLength = /*@__PURE__*/ new Map( [
  517. [ 1, 'float' ],
  518. [ 2, 'vec2' ],
  519. [ 3, 'vec3' ],
  520. [ 4, 'vec4' ],
  521. [ 9, 'mat3' ],
  522. [ 16, 'mat4' ]
  523. ] );
  524. const dataFromObject = /*@__PURE__*/ new WeakMap();
  525. /**
  526. * Returns the data type for the given the length.
  527. *
  528. * @method
  529. * @param {number} length - The length.
  530. * @return {string} The data type.
  531. */
  532. function getTypeFromLength( length ) {
  533. return typeFromLength.get( length );
  534. }
  535. /**
  536. * Returns the typed array for the given data type.
  537. *
  538. * @method
  539. * @param {string} type - The data type.
  540. * @return {TypedArray} The typed array.
  541. */
  542. function getTypedArrayFromType( type ) {
  543. // Handle component type for vectors and matrices
  544. if ( /[iu]?vec\d/.test( type ) ) {
  545. // Handle int vectors
  546. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  547. // Handle uint vectors
  548. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  549. // Default to float vectors
  550. return Float32Array;
  551. }
  552. // Handle matrices (always float)
  553. if ( /mat\d/.test( type ) ) return Float32Array;
  554. // Basic types
  555. if ( /float/.test( type ) ) return Float32Array;
  556. if ( /uint/.test( type ) ) return Uint32Array;
  557. if ( /int/.test( type ) ) return Int32Array;
  558. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  559. }
  560. /**
  561. * Returns the length for the given data type.
  562. *
  563. * @method
  564. * @param {string} type - The data type.
  565. * @return {number} The length.
  566. */
  567. function getLengthFromType( type ) {
  568. if ( /float|int|uint/.test( type ) ) return 1;
  569. if ( /vec2/.test( type ) ) return 2;
  570. if ( /vec3/.test( type ) ) return 3;
  571. if ( /vec4/.test( type ) ) return 4;
  572. if ( /mat2/.test( type ) ) return 4;
  573. if ( /mat3/.test( type ) ) return 9;
  574. if ( /mat4/.test( type ) ) return 16;
  575. console.error( 'THREE.TSL: Unsupported type:', type );
  576. }
  577. /**
  578. * Returns the gpu memory length for the given data type.
  579. *
  580. * @method
  581. * @param {string} type - The data type.
  582. * @return {number} The length.
  583. */
  584. function getMemoryLengthFromType( type ) {
  585. if ( /float|int|uint/.test( type ) ) return 1;
  586. if ( /vec2/.test( type ) ) return 2;
  587. if ( /vec3/.test( type ) ) return 3;
  588. if ( /vec4/.test( type ) ) return 4;
  589. if ( /mat2/.test( type ) ) return 4;
  590. if ( /mat3/.test( type ) ) return 12;
  591. if ( /mat4/.test( type ) ) return 16;
  592. console.error( 'THREE.TSL: Unsupported type:', type );
  593. }
  594. /**
  595. * Returns the byte boundary for the given data type.
  596. *
  597. * @method
  598. * @param {string} type - The data type.
  599. * @return {number} The byte boundary.
  600. */
  601. function getByteBoundaryFromType( type ) {
  602. if ( /float|int|uint/.test( type ) ) return 4;
  603. if ( /vec2/.test( type ) ) return 8;
  604. if ( /vec3/.test( type ) ) return 16;
  605. if ( /vec4/.test( type ) ) return 16;
  606. if ( /mat2/.test( type ) ) return 8;
  607. if ( /mat3/.test( type ) ) return 48;
  608. if ( /mat4/.test( type ) ) return 64;
  609. console.error( 'THREE.TSL: Unsupported type:', type );
  610. }
  611. /**
  612. * Returns the data type for the given value.
  613. *
  614. * @method
  615. * @param {any} value - The value.
  616. * @return {?string} The data type.
  617. */
  618. function getValueType( value ) {
  619. if ( value === undefined || value === null ) return null;
  620. const typeOf = typeof value;
  621. if ( value.isNode === true ) {
  622. return 'node';
  623. } else if ( typeOf === 'number' ) {
  624. return 'float';
  625. } else if ( typeOf === 'boolean' ) {
  626. return 'bool';
  627. } else if ( typeOf === 'string' ) {
  628. return 'string';
  629. } else if ( typeOf === 'function' ) {
  630. return 'shader';
  631. } else if ( value.isVector2 === true ) {
  632. return 'vec2';
  633. } else if ( value.isVector3 === true ) {
  634. return 'vec3';
  635. } else if ( value.isVector4 === true ) {
  636. return 'vec4';
  637. } else if ( value.isMatrix2 === true ) {
  638. return 'mat2';
  639. } else if ( value.isMatrix3 === true ) {
  640. return 'mat3';
  641. } else if ( value.isMatrix4 === true ) {
  642. return 'mat4';
  643. } else if ( value.isColor === true ) {
  644. return 'color';
  645. } else if ( value instanceof ArrayBuffer ) {
  646. return 'ArrayBuffer';
  647. }
  648. return null;
  649. }
  650. /**
  651. * Returns the value/object for the given data type and parameters.
  652. *
  653. * @method
  654. * @param {string} type - The given type.
  655. * @param {...any} params - A parameter list.
  656. * @return {any} The value/object.
  657. */
  658. function getValueFromType( type, ...params ) {
  659. const last4 = type ? type.slice( -4 ) : undefined;
  660. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  661. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  662. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  663. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  664. }
  665. if ( type === 'color' ) {
  666. return new Color( ...params );
  667. } else if ( last4 === 'vec2' ) {
  668. return new Vector2( ...params );
  669. } else if ( last4 === 'vec3' ) {
  670. return new Vector3( ...params );
  671. } else if ( last4 === 'vec4' ) {
  672. return new Vector4( ...params );
  673. } else if ( last4 === 'mat2' ) {
  674. return new Matrix2( ...params );
  675. } else if ( last4 === 'mat3' ) {
  676. return new Matrix3( ...params );
  677. } else if ( last4 === 'mat4' ) {
  678. return new Matrix4( ...params );
  679. } else if ( type === 'bool' ) {
  680. return params[ 0 ] || false;
  681. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  682. return params[ 0 ] || 0;
  683. } else if ( type === 'string' ) {
  684. return params[ 0 ] || '';
  685. } else if ( type === 'ArrayBuffer' ) {
  686. return base64ToArrayBuffer( params[ 0 ] );
  687. }
  688. return null;
  689. }
  690. /**
  691. * Gets the object data that can be shared between different rendering steps.
  692. *
  693. * @param {Object} object - The object to get the data for.
  694. * @return {Object} The object data.
  695. */
  696. function getDataFromObject( object ) {
  697. let data = dataFromObject.get( object );
  698. if ( data === undefined ) {
  699. data = {};
  700. dataFromObject.set( object, data );
  701. }
  702. return data;
  703. }
  704. /**
  705. * Converts the given array buffer to a Base64 string.
  706. *
  707. * @method
  708. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  709. * @return {string} The Base64 string.
  710. */
  711. function arrayBufferToBase64( arrayBuffer ) {
  712. let chars = '';
  713. const array = new Uint8Array( arrayBuffer );
  714. for ( let i = 0; i < array.length; i ++ ) {
  715. chars += String.fromCharCode( array[ i ] );
  716. }
  717. return btoa( chars );
  718. }
  719. /**
  720. * Converts the given Base64 string to an array buffer.
  721. *
  722. * @method
  723. * @param {string} base64 - The Base64 string.
  724. * @return {ArrayBuffer} The array buffer.
  725. */
  726. function base64ToArrayBuffer( base64 ) {
  727. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  728. }
  729. var NodeUtils = /*#__PURE__*/Object.freeze({
  730. __proto__: null,
  731. arrayBufferToBase64: arrayBufferToBase64,
  732. base64ToArrayBuffer: base64ToArrayBuffer,
  733. getByteBoundaryFromType: getByteBoundaryFromType,
  734. getCacheKey: getCacheKey$1,
  735. getDataFromObject: getDataFromObject,
  736. getLengthFromType: getLengthFromType,
  737. getMemoryLengthFromType: getMemoryLengthFromType,
  738. getNodeChildren: getNodeChildren,
  739. getTypeFromLength: getTypeFromLength,
  740. getTypedArrayFromType: getTypedArrayFromType,
  741. getValueFromType: getValueFromType,
  742. getValueType: getValueType,
  743. hash: hash$1,
  744. hashArray: hashArray,
  745. hashString: hashString
  746. });
  747. /**
  748. * Possible shader stages.
  749. *
  750. * @property {string} VERTEX The vertex shader stage.
  751. * @property {string} FRAGMENT The fragment shader stage.
  752. */
  753. const NodeShaderStage = {
  754. VERTEX: 'vertex',
  755. FRAGMENT: 'fragment'
  756. };
  757. /**
  758. * Update types of a node.
  759. *
  760. * @property {string} NONE The update method is not executed.
  761. * @property {string} FRAME The update method is executed per frame.
  762. * @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.
  763. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  764. */
  765. const NodeUpdateType = {
  766. NONE: 'none',
  767. FRAME: 'frame',
  768. RENDER: 'render',
  769. OBJECT: 'object'
  770. };
  771. /**
  772. * Data types of a node.
  773. *
  774. * @property {string} BOOLEAN Boolean type.
  775. * @property {string} INTEGER Integer type.
  776. * @property {string} FLOAT Float type.
  777. * @property {string} VECTOR2 Two-dimensional vector type.
  778. * @property {string} VECTOR3 Three-dimensional vector type.
  779. * @property {string} VECTOR4 Four-dimensional vector type.
  780. * @property {string} MATRIX2 2x2 matrix type.
  781. * @property {string} MATRIX3 3x3 matrix type.
  782. * @property {string} MATRIX4 4x4 matrix type.
  783. */
  784. const NodeType = {
  785. BOOLEAN: 'bool',
  786. INTEGER: 'int',
  787. FLOAT: 'float',
  788. VECTOR2: 'vec2',
  789. VECTOR3: 'vec3',
  790. VECTOR4: 'vec4',
  791. MATRIX2: 'mat2',
  792. MATRIX3: 'mat3',
  793. MATRIX4: 'mat4'
  794. };
  795. /**
  796. * Access types of a node. These are relevant for compute and storage usage.
  797. *
  798. * @property {string} READ_ONLY Read-only access
  799. * @property {string} WRITE_ONLY Write-only access.
  800. * @property {string} READ_WRITE Read and write access.
  801. */
  802. const NodeAccess = {
  803. READ_ONLY: 'readOnly',
  804. WRITE_ONLY: 'writeOnly',
  805. READ_WRITE: 'readWrite',
  806. };
  807. const defaultShaderStages = [ 'fragment', 'vertex' ];
  808. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  809. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  810. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  811. const _parentBuildStage = {
  812. analyze: 'setup',
  813. generate: 'analyze'
  814. };
  815. let _nodeId = 0;
  816. /**
  817. * Base class for all nodes.
  818. *
  819. * @augments EventDispatcher
  820. */
  821. class Node extends EventDispatcher {
  822. static get type() {
  823. return 'Node';
  824. }
  825. /**
  826. * Constructs a new node.
  827. *
  828. * @param {?string} nodeType - The node type.
  829. */
  830. constructor( nodeType = null ) {
  831. super();
  832. /**
  833. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  834. *
  835. * @type {?string}
  836. * @default null
  837. */
  838. this.nodeType = nodeType;
  839. /**
  840. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  841. *
  842. * @type {string}
  843. * @default 'none'
  844. */
  845. this.updateType = NodeUpdateType.NONE;
  846. /**
  847. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  848. *
  849. * @type {string}
  850. * @default 'none'
  851. */
  852. this.updateBeforeType = NodeUpdateType.NONE;
  853. /**
  854. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  855. *
  856. * @type {string}
  857. * @default 'none'
  858. */
  859. this.updateAfterType = NodeUpdateType.NONE;
  860. /**
  861. * The UUID of the node.
  862. *
  863. * @type {string}
  864. * @readonly
  865. */
  866. this.uuid = MathUtils.generateUUID();
  867. /**
  868. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  869. *
  870. * @type {number}
  871. * @readonly
  872. * @default 0
  873. */
  874. this.version = 0;
  875. /**
  876. * Whether this node is global or not. This property is relevant for the internal
  877. * node caching system. All nodes which should be declared just once should
  878. * set this flag to `true` (a typical example is {@link AttributeNode}).
  879. *
  880. * @type {boolean}
  881. * @default false
  882. */
  883. this.global = false;
  884. /**
  885. * Create a list of parents for this node during the build process.
  886. *
  887. * @type {boolean}
  888. * @default false
  889. */
  890. this.parents = false;
  891. /**
  892. * This flag can be used for type testing.
  893. *
  894. * @type {boolean}
  895. * @readonly
  896. * @default true
  897. */
  898. this.isNode = true;
  899. // private
  900. /**
  901. * The cache key of this node.
  902. *
  903. * @private
  904. * @type {?number}
  905. * @default null
  906. */
  907. this._cacheKey = null;
  908. /**
  909. * The cache key 's version.
  910. *
  911. * @private
  912. * @type {number}
  913. * @default 0
  914. */
  915. this._cacheKeyVersion = 0;
  916. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  917. }
  918. /**
  919. * Set this property to `true` when the node should be regenerated.
  920. *
  921. * @type {boolean}
  922. * @default false
  923. * @param {boolean} value
  924. */
  925. set needsUpdate( value ) {
  926. if ( value === true ) {
  927. this.version ++;
  928. }
  929. }
  930. /**
  931. * The type of the class. The value is usually the constructor name.
  932. *
  933. * @type {string}
  934. * @readonly
  935. */
  936. get type() {
  937. return this.constructor.type;
  938. }
  939. /**
  940. * Convenient method for defining {@link Node#update}.
  941. *
  942. * @param {Function} callback - The update method.
  943. * @param {string} updateType - The update type.
  944. * @return {Node} A reference to this node.
  945. */
  946. onUpdate( callback, updateType ) {
  947. this.updateType = updateType;
  948. this.update = callback.bind( this );
  949. return this;
  950. }
  951. /**
  952. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  953. * this method automatically sets the update type to `FRAME`.
  954. *
  955. * @param {Function} callback - The update method.
  956. * @return {Node} A reference to this node.
  957. */
  958. onFrameUpdate( callback ) {
  959. return this.onUpdate( callback, NodeUpdateType.FRAME );
  960. }
  961. /**
  962. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  963. * this method automatically sets the update type to `RENDER`.
  964. *
  965. * @param {Function} callback - The update method.
  966. * @return {Node} A reference to this node.
  967. */
  968. onRenderUpdate( callback ) {
  969. return this.onUpdate( callback, NodeUpdateType.RENDER );
  970. }
  971. /**
  972. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  973. * this method automatically sets the update type to `OBJECT`.
  974. *
  975. * @param {Function} callback - The update method.
  976. * @return {Node} A reference to this node.
  977. */
  978. onObjectUpdate( callback ) {
  979. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  980. }
  981. /**
  982. * Convenient method for defining {@link Node#updateReference}.
  983. *
  984. * @param {Function} callback - The update method.
  985. * @return {Node} A reference to this node.
  986. */
  987. onReference( callback ) {
  988. this.updateReference = callback.bind( this );
  989. return this;
  990. }
  991. /**
  992. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  993. * to such objects based on a given state (e.g. the current node frame or builder).
  994. *
  995. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  996. * @return {any} The updated reference.
  997. */
  998. updateReference( /*state*/ ) {
  999. return this;
  1000. }
  1001. /**
  1002. * By default this method returns the value of the {@link Node#global} flag. This method
  1003. * can be overwritten in derived classes if an analytical way is required to determine the
  1004. * global cache referring to the current shader-stage.
  1005. *
  1006. * @param {NodeBuilder} builder - The current node builder.
  1007. * @return {boolean} Whether this node is global or not.
  1008. */
  1009. isGlobal( /*builder*/ ) {
  1010. return this.global;
  1011. }
  1012. /**
  1013. * Generator function that can be used to iterate over the child nodes.
  1014. *
  1015. * @generator
  1016. * @yields {Node} A child node.
  1017. */
  1018. * getChildren() {
  1019. for ( const { childNode } of getNodeChildren( this ) ) {
  1020. yield childNode;
  1021. }
  1022. }
  1023. /**
  1024. * Calling this method dispatches the `dispose` event. This event can be used
  1025. * to register event listeners for clean up tasks.
  1026. */
  1027. dispose() {
  1028. this.dispatchEvent( { type: 'dispose' } );
  1029. }
  1030. /**
  1031. * Callback for {@link Node#traverse}.
  1032. *
  1033. * @callback traverseCallback
  1034. * @param {Node} node - The current node.
  1035. */
  1036. /**
  1037. * Can be used to traverse through the node's hierarchy.
  1038. *
  1039. * @param {traverseCallback} callback - A callback that is executed per node.
  1040. */
  1041. traverse( callback ) {
  1042. callback( this );
  1043. for ( const childNode of this.getChildren() ) {
  1044. childNode.traverse( callback );
  1045. }
  1046. }
  1047. /**
  1048. * Returns the cache key for this node.
  1049. *
  1050. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1051. * @return {number} The cache key of the node.
  1052. */
  1053. getCacheKey( force = false ) {
  1054. force = force || this.version !== this._cacheKeyVersion;
  1055. if ( force === true || this._cacheKey === null ) {
  1056. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  1057. this._cacheKeyVersion = this.version;
  1058. }
  1059. return this._cacheKey;
  1060. }
  1061. /**
  1062. * Generate a custom cache key for this node.
  1063. *
  1064. * @return {number} The cache key of the node.
  1065. */
  1066. customCacheKey() {
  1067. return 0;
  1068. }
  1069. /**
  1070. * Returns the references to this node which is by default `this`.
  1071. *
  1072. * @return {Node} A reference to this node.
  1073. */
  1074. getScope() {
  1075. return this;
  1076. }
  1077. /**
  1078. * Returns the hash of the node which is used to identify the node. By default it's
  1079. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1080. * depending on their implementation.
  1081. *
  1082. * @param {NodeBuilder} builder - The current node builder.
  1083. * @return {string} The hash.
  1084. */
  1085. getHash( /*builder*/ ) {
  1086. return this.uuid;
  1087. }
  1088. /**
  1089. * Returns the update type of {@link Node#update}.
  1090. *
  1091. * @return {NodeUpdateType} The update type.
  1092. */
  1093. getUpdateType() {
  1094. return this.updateType;
  1095. }
  1096. /**
  1097. * Returns the update type of {@link Node#updateBefore}.
  1098. *
  1099. * @return {NodeUpdateType} The update type.
  1100. */
  1101. getUpdateBeforeType() {
  1102. return this.updateBeforeType;
  1103. }
  1104. /**
  1105. * Returns the update type of {@link Node#updateAfter}.
  1106. *
  1107. * @return {NodeUpdateType} The update type.
  1108. */
  1109. getUpdateAfterType() {
  1110. return this.updateAfterType;
  1111. }
  1112. /**
  1113. * Certain types are composed of multiple elements. For example a `vec3`
  1114. * is composed of three `float` values. This method returns the type of
  1115. * these elements.
  1116. *
  1117. * @param {NodeBuilder} builder - The current node builder.
  1118. * @return {string} The type of the node.
  1119. */
  1120. getElementType( builder ) {
  1121. const type = this.getNodeType( builder );
  1122. const elementType = builder.getElementType( type );
  1123. return elementType;
  1124. }
  1125. /**
  1126. * Returns the node member type for the given name.
  1127. *
  1128. * @param {NodeBuilder} builder - The current node builder.
  1129. * @param {string} name - The name of the member.
  1130. * @return {string} The type of the node.
  1131. */
  1132. getMemberType( /*builder, name*/ ) {
  1133. return 'void';
  1134. }
  1135. /**
  1136. * Returns the node's type.
  1137. *
  1138. * @param {NodeBuilder} builder - The current node builder.
  1139. * @return {string} The type of the node.
  1140. */
  1141. getNodeType( builder ) {
  1142. const nodeProperties = builder.getNodeProperties( this );
  1143. if ( nodeProperties.outputNode ) {
  1144. return nodeProperties.outputNode.getNodeType( builder );
  1145. }
  1146. return this.nodeType;
  1147. }
  1148. /**
  1149. * This method is used during the build process of a node and ensures
  1150. * equal nodes are not built multiple times but just once. For example if
  1151. * `attribute( 'uv' )` is used multiple times by the user, the build
  1152. * process makes sure to process just the first node.
  1153. *
  1154. * @param {NodeBuilder} builder - The current node builder.
  1155. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1156. */
  1157. getShared( builder ) {
  1158. const hash = this.getHash( builder );
  1159. const nodeFromHash = builder.getNodeFromHash( hash );
  1160. return nodeFromHash || this;
  1161. }
  1162. /**
  1163. * Returns the number of elements in the node array.
  1164. *
  1165. * @param {NodeBuilder} builder - The current node builder.
  1166. * @return {?number} The number of elements in the node array.
  1167. */
  1168. getArrayCount( /*builder*/ ) {
  1169. return null;
  1170. }
  1171. /**
  1172. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1173. * This method is often overwritten in derived modules to prepare the node which is used as a node's output/result.
  1174. * If an output node is prepared, then it must be returned in the `return` statement of the derived module's setup function.
  1175. *
  1176. * @param {NodeBuilder} builder - The current node builder.
  1177. * @return {?Node} The output node.
  1178. */
  1179. setup( builder ) {
  1180. const nodeProperties = builder.getNodeProperties( this );
  1181. let index = 0;
  1182. for ( const childNode of this.getChildren() ) {
  1183. nodeProperties[ 'node' + index ++ ] = childNode;
  1184. }
  1185. // return a outputNode if exists or null
  1186. return nodeProperties.outputNode || null;
  1187. }
  1188. /**
  1189. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1190. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1191. *
  1192. * @param {NodeBuilder} builder - The current node builder.
  1193. * @param {?Node} output - The target output node.
  1194. */
  1195. analyze( builder, output = null ) {
  1196. const usageCount = builder.increaseUsage( this );
  1197. if ( this.parents === true ) {
  1198. const nodeData = builder.getDataFromNode( this, 'any' );
  1199. nodeData.stages = nodeData.stages || {};
  1200. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1201. nodeData.stages[ builder.shaderStage ].push( output );
  1202. }
  1203. if ( usageCount === 1 ) {
  1204. // node flow children
  1205. const nodeProperties = builder.getNodeProperties( this );
  1206. for ( const childNode of Object.values( nodeProperties ) ) {
  1207. if ( childNode && childNode.isNode === true ) {
  1208. childNode.build( builder, this );
  1209. }
  1210. }
  1211. }
  1212. }
  1213. /**
  1214. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1215. * This state builds the output node and returns the resulting shader string.
  1216. *
  1217. * @param {NodeBuilder} builder - The current node builder.
  1218. * @param {?string} [output] - Can be used to define the output type.
  1219. * @return {?string} The generated shader string.
  1220. */
  1221. generate( builder, output ) {
  1222. const { outputNode } = builder.getNodeProperties( this );
  1223. if ( outputNode && outputNode.isNode === true ) {
  1224. return outputNode.build( builder, output );
  1225. }
  1226. }
  1227. /**
  1228. * The method can be implemented to update the node's internal state before it is used to render an object.
  1229. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1230. *
  1231. * @abstract
  1232. * @param {NodeFrame} frame - A reference to the current node frame.
  1233. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1234. */
  1235. updateBefore( /*frame*/ ) {
  1236. console.warn( 'Abstract function.' );
  1237. }
  1238. /**
  1239. * The method can be implemented to update the node's internal state after it was used to render an object.
  1240. * The {@link Node#updateAfterType} 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. updateAfter( /*frame*/ ) {
  1247. console.warn( 'Abstract function.' );
  1248. }
  1249. /**
  1250. * The method can be implemented to update the node's internal state when it is used to render an object.
  1251. * The {@link Node#updateType} 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. update( /*frame*/ ) {
  1258. console.warn( 'Abstract function.' );
  1259. }
  1260. /**
  1261. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1262. * - **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.
  1263. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1264. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1265. *
  1266. * @param {NodeBuilder} builder - The current node builder.
  1267. * @param {?(string|Node)} [output=null] - Can be used to define the output type.
  1268. * @return {?(Node|string)} The result of the build process, depending on the build stage.
  1269. */
  1270. build( builder, output = null ) {
  1271. const refNode = this.getShared( builder );
  1272. if ( this !== refNode ) {
  1273. return refNode.build( builder, output );
  1274. }
  1275. //
  1276. const nodeData = builder.getDataFromNode( this );
  1277. nodeData.buildStages = nodeData.buildStages || {};
  1278. nodeData.buildStages[ builder.buildStage ] = true;
  1279. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1280. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1281. // force parent build stage (setup or analyze)
  1282. const previousBuildStage = builder.getBuildStage();
  1283. builder.setBuildStage( parentBuildStage );
  1284. this.build( builder );
  1285. builder.setBuildStage( previousBuildStage );
  1286. }
  1287. //
  1288. builder.addNode( this );
  1289. builder.addChain( this );
  1290. /* Build stages expected results:
  1291. - "setup" -> Node
  1292. - "analyze" -> null
  1293. - "generate" -> String
  1294. */
  1295. let result = null;
  1296. const buildStage = builder.getBuildStage();
  1297. if ( buildStage === 'setup' ) {
  1298. this.updateReference( builder );
  1299. const properties = builder.getNodeProperties( this );
  1300. if ( properties.initialized !== true ) {
  1301. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1302. properties.initialized = true;
  1303. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1304. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1305. // !! no outputNode !!
  1306. //outputNode = builder.stack;
  1307. }*/
  1308. for ( const childNode of Object.values( properties ) ) {
  1309. if ( childNode && childNode.isNode === true ) {
  1310. if ( childNode.parents === true ) {
  1311. const childProperties = builder.getNodeProperties( childNode );
  1312. childProperties.parents = childProperties.parents || [];
  1313. childProperties.parents.push( this );
  1314. }
  1315. childNode.build( builder );
  1316. }
  1317. }
  1318. }
  1319. result = properties.outputNode;
  1320. } else if ( buildStage === 'analyze' ) {
  1321. this.analyze( builder, output );
  1322. } else if ( buildStage === 'generate' ) {
  1323. const isGenerateOnce = this.generate.length === 1;
  1324. if ( isGenerateOnce ) {
  1325. const type = this.getNodeType( builder );
  1326. const nodeData = builder.getDataFromNode( this );
  1327. result = nodeData.snippet;
  1328. if ( result === undefined ) {
  1329. if ( nodeData.generated === undefined ) {
  1330. nodeData.generated = true;
  1331. result = this.generate( builder ) || '';
  1332. nodeData.snippet = result;
  1333. } else {
  1334. console.warn( 'THREE.Node: Recursion detected.', this );
  1335. result = '/* Recursion detected. */';
  1336. }
  1337. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1338. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1339. }
  1340. result = builder.format( result, type, output );
  1341. } else {
  1342. result = this.generate( builder, output ) || '';
  1343. }
  1344. if ( result === '' && output !== null && output !== 'void' && output !== 'OutputType' ) {
  1345. // if no snippet is generated, return a default value
  1346. console.error( `THREE.TSL: Invalid generated code, expected a "${ output }".` );
  1347. result = builder.generateConst( output );
  1348. }
  1349. }
  1350. builder.removeChain( this );
  1351. builder.addSequentialNode( this );
  1352. return result;
  1353. }
  1354. /**
  1355. * Returns the child nodes as a JSON object.
  1356. *
  1357. * @return {Generator<Object>} An iterable list of serialized child objects as JSON.
  1358. */
  1359. getSerializeChildren() {
  1360. return getNodeChildren( this );
  1361. }
  1362. /**
  1363. * Serializes the node to JSON.
  1364. *
  1365. * @param {Object} json - The output JSON object.
  1366. */
  1367. serialize( json ) {
  1368. const nodeChildren = this.getSerializeChildren();
  1369. const inputNodes = {};
  1370. for ( const { property, index, childNode } of nodeChildren ) {
  1371. if ( index !== undefined ) {
  1372. if ( inputNodes[ property ] === undefined ) {
  1373. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1374. }
  1375. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1376. } else {
  1377. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1378. }
  1379. }
  1380. if ( Object.keys( inputNodes ).length > 0 ) {
  1381. json.inputNodes = inputNodes;
  1382. }
  1383. }
  1384. /**
  1385. * Deserializes the node from the given JSON.
  1386. *
  1387. * @param {Object} json - The JSON object.
  1388. */
  1389. deserialize( json ) {
  1390. if ( json.inputNodes !== undefined ) {
  1391. const nodes = json.meta.nodes;
  1392. for ( const property in json.inputNodes ) {
  1393. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1394. const inputArray = [];
  1395. for ( const uuid of json.inputNodes[ property ] ) {
  1396. inputArray.push( nodes[ uuid ] );
  1397. }
  1398. this[ property ] = inputArray;
  1399. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1400. const inputObject = {};
  1401. for ( const subProperty in json.inputNodes[ property ] ) {
  1402. const uuid = json.inputNodes[ property ][ subProperty ];
  1403. inputObject[ subProperty ] = nodes[ uuid ];
  1404. }
  1405. this[ property ] = inputObject;
  1406. } else {
  1407. const uuid = json.inputNodes[ property ];
  1408. this[ property ] = nodes[ uuid ];
  1409. }
  1410. }
  1411. }
  1412. }
  1413. /**
  1414. * Serializes the node into the three.js JSON Object/Scene format.
  1415. *
  1416. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1417. * @return {Object} The serialized node.
  1418. */
  1419. toJSON( meta ) {
  1420. const { uuid, type } = this;
  1421. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1422. if ( isRoot ) {
  1423. meta = {
  1424. textures: {},
  1425. images: {},
  1426. nodes: {}
  1427. };
  1428. }
  1429. // serialize
  1430. let data = meta.nodes[ uuid ];
  1431. if ( data === undefined ) {
  1432. data = {
  1433. uuid,
  1434. type,
  1435. meta,
  1436. metadata: {
  1437. version: 4.7,
  1438. type: 'Node',
  1439. generator: 'Node.toJSON'
  1440. }
  1441. };
  1442. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1443. this.serialize( data );
  1444. delete data.meta;
  1445. }
  1446. // TODO: Copied from Object3D.toJSON
  1447. function extractFromCache( cache ) {
  1448. const values = [];
  1449. for ( const key in cache ) {
  1450. const data = cache[ key ];
  1451. delete data.metadata;
  1452. values.push( data );
  1453. }
  1454. return values;
  1455. }
  1456. if ( isRoot ) {
  1457. const textures = extractFromCache( meta.textures );
  1458. const images = extractFromCache( meta.images );
  1459. const nodes = extractFromCache( meta.nodes );
  1460. if ( textures.length > 0 ) data.textures = textures;
  1461. if ( images.length > 0 ) data.images = images;
  1462. if ( nodes.length > 0 ) data.nodes = nodes;
  1463. }
  1464. return data;
  1465. }
  1466. }
  1467. /**
  1468. * Base class for representing element access on an array-like
  1469. * node data structures.
  1470. *
  1471. * @augments Node
  1472. */
  1473. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1474. static get type() {
  1475. return 'ArrayElementNode';
  1476. }
  1477. /**
  1478. * Constructs an array element node.
  1479. *
  1480. * @param {Node} node - The array-like node.
  1481. * @param {Node} indexNode - The index node that defines the element access.
  1482. */
  1483. constructor( node, indexNode ) {
  1484. super();
  1485. /**
  1486. * The array-like node.
  1487. *
  1488. * @type {Node}
  1489. */
  1490. this.node = node;
  1491. /**
  1492. * The index node that defines the element access.
  1493. *
  1494. * @type {Node}
  1495. */
  1496. this.indexNode = indexNode;
  1497. /**
  1498. * This flag can be used for type testing.
  1499. *
  1500. * @type {boolean}
  1501. * @readonly
  1502. * @default true
  1503. */
  1504. this.isArrayElementNode = true;
  1505. }
  1506. /**
  1507. * This method is overwritten since the node type is inferred from the array-like node.
  1508. *
  1509. * @param {NodeBuilder} builder - The current node builder.
  1510. * @return {string} The node type.
  1511. */
  1512. getNodeType( builder ) {
  1513. return this.node.getElementType( builder );
  1514. }
  1515. generate( builder ) {
  1516. const indexType = this.indexNode.getNodeType( builder );
  1517. const nodeSnippet = this.node.build( builder );
  1518. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1519. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1520. }
  1521. }
  1522. /**
  1523. * This module is part of the TSL core and usually not used in app level code.
  1524. * It represents a convert operation during the shader generation process
  1525. * meaning it converts the data type of a node to a target data type.
  1526. *
  1527. * @augments Node
  1528. */
  1529. class ConvertNode extends Node {
  1530. static get type() {
  1531. return 'ConvertNode';
  1532. }
  1533. /**
  1534. * Constructs a new convert node.
  1535. *
  1536. * @param {Node} node - The node which type should be converted.
  1537. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1538. */
  1539. constructor( node, convertTo ) {
  1540. super();
  1541. /**
  1542. * The node which type should be converted.
  1543. *
  1544. * @type {Node}
  1545. */
  1546. this.node = node;
  1547. /**
  1548. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1549. *
  1550. * @type {string}
  1551. */
  1552. this.convertTo = convertTo;
  1553. }
  1554. /**
  1555. * This method is overwritten since the implementation tries to infer the best
  1556. * matching type from the {@link ConvertNode#convertTo} property.
  1557. *
  1558. * @param {NodeBuilder} builder - The current node builder.
  1559. * @return {string} The node type.
  1560. */
  1561. getNodeType( builder ) {
  1562. const requestType = this.node.getNodeType( builder );
  1563. let convertTo = null;
  1564. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1565. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1566. convertTo = overloadingType;
  1567. }
  1568. }
  1569. return convertTo;
  1570. }
  1571. serialize( data ) {
  1572. super.serialize( data );
  1573. data.convertTo = this.convertTo;
  1574. }
  1575. deserialize( data ) {
  1576. super.deserialize( data );
  1577. this.convertTo = data.convertTo;
  1578. }
  1579. generate( builder, output ) {
  1580. const node = this.node;
  1581. const type = this.getNodeType( builder );
  1582. const snippet = node.build( builder, type );
  1583. return builder.format( snippet, type, output );
  1584. }
  1585. }
  1586. /**
  1587. * This module uses cache management to create temporary variables
  1588. * if the node is used more than once to prevent duplicate calculations.
  1589. *
  1590. * The class acts as a base class for many other nodes types.
  1591. *
  1592. * @augments Node
  1593. */
  1594. class TempNode extends Node {
  1595. static get type() {
  1596. return 'TempNode';
  1597. }
  1598. /**
  1599. * Constructs a temp node.
  1600. *
  1601. * @param {?string} nodeType - The node type.
  1602. */
  1603. constructor( nodeType = null ) {
  1604. super( nodeType );
  1605. /**
  1606. * This flag can be used for type testing.
  1607. *
  1608. * @type {boolean}
  1609. * @readonly
  1610. * @default true
  1611. */
  1612. this.isTempNode = true;
  1613. }
  1614. /**
  1615. * Whether this node is used more than once in context of other nodes.
  1616. *
  1617. * @param {NodeBuilder} builder - The node builder.
  1618. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1619. */
  1620. hasDependencies( builder ) {
  1621. return builder.getDataFromNode( this ).usageCount > 1;
  1622. }
  1623. build( builder, output ) {
  1624. const buildStage = builder.getBuildStage();
  1625. if ( buildStage === 'generate' ) {
  1626. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1627. const nodeData = builder.getDataFromNode( this );
  1628. if ( nodeData.propertyName !== undefined ) {
  1629. return builder.format( nodeData.propertyName, type, output );
  1630. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1631. const snippet = super.build( builder, type );
  1632. const nodeVar = builder.getVarFromNode( this, null, type );
  1633. const propertyName = builder.getPropertyName( nodeVar );
  1634. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1635. nodeData.snippet = snippet;
  1636. nodeData.propertyName = propertyName;
  1637. return builder.format( nodeData.propertyName, type, output );
  1638. }
  1639. }
  1640. return super.build( builder, output );
  1641. }
  1642. }
  1643. /**
  1644. * This module is part of the TSL core and usually not used in app level code.
  1645. * It represents a join operation during the shader generation process.
  1646. * For example in can compose/join two single floats into a `vec2` type.
  1647. *
  1648. * @augments TempNode
  1649. */
  1650. class JoinNode extends TempNode {
  1651. static get type() {
  1652. return 'JoinNode';
  1653. }
  1654. /**
  1655. * Constructs a new join node.
  1656. *
  1657. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1658. * @param {?string} [nodeType=null] - The node type.
  1659. */
  1660. constructor( nodes = [], nodeType = null ) {
  1661. super( nodeType );
  1662. /**
  1663. * An array of nodes that should be joined.
  1664. *
  1665. * @type {Array<Node>}
  1666. */
  1667. this.nodes = nodes;
  1668. }
  1669. /**
  1670. * This method is overwritten since the node type must be inferred from the
  1671. * joined data length if not explicitly defined.
  1672. *
  1673. * @param {NodeBuilder} builder - The current node builder.
  1674. * @return {string} The node type.
  1675. */
  1676. getNodeType( builder ) {
  1677. if ( this.nodeType !== null ) {
  1678. return builder.getVectorType( this.nodeType );
  1679. }
  1680. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1681. }
  1682. generate( builder, output ) {
  1683. const type = this.getNodeType( builder );
  1684. const maxLength = builder.getTypeLength( type );
  1685. const nodes = this.nodes;
  1686. const primitiveType = builder.getComponentType( type );
  1687. const snippetValues = [];
  1688. let length = 0;
  1689. for ( const input of nodes ) {
  1690. if ( length >= maxLength ) {
  1691. console.error( `THREE.TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1692. break;
  1693. }
  1694. let inputType = input.getNodeType( builder );
  1695. let inputTypeLength = builder.getTypeLength( inputType );
  1696. let inputSnippet;
  1697. if ( length + inputTypeLength > maxLength ) {
  1698. console.error( `THREE.TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1699. inputTypeLength = maxLength - length;
  1700. inputType = builder.getTypeFromLength( inputTypeLength );
  1701. }
  1702. length += inputTypeLength;
  1703. inputSnippet = input.build( builder, inputType );
  1704. const inputPrimitiveType = builder.getComponentType( inputType );
  1705. if ( inputPrimitiveType !== primitiveType ) {
  1706. const targetType = builder.getTypeFromLength( inputTypeLength, primitiveType );
  1707. inputSnippet = builder.format( inputSnippet, inputType, targetType );
  1708. }
  1709. snippetValues.push( inputSnippet );
  1710. }
  1711. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1712. return builder.format( snippet, type, output );
  1713. }
  1714. }
  1715. const _stringVectorComponents = vectorComponents.join( '' );
  1716. /**
  1717. * This module is part of the TSL core and usually not used in app level code.
  1718. * `SplitNode` represents a property access operation which means it is
  1719. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1720. * For example:
  1721. * ```js
  1722. * const redValue = color.r;
  1723. * ```
  1724. *
  1725. * @augments Node
  1726. */
  1727. class SplitNode extends Node {
  1728. static get type() {
  1729. return 'SplitNode';
  1730. }
  1731. /**
  1732. * Constructs a new split node.
  1733. *
  1734. * @param {Node} node - The node that should be accessed.
  1735. * @param {string} [components='x'] - The components that should be accessed.
  1736. */
  1737. constructor( node, components = 'x' ) {
  1738. super();
  1739. /**
  1740. * The node that should be accessed.
  1741. *
  1742. * @type {Node}
  1743. */
  1744. this.node = node;
  1745. /**
  1746. * The components that should be accessed.
  1747. *
  1748. * @type {string}
  1749. */
  1750. this.components = components;
  1751. /**
  1752. * This flag can be used for type testing.
  1753. *
  1754. * @type {boolean}
  1755. * @readonly
  1756. * @default true
  1757. */
  1758. this.isSplitNode = true;
  1759. }
  1760. /**
  1761. * Returns the vector length which is computed based on the requested components.
  1762. *
  1763. * @return {number} The vector length.
  1764. */
  1765. getVectorLength() {
  1766. let vectorLength = this.components.length;
  1767. for ( const c of this.components ) {
  1768. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1769. }
  1770. return vectorLength;
  1771. }
  1772. /**
  1773. * Returns the component type of the node's type.
  1774. *
  1775. * @param {NodeBuilder} builder - The current node builder.
  1776. * @return {string} The component type.
  1777. */
  1778. getComponentType( builder ) {
  1779. return builder.getComponentType( this.node.getNodeType( builder ) );
  1780. }
  1781. /**
  1782. * This method is overwritten since the node type is inferred from requested components.
  1783. *
  1784. * @param {NodeBuilder} builder - The current node builder.
  1785. * @return {string} The node type.
  1786. */
  1787. getNodeType( builder ) {
  1788. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1789. }
  1790. /**
  1791. * Returns the scope of the node.
  1792. *
  1793. * @return {Node} The scope of the node.
  1794. */
  1795. getScope() {
  1796. return this.node.getScope();
  1797. }
  1798. generate( builder, output ) {
  1799. const node = this.node;
  1800. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1801. let snippet = null;
  1802. if ( nodeTypeLength > 1 ) {
  1803. let type = null;
  1804. const componentsLength = this.getVectorLength();
  1805. if ( componentsLength >= nodeTypeLength ) {
  1806. // needed expand the input node
  1807. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1808. }
  1809. const nodeSnippet = node.build( builder, type );
  1810. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1811. // unnecessary swizzle
  1812. snippet = builder.format( nodeSnippet, type, output );
  1813. } else {
  1814. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1815. }
  1816. } else {
  1817. // ignore .components if .node returns float/integer
  1818. snippet = node.build( builder, output );
  1819. }
  1820. return snippet;
  1821. }
  1822. serialize( data ) {
  1823. super.serialize( data );
  1824. data.components = this.components;
  1825. }
  1826. deserialize( data ) {
  1827. super.deserialize( data );
  1828. this.components = data.components;
  1829. }
  1830. }
  1831. /**
  1832. * This module is part of the TSL core and usually not used in app level code.
  1833. * `SetNode` represents a set operation which means it is used to implement any
  1834. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1835. * For example:
  1836. * ```js
  1837. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1838. * ```
  1839. *
  1840. * @augments TempNode
  1841. */
  1842. class SetNode extends TempNode {
  1843. static get type() {
  1844. return 'SetNode';
  1845. }
  1846. /**
  1847. * Constructs a new set node.
  1848. *
  1849. * @param {Node} sourceNode - The node that should be updated.
  1850. * @param {string} components - The components that should be updated.
  1851. * @param {Node} targetNode - The value node.
  1852. */
  1853. constructor( sourceNode, components, targetNode ) {
  1854. super();
  1855. /**
  1856. * The node that should be updated.
  1857. *
  1858. * @type {Node}
  1859. */
  1860. this.sourceNode = sourceNode;
  1861. /**
  1862. * The components that should be updated.
  1863. *
  1864. * @type {string}
  1865. */
  1866. this.components = components;
  1867. /**
  1868. * The value node.
  1869. *
  1870. * @type {Node}
  1871. */
  1872. this.targetNode = targetNode;
  1873. }
  1874. /**
  1875. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1876. *
  1877. * @param {NodeBuilder} builder - The current node builder.
  1878. * @return {string} The node type.
  1879. */
  1880. getNodeType( builder ) {
  1881. return this.sourceNode.getNodeType( builder );
  1882. }
  1883. generate( builder ) {
  1884. const { sourceNode, components, targetNode } = this;
  1885. const sourceType = this.getNodeType( builder );
  1886. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1887. const targetType = builder.getTypeFromLength( components.length, componentType );
  1888. const targetSnippet = targetNode.build( builder, targetType );
  1889. const sourceSnippet = sourceNode.build( builder, sourceType );
  1890. const length = builder.getTypeLength( sourceType );
  1891. const snippetValues = [];
  1892. for ( let i = 0; i < length; i ++ ) {
  1893. const component = vectorComponents[ i ];
  1894. if ( component === components[ 0 ] ) {
  1895. snippetValues.push( targetSnippet );
  1896. i += components.length - 1;
  1897. } else {
  1898. snippetValues.push( sourceSnippet + '.' + component );
  1899. }
  1900. }
  1901. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1902. }
  1903. }
  1904. /**
  1905. * This module is part of the TSL core and usually not used in app level code.
  1906. * It represents a flip operation during the shader generation process
  1907. * meaning it flips normalized values with the following formula:
  1908. * ```
  1909. * x = 1 - x;
  1910. * ```
  1911. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1912. * `flipSTPQ()` method invocations on node objects. For example:
  1913. * ```js
  1914. * uvNode = uvNode.flipY();
  1915. * ```
  1916. *
  1917. * @augments TempNode
  1918. */
  1919. class FlipNode extends TempNode {
  1920. static get type() {
  1921. return 'FlipNode';
  1922. }
  1923. /**
  1924. * Constructs a new flip node.
  1925. *
  1926. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1927. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1928. */
  1929. constructor( sourceNode, components ) {
  1930. super();
  1931. /**
  1932. * The node which component(s) should be flipped.
  1933. *
  1934. * @type {Node}
  1935. */
  1936. this.sourceNode = sourceNode;
  1937. /**
  1938. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1939. *
  1940. * @type {string}
  1941. */
  1942. this.components = components;
  1943. }
  1944. /**
  1945. * This method is overwritten since the node type is inferred from the source node.
  1946. *
  1947. * @param {NodeBuilder} builder - The current node builder.
  1948. * @return {string} The node type.
  1949. */
  1950. getNodeType( builder ) {
  1951. return this.sourceNode.getNodeType( builder );
  1952. }
  1953. generate( builder ) {
  1954. const { components, sourceNode } = this;
  1955. const sourceType = this.getNodeType( builder );
  1956. const sourceSnippet = sourceNode.build( builder );
  1957. const sourceCache = builder.getVarFromNode( this );
  1958. const sourceProperty = builder.getPropertyName( sourceCache );
  1959. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1960. const length = builder.getTypeLength( sourceType );
  1961. const snippetValues = [];
  1962. let componentIndex = 0;
  1963. for ( let i = 0; i < length; i ++ ) {
  1964. const component = vectorComponents[ i ];
  1965. if ( component === components[ componentIndex ] ) {
  1966. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1967. componentIndex ++;
  1968. } else {
  1969. snippetValues.push( sourceProperty + '.' + component );
  1970. }
  1971. }
  1972. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1973. }
  1974. }
  1975. /**
  1976. * Base class for representing data input nodes.
  1977. *
  1978. * @augments Node
  1979. */
  1980. class InputNode extends Node {
  1981. static get type() {
  1982. return 'InputNode';
  1983. }
  1984. /**
  1985. * Constructs a new input node.
  1986. *
  1987. * @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).
  1988. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1989. */
  1990. constructor( value, nodeType = null ) {
  1991. super( nodeType );
  1992. /**
  1993. * This flag can be used for type testing.
  1994. *
  1995. * @type {boolean}
  1996. * @readonly
  1997. * @default true
  1998. */
  1999. this.isInputNode = true;
  2000. /**
  2001. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  2002. *
  2003. * @type {any}
  2004. */
  2005. this.value = value;
  2006. /**
  2007. * The precision of the value in the shader.
  2008. *
  2009. * @type {?('low'|'medium'|'high')}
  2010. * @default null
  2011. */
  2012. this.precision = null;
  2013. }
  2014. getNodeType( /*builder*/ ) {
  2015. if ( this.nodeType === null ) {
  2016. return getValueType( this.value );
  2017. }
  2018. return this.nodeType;
  2019. }
  2020. /**
  2021. * Returns the input type of the node which is by default the node type. Derived modules
  2022. * might overwrite this method and use a fixed type or compute one analytically.
  2023. *
  2024. * A typical example for different input and node types are textures. The input type of a
  2025. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  2026. *
  2027. * @param {NodeBuilder} builder - The current node builder.
  2028. * @return {string} The input type.
  2029. */
  2030. getInputType( builder ) {
  2031. return this.getNodeType( builder );
  2032. }
  2033. /**
  2034. * Sets the precision to the given value. The method can be
  2035. * overwritten in derived classes if the final precision must be computed
  2036. * analytically.
  2037. *
  2038. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  2039. * @return {InputNode} A reference to this node.
  2040. */
  2041. setPrecision( precision ) {
  2042. this.precision = precision;
  2043. return this;
  2044. }
  2045. serialize( data ) {
  2046. super.serialize( data );
  2047. data.value = this.value;
  2048. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  2049. data.valueType = getValueType( this.value );
  2050. data.nodeType = this.nodeType;
  2051. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  2052. data.precision = this.precision;
  2053. }
  2054. deserialize( data ) {
  2055. super.deserialize( data );
  2056. this.nodeType = data.nodeType;
  2057. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  2058. this.precision = data.precision || null;
  2059. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  2060. }
  2061. generate( /*builder, output*/ ) {
  2062. console.warn( 'Abstract function.' );
  2063. }
  2064. }
  2065. const _regNum = /float|u?int/;
  2066. /**
  2067. * Class for representing a constant value in the shader.
  2068. *
  2069. * @augments InputNode
  2070. */
  2071. class ConstNode extends InputNode {
  2072. static get type() {
  2073. return 'ConstNode';
  2074. }
  2075. /**
  2076. * Constructs a new input node.
  2077. *
  2078. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2079. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2080. */
  2081. constructor( value, nodeType = null ) {
  2082. super( value, nodeType );
  2083. /**
  2084. * This flag can be used for type testing.
  2085. *
  2086. * @type {boolean}
  2087. * @readonly
  2088. * @default true
  2089. */
  2090. this.isConstNode = true;
  2091. }
  2092. /**
  2093. * Generates the shader string of the value with the current node builder.
  2094. *
  2095. * @param {NodeBuilder} builder - The current node builder.
  2096. * @return {string} The generated value as a shader string.
  2097. */
  2098. generateConst( builder ) {
  2099. return builder.generateConst( this.getNodeType( builder ), this.value );
  2100. }
  2101. generate( builder, output ) {
  2102. const type = this.getNodeType( builder );
  2103. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2104. return builder.generateConst( output, this.value );
  2105. }
  2106. return builder.format( this.generateConst( builder ), type, output );
  2107. }
  2108. }
  2109. /**
  2110. * Base class for representing member access on an object-like
  2111. * node data structures.
  2112. *
  2113. * @augments Node
  2114. */
  2115. class MemberNode extends Node {
  2116. static get type() {
  2117. return 'MemberNode';
  2118. }
  2119. /**
  2120. * Constructs a member node.
  2121. *
  2122. * @param {Node} structNode - The struct node.
  2123. * @param {string} property - The property name.
  2124. */
  2125. constructor( structNode, property ) {
  2126. super();
  2127. /**
  2128. * The struct node.
  2129. *
  2130. * @type {Node}
  2131. */
  2132. this.structNode = structNode;
  2133. /**
  2134. * The property name.
  2135. *
  2136. * @type {Node}
  2137. */
  2138. this.property = property;
  2139. /**
  2140. * This flag can be used for type testing.
  2141. *
  2142. * @type {boolean}
  2143. * @readonly
  2144. * @default true
  2145. */
  2146. this.isMemberNode = true;
  2147. }
  2148. hasMember( builder ) {
  2149. if ( this.structNode.isMemberNode ) {
  2150. if ( this.structNode.hasMember( builder ) === false ) {
  2151. return false;
  2152. }
  2153. }
  2154. return this.structNode.getMemberType( builder, this.property ) !== 'void';
  2155. }
  2156. getNodeType( builder ) {
  2157. if ( this.hasMember( builder ) === false ) {
  2158. // default type if member does not exist
  2159. return 'float';
  2160. }
  2161. return this.structNode.getMemberType( builder, this.property );
  2162. }
  2163. getMemberType( builder, name ) {
  2164. if ( this.hasMember( builder ) === false ) {
  2165. // default type if member does not exist
  2166. return 'float';
  2167. }
  2168. const type = this.getNodeType( builder );
  2169. const struct = builder.getStructTypeNode( type );
  2170. return struct.getMemberType( builder, name );
  2171. }
  2172. generate( builder ) {
  2173. if ( this.hasMember( builder ) === false ) {
  2174. console.warn( `THREE.TSL: Member "${ this.property }" does not exist in struct.` );
  2175. const type = this.getNodeType( builder );
  2176. return builder.generateConst( type );
  2177. }
  2178. const propertyName = this.structNode.build( builder );
  2179. return propertyName + '.' + this.property;
  2180. }
  2181. }
  2182. let currentStack = null;
  2183. const NodeElements = new Map();
  2184. // Extend Node Class for TSL using prototype
  2185. function addMethodChaining( name, nodeElement ) {
  2186. if ( NodeElements.has( name ) ) {
  2187. console.warn( `THREE.TSL: Redefinition of method chaining '${ name }'.` );
  2188. return;
  2189. }
  2190. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2191. NodeElements.set( name, nodeElement );
  2192. if ( name !== 'assign' ) {
  2193. // Changing Node prototype to add method chaining
  2194. Node.prototype[ name ] = function ( ...params ) {
  2195. //if ( name === 'toVarIntent' ) return this;
  2196. return this.isStackNode ? this.add( nodeElement( ...params ) ) : nodeElement( this, ...params );
  2197. };
  2198. // Adding assign method chaining
  2199. Node.prototype[ name + 'Assign' ] = function ( ...params ) {
  2200. return this.isStackNode ? this.assign( params[ 0 ], nodeElement( ...params ) ) : this.assign( nodeElement( this, ...params ) );
  2201. };
  2202. }
  2203. }
  2204. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2205. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2206. Node.prototype.assign = function ( ...params ) {
  2207. if ( this.isStackNode !== true ) {
  2208. if ( currentStack !== null ) {
  2209. currentStack.assign( this, ...params );
  2210. } else {
  2211. console.error( 'THREE.TSL: No stack defined for assign operation. Make sure the assign is inside a Fn().' );
  2212. }
  2213. return this;
  2214. } else {
  2215. const nodeElement = NodeElements.get( 'assign' );
  2216. return this.add( nodeElement( ...params ) );
  2217. }
  2218. };
  2219. Node.prototype.toVarIntent = function () {
  2220. return this;
  2221. };
  2222. Node.prototype.get = function ( value ) {
  2223. return new MemberNode( this, value );
  2224. };
  2225. // Cache prototype for TSL
  2226. const proto = {};
  2227. // Set swizzle properties for xyzw, rgba, and stpq.
  2228. function setProtoSwizzle( property, altA, altB ) {
  2229. // swizzle properties
  2230. proto[ property ] = proto[ altA ] = proto[ altB ] = {
  2231. get() {
  2232. this._cache = this._cache || {};
  2233. //
  2234. let split = this._cache[ property ];
  2235. if ( split === undefined ) {
  2236. split = new SplitNode( this, property );
  2237. this._cache[ property ] = split;
  2238. }
  2239. return split;
  2240. },
  2241. set( value ) {
  2242. this[ property ].assign( nodeObject( value ) );
  2243. }
  2244. };
  2245. // set properties ( swizzle ) and sort to xyzw sequence
  2246. const propUpper = property.toUpperCase();
  2247. const altAUpper = altA.toUpperCase();
  2248. const altBUpper = altB.toUpperCase();
  2249. // Set methods for swizzle properties
  2250. Node.prototype[ 'set' + propUpper ] = Node.prototype[ 'set' + altAUpper ] = Node.prototype[ 'set' + altBUpper ] = function ( value ) {
  2251. const swizzle = parseSwizzleAndSort( property );
  2252. return new SetNode( this, swizzle, nodeObject( value ) );
  2253. };
  2254. // Set methods for flip properties
  2255. Node.prototype[ 'flip' + propUpper ] = Node.prototype[ 'flip' + altAUpper ] = Node.prototype[ 'flip' + altBUpper ] = function () {
  2256. const swizzle = parseSwizzleAndSort( property );
  2257. return new FlipNode( this, swizzle );
  2258. };
  2259. }
  2260. const swizzleA = [ 'x', 'y', 'z', 'w' ];
  2261. const swizzleB = [ 'r', 'g', 'b', 'a' ];
  2262. const swizzleC = [ 's', 't', 'p', 'q' ];
  2263. for ( let a = 0; a < 4; a ++ ) {
  2264. let prop = swizzleA[ a ];
  2265. let altA = swizzleB[ a ];
  2266. let altB = swizzleC[ a ];
  2267. setProtoSwizzle( prop, altA, altB );
  2268. for ( let b = 0; b < 4; b ++ ) {
  2269. prop = swizzleA[ a ] + swizzleA[ b ];
  2270. altA = swizzleB[ a ] + swizzleB[ b ];
  2271. altB = swizzleC[ a ] + swizzleC[ b ];
  2272. setProtoSwizzle( prop, altA, altB );
  2273. for ( let c = 0; c < 4; c ++ ) {
  2274. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ];
  2275. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ];
  2276. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ];
  2277. setProtoSwizzle( prop, altA, altB );
  2278. for ( let d = 0; d < 4; d ++ ) {
  2279. prop = swizzleA[ a ] + swizzleA[ b ] + swizzleA[ c ] + swizzleA[ d ];
  2280. altA = swizzleB[ a ] + swizzleB[ b ] + swizzleB[ c ] + swizzleB[ d ];
  2281. altB = swizzleC[ a ] + swizzleC[ b ] + swizzleC[ c ] + swizzleC[ d ];
  2282. setProtoSwizzle( prop, altA, altB );
  2283. }
  2284. }
  2285. }
  2286. }
  2287. // Set/get static properties for array elements (0-31).
  2288. for ( let i = 0; i < 32; i ++ ) {
  2289. proto[ i ] = {
  2290. get() {
  2291. this._cache = this._cache || {};
  2292. //
  2293. let element = this._cache[ i ];
  2294. if ( element === undefined ) {
  2295. element = new ArrayElementNode( this, new ConstNode( i, 'uint' ) );
  2296. this._cache[ i ] = element;
  2297. }
  2298. return element;
  2299. },
  2300. set( value ) {
  2301. this[ i ].assign( nodeObject( value ) );
  2302. }
  2303. };
  2304. }
  2305. /*
  2306. // Set properties for width, height, and depth.
  2307. function setProtoProperty( property, target ) {
  2308. proto[ property ] = {
  2309. get() {
  2310. this._cache = this._cache || {};
  2311. //
  2312. let split = this._cache[ target ];
  2313. if ( split === undefined ) {
  2314. split = new SplitNode( this, target );
  2315. this._cache[ target ] = split;
  2316. }
  2317. return split;
  2318. },
  2319. set( value ) {
  2320. this[ target ].assign( nodeObject( value ) );
  2321. }
  2322. };
  2323. }
  2324. setProtoProperty( 'width', 'x' );
  2325. setProtoProperty( 'height', 'y' );
  2326. setProtoProperty( 'depth', 'z' );
  2327. */
  2328. Object.defineProperties( Node.prototype, proto );
  2329. // --- FINISH ---
  2330. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2331. const ShaderNodeObject = function ( obj, altType = null ) {
  2332. const type = getValueType( obj );
  2333. if ( type === 'node' ) {
  2334. return obj;
  2335. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2336. return nodeObject( getConstNode( obj, altType ) );
  2337. } else if ( type === 'shader' ) {
  2338. return obj.isFn ? obj : Fn( obj );
  2339. }
  2340. return obj;
  2341. };
  2342. const ShaderNodeObjects = function ( objects, altType = null ) {
  2343. for ( const name in objects ) {
  2344. objects[ name ] = nodeObject( objects[ name ], altType );
  2345. }
  2346. return objects;
  2347. };
  2348. const ShaderNodeArray = function ( array, altType = null ) {
  2349. const len = array.length;
  2350. for ( let i = 0; i < len; i ++ ) {
  2351. array[ i ] = nodeObject( array[ i ], altType );
  2352. }
  2353. return array;
  2354. };
  2355. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2356. function assignNode( node ) {
  2357. if ( settings !== null ) {
  2358. node = nodeObject( Object.assign( node, settings ) );
  2359. if ( settings.intent === true ) {
  2360. node = node.toVarIntent();
  2361. }
  2362. } else {
  2363. node = nodeObject( node );
  2364. }
  2365. return node;
  2366. }
  2367. let fn, name = scope, minParams, maxParams;
  2368. function verifyParamsLimit( params ) {
  2369. let tslName;
  2370. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2371. else tslName = NodeClass.type;
  2372. if ( minParams !== undefined && params.length < minParams ) {
  2373. console.error( `THREE.TSL: "${ tslName }" parameter length is less than minimum required.` );
  2374. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2375. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2376. console.error( `THREE.TSL: "${ tslName }" parameter length exceeds limit.` );
  2377. return params.slice( 0, maxParams );
  2378. }
  2379. return params;
  2380. }
  2381. if ( scope === null ) {
  2382. fn = ( ...params ) => {
  2383. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2384. };
  2385. } else if ( factor !== null ) {
  2386. factor = nodeObject( factor );
  2387. fn = ( ...params ) => {
  2388. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2389. };
  2390. } else {
  2391. fn = ( ...params ) => {
  2392. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2393. };
  2394. }
  2395. fn.setParameterLength = ( ...params ) => {
  2396. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2397. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2398. return fn;
  2399. };
  2400. fn.setName = ( value ) => {
  2401. name = value;
  2402. return fn;
  2403. };
  2404. return fn;
  2405. };
  2406. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2407. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2408. };
  2409. class ShaderCallNodeInternal extends Node {
  2410. constructor( shaderNode, rawInputs ) {
  2411. super();
  2412. this.shaderNode = shaderNode;
  2413. this.rawInputs = rawInputs;
  2414. this.isShaderCallNodeInternal = true;
  2415. }
  2416. getNodeType( builder ) {
  2417. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2418. }
  2419. getMemberType( builder, name ) {
  2420. return this.getOutputNode( builder ).getMemberType( builder, name );
  2421. }
  2422. call( builder ) {
  2423. const { shaderNode, rawInputs } = this;
  2424. const properties = builder.getNodeProperties( shaderNode );
  2425. const subBuild = builder.getClosestSubBuild( shaderNode.subBuilds ) || '';
  2426. const subBuildProperty = subBuild || 'default';
  2427. if ( properties[ subBuildProperty ] ) {
  2428. return properties[ subBuildProperty ];
  2429. }
  2430. //
  2431. const previousSubBuildFn = builder.subBuildFn;
  2432. builder.subBuildFn = subBuild;
  2433. let result = null;
  2434. if ( shaderNode.layout ) {
  2435. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2436. if ( functionNodesCacheMap === undefined ) {
  2437. functionNodesCacheMap = new WeakMap();
  2438. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2439. }
  2440. let functionNode = functionNodesCacheMap.get( shaderNode );
  2441. if ( functionNode === undefined ) {
  2442. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2443. functionNodesCacheMap.set( shaderNode, functionNode );
  2444. }
  2445. builder.addInclude( functionNode );
  2446. //
  2447. const inputs = rawInputs ? getLayoutParameters( rawInputs ) : null;
  2448. result = nodeObject( functionNode.call( inputs ) );
  2449. } else {
  2450. const secureNodeBuilder = new Proxy( builder, {
  2451. get: ( target, property, receiver ) => {
  2452. let value;
  2453. if ( Symbol.iterator === property ) {
  2454. value = function* () {
  2455. yield undefined;
  2456. };
  2457. } else {
  2458. value = Reflect.get( target, property, receiver );
  2459. }
  2460. return value;
  2461. }
  2462. } );
  2463. //
  2464. const inputs = rawInputs ? getProxyParameters( rawInputs ) : null;
  2465. const hasParameters = Array.isArray( rawInputs ) ? rawInputs.length > 0 : rawInputs !== null;
  2466. const jsFunc = shaderNode.jsFunc;
  2467. const outputNode = hasParameters || jsFunc.length > 1 ? jsFunc( inputs, secureNodeBuilder ) : jsFunc( secureNodeBuilder );
  2468. result = nodeObject( outputNode );
  2469. }
  2470. builder.subBuildFn = previousSubBuildFn;
  2471. if ( shaderNode.once ) {
  2472. properties[ subBuildProperty ] = result;
  2473. }
  2474. return result;
  2475. }
  2476. setupOutput( builder ) {
  2477. builder.addStack();
  2478. builder.stack.outputNode = this.call( builder );
  2479. return builder.removeStack();
  2480. }
  2481. getOutputNode( builder ) {
  2482. const properties = builder.getNodeProperties( this );
  2483. const subBuildOutput = builder.getSubBuildOutput( this );
  2484. properties[ subBuildOutput ] = properties[ subBuildOutput ] || this.setupOutput( builder );
  2485. properties[ subBuildOutput ].subBuild = builder.getClosestSubBuild( this );
  2486. return properties[ subBuildOutput ];
  2487. }
  2488. build( builder, output = null ) {
  2489. let result = null;
  2490. const buildStage = builder.getBuildStage();
  2491. const properties = builder.getNodeProperties( this );
  2492. const subBuildOutput = builder.getSubBuildOutput( this );
  2493. const outputNode = this.getOutputNode( builder );
  2494. if ( buildStage === 'setup' ) {
  2495. const subBuildInitialized = builder.getSubBuildProperty( 'initialized', this );
  2496. if ( properties[ subBuildInitialized ] !== true ) {
  2497. properties[ subBuildInitialized ] = true;
  2498. properties[ subBuildOutput ] = this.getOutputNode( builder );
  2499. properties[ subBuildOutput ].build( builder );
  2500. // If the shaderNode has subBuilds, add them to the chaining nodes
  2501. // so they can be built later in the build process.
  2502. if ( this.shaderNode.subBuilds ) {
  2503. for ( const node of builder.chaining ) {
  2504. const nodeData = builder.getDataFromNode( node, 'any' );
  2505. nodeData.subBuilds = nodeData.subBuilds || new Set();
  2506. for ( const subBuild of this.shaderNode.subBuilds ) {
  2507. nodeData.subBuilds.add( subBuild );
  2508. }
  2509. //builder.getDataFromNode( node ).subBuilds = nodeData.subBuilds;
  2510. }
  2511. }
  2512. }
  2513. result = properties[ subBuildOutput ];
  2514. } else if ( buildStage === 'analyze' ) {
  2515. outputNode.build( builder, output );
  2516. } else if ( buildStage === 'generate' ) {
  2517. result = outputNode.build( builder, output ) || '';
  2518. }
  2519. return result;
  2520. }
  2521. }
  2522. function getLayoutParameters( params ) {
  2523. let output;
  2524. nodeObjects( params );
  2525. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2526. if ( isArrayAsParameter ) {
  2527. output = [ ...params ];
  2528. } else {
  2529. output = params[ 0 ];
  2530. }
  2531. return output;
  2532. }
  2533. function getProxyParameters( params ) {
  2534. let index = 0;
  2535. nodeObjects( params );
  2536. return new Proxy( params, {
  2537. get: ( target, property, receiver ) => {
  2538. let value;
  2539. if ( property === 'length' ) {
  2540. value = params.length;
  2541. return value;
  2542. }
  2543. if ( Symbol.iterator === property ) {
  2544. value = function* () {
  2545. for ( const inputNode of params ) {
  2546. yield nodeObject( inputNode );
  2547. }
  2548. };
  2549. } else {
  2550. if ( params.length > 0 ) {
  2551. if ( Object.getPrototypeOf( params[ 0 ] ) === Object.prototype ) {
  2552. const objectTarget = params[ 0 ];
  2553. if ( objectTarget[ property ] === undefined ) {
  2554. value = objectTarget[ index ++ ];
  2555. } else {
  2556. value = Reflect.get( objectTarget, property, receiver );
  2557. }
  2558. } else if ( params[ 0 ] instanceof Node ) {
  2559. if ( params[ property ] === undefined ) {
  2560. value = params[ index ++ ];
  2561. } else {
  2562. value = Reflect.get( params, property, receiver );
  2563. }
  2564. }
  2565. } else {
  2566. value = Reflect.get( target, property, receiver );
  2567. }
  2568. value = nodeObject( value );
  2569. }
  2570. return value;
  2571. }
  2572. } );
  2573. }
  2574. class ShaderNodeInternal extends Node {
  2575. constructor( jsFunc, nodeType ) {
  2576. super( nodeType );
  2577. this.jsFunc = jsFunc;
  2578. this.layout = null;
  2579. this.global = true;
  2580. this.once = false;
  2581. }
  2582. setLayout( layout ) {
  2583. this.layout = layout;
  2584. return this;
  2585. }
  2586. call( rawInputs = null ) {
  2587. return nodeObject( new ShaderCallNodeInternal( this, rawInputs ) );
  2588. }
  2589. setup() {
  2590. return this.call();
  2591. }
  2592. }
  2593. const bools = [ false, true ];
  2594. const uints = [ 0, 1, 2, 3 ];
  2595. const ints = [ -1, -2 ];
  2596. 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 ];
  2597. const boolsCacheMap = new Map();
  2598. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2599. const uintsCacheMap = new Map();
  2600. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2601. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2602. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2603. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2604. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2605. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2606. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2607. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2608. const getConstNode = ( value, type ) => {
  2609. if ( constNodesCacheMap.has( value ) ) {
  2610. return constNodesCacheMap.get( value );
  2611. } else if ( value.isNode === true ) {
  2612. return value;
  2613. } else {
  2614. return new ConstNode( value, type );
  2615. }
  2616. };
  2617. const ConvertType = function ( type, cacheMap = null ) {
  2618. return ( ...params ) => {
  2619. for ( const param of params ) {
  2620. if ( param === undefined ) {
  2621. console.error( `THREE.TSL: Invalid parameter for the type "${ type }".` );
  2622. return nodeObject( new ConstNode( 0, type ) );
  2623. }
  2624. }
  2625. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => {
  2626. const paramType = typeof param;
  2627. return paramType !== 'object' && paramType !== 'function';
  2628. } ) ) ) {
  2629. params = [ getValueFromType( type, ...params ) ];
  2630. }
  2631. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2632. return nodeObjectIntent( cacheMap.get( params[ 0 ] ) );
  2633. }
  2634. if ( params.length === 1 ) {
  2635. const node = getConstNode( params[ 0 ], type );
  2636. if ( node.nodeType === type ) return nodeObjectIntent( node );
  2637. return nodeObjectIntent( new ConvertNode( node, type ) );
  2638. }
  2639. const nodes = params.map( param => getConstNode( param ) );
  2640. return nodeObjectIntent( new JoinNode( nodes, type ) );
  2641. };
  2642. };
  2643. // exports
  2644. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2645. // utils
  2646. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2647. // shader node base
  2648. function ShaderNode( jsFunc, nodeType ) {
  2649. return new ShaderNodeInternal( jsFunc, nodeType );
  2650. }
  2651. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2652. const nodeObjectIntent = ( val, altType = null ) => /* new */ nodeObject( val, altType ).toVarIntent();
  2653. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2654. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2655. const nodeProxy = ( NodeClass, scope = null, factor = null, settings = null ) => new ShaderNodeProxy( NodeClass, scope, factor, settings );
  2656. const nodeImmutable = ( NodeClass, ...params ) => new ShaderNodeImmutable( NodeClass, ...params );
  2657. const nodeProxyIntent = ( NodeClass, scope = null, factor = null, settings = {} ) => new ShaderNodeProxy( NodeClass, scope, factor, { intent: true, ...settings } );
  2658. let fnId = 0;
  2659. class FnNode extends Node {
  2660. constructor( jsFunc, layout = null ) {
  2661. super();
  2662. let nodeType = null;
  2663. if ( layout !== null ) {
  2664. if ( typeof layout === 'object' ) {
  2665. nodeType = layout.return;
  2666. } else {
  2667. if ( typeof layout === 'string' ) {
  2668. nodeType = layout;
  2669. } else {
  2670. console.error( 'THREE.TSL: Invalid layout type.' );
  2671. }
  2672. layout = null;
  2673. }
  2674. }
  2675. this.shaderNode = new ShaderNode( jsFunc, nodeType );
  2676. if ( layout !== null ) {
  2677. this.setLayout( layout );
  2678. }
  2679. this.isFn = true;
  2680. }
  2681. setLayout( layout ) {
  2682. const nodeType = this.shaderNode.nodeType;
  2683. if ( typeof layout.inputs !== 'object' ) {
  2684. const fullLayout = {
  2685. name: 'fn' + fnId ++,
  2686. type: nodeType,
  2687. inputs: []
  2688. };
  2689. for ( const name in layout ) {
  2690. if ( name === 'return' ) continue;
  2691. fullLayout.inputs.push( {
  2692. name: name,
  2693. type: layout[ name ]
  2694. } );
  2695. }
  2696. layout = fullLayout;
  2697. }
  2698. this.shaderNode.setLayout( layout );
  2699. return this;
  2700. }
  2701. getNodeType( builder ) {
  2702. return this.shaderNode.getNodeType( builder ) || 'float';
  2703. }
  2704. call( ...params ) {
  2705. const fnCall = this.shaderNode.call( params );
  2706. if ( this.shaderNode.nodeType === 'void' ) fnCall.toStack();
  2707. return fnCall.toVarIntent();
  2708. }
  2709. once( subBuilds = null ) {
  2710. this.shaderNode.once = true;
  2711. this.shaderNode.subBuilds = subBuilds;
  2712. return this;
  2713. }
  2714. generate( builder ) {
  2715. const type = this.getNodeType( builder );
  2716. console.error( 'THREE.TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".' );
  2717. return builder.generateConst( type );
  2718. }
  2719. }
  2720. function Fn( jsFunc, layout = null ) {
  2721. const instance = new FnNode( jsFunc, layout );
  2722. return new Proxy( () => {}, {
  2723. apply( target, thisArg, params ) {
  2724. return instance.call( ...params );
  2725. },
  2726. get( target, prop, receiver ) {
  2727. return Reflect.get( instance, prop, receiver );
  2728. },
  2729. set( target, prop, value, receiver ) {
  2730. return Reflect.set( instance, prop, value, receiver );
  2731. }
  2732. } );
  2733. }
  2734. //
  2735. const setCurrentStack = ( stack ) => {
  2736. currentStack = stack;
  2737. };
  2738. const getCurrentStack = () => currentStack;
  2739. /**
  2740. * Represent a conditional node using if/else statements.
  2741. *
  2742. * ```js
  2743. * If( condition, function )
  2744. * .ElseIf( condition, function )
  2745. * .Else( function )
  2746. * ```
  2747. * @tsl
  2748. * @function
  2749. * @param {...any} params - The parameters for the conditional node.
  2750. * @returns {StackNode} The conditional node.
  2751. */
  2752. const If = ( ...params ) => currentStack.If( ...params );
  2753. /**
  2754. * Represent a conditional node using switch/case statements.
  2755. *
  2756. * ```js
  2757. * Switch( value )
  2758. * .Case( 1, function )
  2759. * .Case( 2, 3, 4, function )
  2760. * .Default( function )
  2761. * ```
  2762. * @tsl
  2763. * @function
  2764. * @param {...any} params - The parameters for the conditional node.
  2765. * @returns {StackNode} The conditional node.
  2766. */
  2767. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2768. /**
  2769. * Add the given node to the current stack.
  2770. *
  2771. * @param {Node} node - The node to add.
  2772. * @returns {Node} The node that was added to the stack.
  2773. */
  2774. function Stack( node ) {
  2775. if ( currentStack ) currentStack.add( node );
  2776. return node;
  2777. }
  2778. addMethodChaining( 'toStack', Stack );
  2779. // types
  2780. const color = new ConvertType( 'color' );
  2781. const float = new ConvertType( 'float', cacheMaps.float );
  2782. const int = new ConvertType( 'int', cacheMaps.ints );
  2783. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2784. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2785. const vec2 = new ConvertType( 'vec2' );
  2786. const ivec2 = new ConvertType( 'ivec2' );
  2787. const uvec2 = new ConvertType( 'uvec2' );
  2788. const bvec2 = new ConvertType( 'bvec2' );
  2789. const vec3 = new ConvertType( 'vec3' );
  2790. const ivec3 = new ConvertType( 'ivec3' );
  2791. const uvec3 = new ConvertType( 'uvec3' );
  2792. const bvec3 = new ConvertType( 'bvec3' );
  2793. const vec4 = new ConvertType( 'vec4' );
  2794. const ivec4 = new ConvertType( 'ivec4' );
  2795. const uvec4 = new ConvertType( 'uvec4' );
  2796. const bvec4 = new ConvertType( 'bvec4' );
  2797. const mat2 = new ConvertType( 'mat2' );
  2798. const mat3 = new ConvertType( 'mat3' );
  2799. const mat4 = new ConvertType( 'mat4' );
  2800. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2801. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2802. addMethodChaining( 'toColor', color );
  2803. addMethodChaining( 'toFloat', float );
  2804. addMethodChaining( 'toInt', int );
  2805. addMethodChaining( 'toUint', uint );
  2806. addMethodChaining( 'toBool', bool );
  2807. addMethodChaining( 'toVec2', vec2 );
  2808. addMethodChaining( 'toIVec2', ivec2 );
  2809. addMethodChaining( 'toUVec2', uvec2 );
  2810. addMethodChaining( 'toBVec2', bvec2 );
  2811. addMethodChaining( 'toVec3', vec3 );
  2812. addMethodChaining( 'toIVec3', ivec3 );
  2813. addMethodChaining( 'toUVec3', uvec3 );
  2814. addMethodChaining( 'toBVec3', bvec3 );
  2815. addMethodChaining( 'toVec4', vec4 );
  2816. addMethodChaining( 'toIVec4', ivec4 );
  2817. addMethodChaining( 'toUVec4', uvec4 );
  2818. addMethodChaining( 'toBVec4', bvec4 );
  2819. addMethodChaining( 'toMat2', mat2 );
  2820. addMethodChaining( 'toMat3', mat3 );
  2821. addMethodChaining( 'toMat4', mat4 );
  2822. // basic nodes
  2823. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2824. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2825. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2826. addMethodChaining( 'element', element );
  2827. addMethodChaining( 'convert', convert );
  2828. // deprecated
  2829. /**
  2830. * @tsl
  2831. * @function
  2832. * @deprecated since r176. Use {@link Stack} instead.
  2833. *
  2834. * @param {Node} node - The node to add.
  2835. * @returns {Function}
  2836. */
  2837. const append = ( node ) => { // @deprecated, r176
  2838. console.warn( 'THREE.TSL: append() has been renamed to Stack().' );
  2839. return Stack( node );
  2840. };
  2841. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2842. console.warn( 'THREE.TSL: .append() has been renamed to .toStack().' );
  2843. return Stack( node );
  2844. } );
  2845. /**
  2846. * This class represents a shader property. It can be used
  2847. * to explicitly define a property and assign a value to it.
  2848. *
  2849. * ```js
  2850. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2851. *```
  2852. * `PropertyNode` is used by the engine to predefined common material properties
  2853. * for TSL code.
  2854. *
  2855. * @augments Node
  2856. */
  2857. class PropertyNode extends Node {
  2858. static get type() {
  2859. return 'PropertyNode';
  2860. }
  2861. /**
  2862. * Constructs a new property node.
  2863. *
  2864. * @param {string} nodeType - The type of the node.
  2865. * @param {?string} [name=null] - The name of the property in the shader.
  2866. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2867. */
  2868. constructor( nodeType, name = null, varying = false ) {
  2869. super( nodeType );
  2870. /**
  2871. * The name of the property in the shader. If no name is defined,
  2872. * the node system auto-generates one.
  2873. *
  2874. * @type {?string}
  2875. * @default null
  2876. */
  2877. this.name = name;
  2878. /**
  2879. * Whether this property is a varying or not.
  2880. *
  2881. * @type {boolean}
  2882. * @default false
  2883. */
  2884. this.varying = varying;
  2885. /**
  2886. * This flag can be used for type testing.
  2887. *
  2888. * @type {boolean}
  2889. * @readonly
  2890. * @default true
  2891. */
  2892. this.isPropertyNode = true;
  2893. /**
  2894. * This flag is used for global cache.
  2895. *
  2896. * @type {boolean}
  2897. * @default true
  2898. */
  2899. this.global = true;
  2900. }
  2901. getHash( builder ) {
  2902. return this.name || super.getHash( builder );
  2903. }
  2904. generate( builder ) {
  2905. let nodeVar;
  2906. if ( this.varying === true ) {
  2907. nodeVar = builder.getVaryingFromNode( this, this.name );
  2908. nodeVar.needsInterpolation = true;
  2909. } else {
  2910. nodeVar = builder.getVarFromNode( this, this.name );
  2911. }
  2912. return builder.getPropertyName( nodeVar );
  2913. }
  2914. }
  2915. /**
  2916. * TSL function for creating a property node.
  2917. *
  2918. * @tsl
  2919. * @function
  2920. * @param {string} type - The type of the node.
  2921. * @param {?string} [name=null] - The name of the property in the shader.
  2922. * @returns {PropertyNode}
  2923. */
  2924. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2925. /**
  2926. * TSL function for creating a varying property node.
  2927. *
  2928. * @tsl
  2929. * @function
  2930. * @param {string} type - The type of the node.
  2931. * @param {?string} [name=null] - The name of the varying in the shader.
  2932. * @returns {PropertyNode}
  2933. */
  2934. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2935. /**
  2936. * TSL object that represents the shader variable `DiffuseColor`.
  2937. *
  2938. * @tsl
  2939. * @type {PropertyNode<vec4>}
  2940. */
  2941. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2942. /**
  2943. * TSL object that represents the shader variable `EmissiveColor`.
  2944. *
  2945. * @tsl
  2946. * @type {PropertyNode<vec3>}
  2947. */
  2948. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2949. /**
  2950. * TSL object that represents the shader variable `Roughness`.
  2951. *
  2952. * @tsl
  2953. * @type {PropertyNode<float>}
  2954. */
  2955. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2956. /**
  2957. * TSL object that represents the shader variable `Metalness`.
  2958. *
  2959. * @tsl
  2960. * @type {PropertyNode<float>}
  2961. */
  2962. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2963. /**
  2964. * TSL object that represents the shader variable `Clearcoat`.
  2965. *
  2966. * @tsl
  2967. * @type {PropertyNode<float>}
  2968. */
  2969. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2970. /**
  2971. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2972. *
  2973. * @tsl
  2974. * @type {PropertyNode<float>}
  2975. */
  2976. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2977. /**
  2978. * TSL object that represents the shader variable `Sheen`.
  2979. *
  2980. * @tsl
  2981. * @type {PropertyNode<vec3>}
  2982. */
  2983. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2984. /**
  2985. * TSL object that represents the shader variable `SheenRoughness`.
  2986. *
  2987. * @tsl
  2988. * @type {PropertyNode<float>}
  2989. */
  2990. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2991. /**
  2992. * TSL object that represents the shader variable `Iridescence`.
  2993. *
  2994. * @tsl
  2995. * @type {PropertyNode<float>}
  2996. */
  2997. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2998. /**
  2999. * TSL object that represents the shader variable `IridescenceIOR`.
  3000. *
  3001. * @tsl
  3002. * @type {PropertyNode<float>}
  3003. */
  3004. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  3005. /**
  3006. * TSL object that represents the shader variable `IridescenceThickness`.
  3007. *
  3008. * @tsl
  3009. * @type {PropertyNode<float>}
  3010. */
  3011. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  3012. /**
  3013. * TSL object that represents the shader variable `AlphaT`.
  3014. *
  3015. * @tsl
  3016. * @type {PropertyNode<float>}
  3017. */
  3018. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  3019. /**
  3020. * TSL object that represents the shader variable `Anisotropy`.
  3021. *
  3022. * @tsl
  3023. * @type {PropertyNode<float>}
  3024. */
  3025. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  3026. /**
  3027. * TSL object that represents the shader variable `AnisotropyT`.
  3028. *
  3029. * @tsl
  3030. * @type {PropertyNode<vec3>}
  3031. */
  3032. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  3033. /**
  3034. * TSL object that represents the shader variable `AnisotropyB`.
  3035. *
  3036. * @tsl
  3037. * @type {PropertyNode<vec3>}
  3038. */
  3039. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  3040. /**
  3041. * TSL object that represents the shader variable `SpecularColor`.
  3042. *
  3043. * @tsl
  3044. * @type {PropertyNode<color>}
  3045. */
  3046. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  3047. /**
  3048. * TSL object that represents the shader variable `SpecularF90`.
  3049. *
  3050. * @tsl
  3051. * @type {PropertyNode<float>}
  3052. */
  3053. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  3054. /**
  3055. * TSL object that represents the shader variable `Shininess`.
  3056. *
  3057. * @tsl
  3058. * @type {PropertyNode<float>}
  3059. */
  3060. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  3061. /**
  3062. * TSL object that represents the shader variable `Output`.
  3063. *
  3064. * @tsl
  3065. * @type {PropertyNode<vec4>}
  3066. */
  3067. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  3068. /**
  3069. * TSL object that represents the shader variable `dashSize`.
  3070. *
  3071. * @tsl
  3072. * @type {PropertyNode<float>}
  3073. */
  3074. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  3075. /**
  3076. * TSL object that represents the shader variable `gapSize`.
  3077. *
  3078. * @tsl
  3079. * @type {PropertyNode<float>}
  3080. */
  3081. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  3082. /**
  3083. * TSL object that represents the shader variable `pointWidth`.
  3084. *
  3085. * @tsl
  3086. * @type {PropertyNode<float>}
  3087. */
  3088. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  3089. /**
  3090. * TSL object that represents the shader variable `IOR`.
  3091. *
  3092. * @tsl
  3093. * @type {PropertyNode<float>}
  3094. */
  3095. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  3096. /**
  3097. * TSL object that represents the shader variable `Transmission`.
  3098. *
  3099. * @tsl
  3100. * @type {PropertyNode<float>}
  3101. */
  3102. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  3103. /**
  3104. * TSL object that represents the shader variable `Thickness`.
  3105. *
  3106. * @tsl
  3107. * @type {PropertyNode<float>}
  3108. */
  3109. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  3110. /**
  3111. * TSL object that represents the shader variable `AttenuationDistance`.
  3112. *
  3113. * @tsl
  3114. * @type {PropertyNode<float>}
  3115. */
  3116. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  3117. /**
  3118. * TSL object that represents the shader variable `AttenuationColor`.
  3119. *
  3120. * @tsl
  3121. * @type {PropertyNode<color>}
  3122. */
  3123. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  3124. /**
  3125. * TSL object that represents the shader variable `Dispersion`.
  3126. *
  3127. * @tsl
  3128. * @type {PropertyNode<float>}
  3129. */
  3130. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  3131. /**
  3132. * This node can be used to group single instances of {@link UniformNode}
  3133. * and manage them as a uniform buffer.
  3134. *
  3135. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  3136. * will be used when defining the {@link UniformNode#groupNode} property.
  3137. *
  3138. * - `objectGroup`: Uniform buffer per object.
  3139. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  3140. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  3141. *
  3142. * @augments Node
  3143. */
  3144. class UniformGroupNode extends Node {
  3145. static get type() {
  3146. return 'UniformGroupNode';
  3147. }
  3148. /**
  3149. * Constructs a new uniform group node.
  3150. *
  3151. * @param {string} name - The name of the uniform group node.
  3152. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  3153. * @param {number} [order=1] - Influences the internal sorting.
  3154. */
  3155. constructor( name, shared = false, order = 1 ) {
  3156. super( 'string' );
  3157. /**
  3158. * The name of the uniform group node.
  3159. *
  3160. * @type {string}
  3161. */
  3162. this.name = name;
  3163. /**
  3164. * Whether this uniform group node is shared or not.
  3165. *
  3166. * @type {boolean}
  3167. * @default false
  3168. */
  3169. this.shared = shared;
  3170. /**
  3171. * Influences the internal sorting.
  3172. * TODO: Add details when this property should be changed.
  3173. *
  3174. * @type {number}
  3175. * @default 1
  3176. */
  3177. this.order = order;
  3178. /**
  3179. * This flag can be used for type testing.
  3180. *
  3181. * @type {boolean}
  3182. * @readonly
  3183. * @default true
  3184. */
  3185. this.isUniformGroup = true;
  3186. }
  3187. serialize( data ) {
  3188. super.serialize( data );
  3189. data.name = this.name;
  3190. data.version = this.version;
  3191. data.shared = this.shared;
  3192. }
  3193. deserialize( data ) {
  3194. super.deserialize( data );
  3195. this.name = data.name;
  3196. this.version = data.version;
  3197. this.shared = data.shared;
  3198. }
  3199. }
  3200. /**
  3201. * TSL function for creating a uniform group node with the given name.
  3202. *
  3203. * @tsl
  3204. * @function
  3205. * @param {string} name - The name of the uniform group node.
  3206. * @returns {UniformGroupNode}
  3207. */
  3208. const uniformGroup = ( name ) => new UniformGroupNode( name );
  3209. /**
  3210. * TSL function for creating a shared uniform group node with the given name and order.
  3211. *
  3212. * @tsl
  3213. * @function
  3214. * @param {string} name - The name of the uniform group node.
  3215. * @param {number} [order=0] - Influences the internal sorting.
  3216. * @returns {UniformGroupNode}
  3217. */
  3218. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  3219. /**
  3220. * TSL object that represents a shared uniform group node which is updated once per frame.
  3221. *
  3222. * @tsl
  3223. * @type {UniformGroupNode}
  3224. */
  3225. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  3226. /**
  3227. * TSL object that represents a shared uniform group node which is updated once per render.
  3228. *
  3229. * @tsl
  3230. * @type {UniformGroupNode}
  3231. */
  3232. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  3233. /**
  3234. * TSL object that represents a uniform group node which is updated once per object.
  3235. *
  3236. * @tsl
  3237. * @type {UniformGroupNode}
  3238. */
  3239. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  3240. /**
  3241. * Class for representing a uniform.
  3242. *
  3243. * @augments InputNode
  3244. */
  3245. class UniformNode extends InputNode {
  3246. static get type() {
  3247. return 'UniformNode';
  3248. }
  3249. /**
  3250. * Constructs a new uniform node.
  3251. *
  3252. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3253. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3254. */
  3255. constructor( value, nodeType = null ) {
  3256. super( value, nodeType );
  3257. /**
  3258. * This flag can be used for type testing.
  3259. *
  3260. * @type {boolean}
  3261. * @readonly
  3262. * @default true
  3263. */
  3264. this.isUniformNode = true;
  3265. /**
  3266. * The name or label of the uniform.
  3267. *
  3268. * @type {string}
  3269. * @default ''
  3270. */
  3271. this.name = '';
  3272. /**
  3273. * The uniform group of this uniform. By default, uniforms are
  3274. * managed per object but they might belong to a shared group
  3275. * which is updated per frame or render call.
  3276. *
  3277. * @type {UniformGroupNode}
  3278. */
  3279. this.groupNode = objectGroup;
  3280. }
  3281. /**
  3282. * Sets the {@link UniformNode#name} property.
  3283. *
  3284. * @param {string} name - The name of the uniform.
  3285. * @return {UniformNode} A reference to this node.
  3286. */
  3287. setName( name ) {
  3288. this.name = name;
  3289. return this;
  3290. }
  3291. /**
  3292. * Sets the {@link UniformNode#name} property.
  3293. *
  3294. * @deprecated
  3295. * @param {string} name - The name of the uniform.
  3296. * @return {UniformNode} A reference to this node.
  3297. */
  3298. label( name ) {
  3299. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  3300. return this.setName( name );
  3301. }
  3302. /**
  3303. * Sets the {@link UniformNode#groupNode} property.
  3304. *
  3305. * @param {UniformGroupNode} group - The uniform group.
  3306. * @return {UniformNode} A reference to this node.
  3307. */
  3308. setGroup( group ) {
  3309. this.groupNode = group;
  3310. return this;
  3311. }
  3312. /**
  3313. * Returns the {@link UniformNode#groupNode}.
  3314. *
  3315. * @return {UniformGroupNode} The uniform group.
  3316. */
  3317. getGroup() {
  3318. return this.groupNode;
  3319. }
  3320. /**
  3321. * By default, this method returns the result of {@link Node#getHash} but derived
  3322. * classes might overwrite this method with a different implementation.
  3323. *
  3324. * @param {NodeBuilder} builder - The current node builder.
  3325. * @return {string} The uniform hash.
  3326. */
  3327. getUniformHash( builder ) {
  3328. return this.getHash( builder );
  3329. }
  3330. onUpdate( callback, updateType ) {
  3331. callback = callback.bind( this );
  3332. return super.onUpdate( ( frame ) => {
  3333. const value = callback( frame, this );
  3334. if ( value !== undefined ) {
  3335. this.value = value;
  3336. }
  3337. }, updateType );
  3338. }
  3339. getInputType( builder ) {
  3340. let type = super.getInputType( builder );
  3341. if ( type === 'bool' ) {
  3342. type = 'uint';
  3343. }
  3344. return type;
  3345. }
  3346. generate( builder, output ) {
  3347. const type = this.getNodeType( builder );
  3348. const hash = this.getUniformHash( builder );
  3349. let sharedNode = builder.getNodeFromHash( hash );
  3350. if ( sharedNode === undefined ) {
  3351. builder.setHashNode( this, hash );
  3352. sharedNode = this;
  3353. }
  3354. const sharedNodeType = sharedNode.getInputType( builder );
  3355. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.nodeName );
  3356. const uniformName = builder.getPropertyName( nodeUniform );
  3357. if ( builder.context.nodeName !== undefined ) delete builder.context.nodeName;
  3358. //
  3359. let snippet = uniformName;
  3360. if ( type === 'bool' ) {
  3361. // cache to variable
  3362. const nodeData = builder.getDataFromNode( this );
  3363. let propertyName = nodeData.propertyName;
  3364. if ( propertyName === undefined ) {
  3365. const nodeVar = builder.getVarFromNode( this, null, 'bool' );
  3366. propertyName = builder.getPropertyName( nodeVar );
  3367. nodeData.propertyName = propertyName;
  3368. snippet = builder.format( uniformName, sharedNodeType, type );
  3369. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  3370. }
  3371. snippet = propertyName;
  3372. }
  3373. return builder.format( snippet, type, output );
  3374. }
  3375. }
  3376. /**
  3377. * TSL function for creating a uniform node.
  3378. *
  3379. * @tsl
  3380. * @function
  3381. * @param {any|string} value - The value of this uniform or your type. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3382. * @param {string} [type] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3383. * @returns {UniformNode}
  3384. */
  3385. const uniform = ( value, type ) => {
  3386. const nodeType = getConstNodeType( type || value );
  3387. if ( nodeType === value ) {
  3388. // if the value is a type but no having a value
  3389. value = getValueFromType( nodeType );
  3390. }
  3391. // @TODO: get ConstNode from .traverse() in the future
  3392. value = ( value && value.isNode === true ) ? ( value.node && value.node.value ) || value.value : value;
  3393. return nodeObject( new UniformNode( value, nodeType ) );
  3394. };
  3395. /**
  3396. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3397. * ```js
  3398. * const colors = array( [
  3399. * vec3( 1, 0, 0 ),
  3400. * vec3( 0, 1, 0 ),
  3401. * vec3( 0, 0, 1 )
  3402. * ] );
  3403. *
  3404. * const redColor = tintColors.element( 0 );
  3405. *
  3406. * @augments TempNode
  3407. */
  3408. class ArrayNode extends TempNode {
  3409. static get type() {
  3410. return 'ArrayNode';
  3411. }
  3412. /**
  3413. * Constructs a new array node.
  3414. *
  3415. * @param {?string} nodeType - The data type of the elements.
  3416. * @param {number} count - Size of the array.
  3417. * @param {?Array<Node>} [values=null] - Array default values.
  3418. */
  3419. constructor( nodeType, count, values = null ) {
  3420. super( nodeType );
  3421. /**
  3422. * Array size.
  3423. *
  3424. * @type {number}
  3425. */
  3426. this.count = count;
  3427. /**
  3428. * Array default values.
  3429. *
  3430. * @type {?Array<Node>}
  3431. */
  3432. this.values = values;
  3433. /**
  3434. * This flag can be used for type testing.
  3435. *
  3436. * @type {boolean}
  3437. * @readonly
  3438. * @default true
  3439. */
  3440. this.isArrayNode = true;
  3441. }
  3442. /**
  3443. * Returns the number of elements in the node array.
  3444. *
  3445. * @param {NodeBuilder} builder - The current node builder.
  3446. * @return {number} The number of elements in the node array.
  3447. */
  3448. getArrayCount( /*builder*/ ) {
  3449. return this.count;
  3450. }
  3451. /**
  3452. * Returns the node's type.
  3453. *
  3454. * @param {NodeBuilder} builder - The current node builder.
  3455. * @return {string} The type of the node.
  3456. */
  3457. getNodeType( builder ) {
  3458. if ( this.nodeType === null ) {
  3459. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3460. }
  3461. return this.nodeType;
  3462. }
  3463. /**
  3464. * Returns the node's type.
  3465. *
  3466. * @param {NodeBuilder} builder - The current node builder.
  3467. * @return {string} The type of the node.
  3468. */
  3469. getElementType( builder ) {
  3470. return this.getNodeType( builder );
  3471. }
  3472. /**
  3473. * This method builds the output node and returns the resulting array as a shader string.
  3474. *
  3475. * @param {NodeBuilder} builder - The current node builder.
  3476. * @return {string} The generated shader string.
  3477. */
  3478. generate( builder ) {
  3479. const type = this.getNodeType( builder );
  3480. return builder.generateArray( type, this.count, this.values );
  3481. }
  3482. }
  3483. /**
  3484. * TSL function for creating an array node.
  3485. *
  3486. * @tsl
  3487. * @function
  3488. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3489. * or an array containing the default values (e.g., [ vec3() ]).
  3490. * @param {?number} [count] - Size of the array.
  3491. * @returns {ArrayNode}
  3492. */
  3493. const array = ( ...params ) => {
  3494. let node;
  3495. if ( params.length === 1 ) {
  3496. const values = params[ 0 ];
  3497. node = new ArrayNode( null, values.length, values );
  3498. } else {
  3499. const nodeType = params[ 0 ];
  3500. const count = params[ 1 ];
  3501. node = new ArrayNode( nodeType, count );
  3502. }
  3503. return nodeObject( node );
  3504. };
  3505. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3506. /**
  3507. * These node represents an assign operation. Meaning a node is assigned
  3508. * to another node.
  3509. *
  3510. * @augments TempNode
  3511. */
  3512. class AssignNode extends TempNode {
  3513. static get type() {
  3514. return 'AssignNode';
  3515. }
  3516. /**
  3517. * Constructs a new assign node.
  3518. *
  3519. * @param {Node} targetNode - The target node.
  3520. * @param {Node} sourceNode - The source type.
  3521. */
  3522. constructor( targetNode, sourceNode ) {
  3523. super();
  3524. /**
  3525. * The target node.
  3526. *
  3527. * @type {Node}
  3528. */
  3529. this.targetNode = targetNode;
  3530. /**
  3531. * The source node.
  3532. *
  3533. * @type {Node}
  3534. */
  3535. this.sourceNode = sourceNode;
  3536. /**
  3537. * This flag can be used for type testing.
  3538. *
  3539. * @type {boolean}
  3540. * @readonly
  3541. * @default true
  3542. */
  3543. this.isAssignNode = true;
  3544. }
  3545. /**
  3546. * Whether this node is used more than once in context of other nodes. This method
  3547. * is overwritten since it always returns `false` (assigns are unique).
  3548. *
  3549. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3550. */
  3551. hasDependencies() {
  3552. return false;
  3553. }
  3554. getNodeType( builder, output ) {
  3555. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3556. }
  3557. /**
  3558. * Whether a split is required when assigning source to target. This can happen when the component length of
  3559. * target and source data type does not match.
  3560. *
  3561. * @param {NodeBuilder} builder - The current node builder.
  3562. * @return {boolean} Whether a split is required when assigning source to target.
  3563. */
  3564. needsSplitAssign( builder ) {
  3565. const { targetNode } = this;
  3566. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3567. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3568. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3569. return assignDifferentVector;
  3570. }
  3571. return false;
  3572. }
  3573. setup( builder ) {
  3574. const { targetNode, sourceNode } = this;
  3575. const scope = targetNode.getScope();
  3576. const targetProperties = builder.getNodeProperties( scope );
  3577. targetProperties.assign = true;
  3578. const properties = builder.getNodeProperties( this );
  3579. properties.sourceNode = sourceNode;
  3580. properties.targetNode = targetNode.context( { assign: true } );
  3581. }
  3582. generate( builder, output ) {
  3583. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3584. const needsSplitAssign = this.needsSplitAssign( builder );
  3585. const target = targetNode.build( builder );
  3586. const targetType = targetNode.getNodeType( builder );
  3587. const source = sourceNode.build( builder, targetType );
  3588. const sourceType = sourceNode.getNodeType( builder );
  3589. const nodeData = builder.getDataFromNode( this );
  3590. //
  3591. let snippet;
  3592. if ( nodeData.initialized === true ) {
  3593. if ( output !== 'void' ) {
  3594. snippet = target;
  3595. }
  3596. } else if ( needsSplitAssign ) {
  3597. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3598. const sourceProperty = builder.getPropertyName( sourceVar );
  3599. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3600. const splitNode = targetNode.node;
  3601. const splitTargetNode = splitNode.node.context( { assign: true } );
  3602. const targetRoot = splitTargetNode.build( builder );
  3603. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3604. const component = splitNode.components[ i ];
  3605. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3606. }
  3607. if ( output !== 'void' ) {
  3608. snippet = target;
  3609. }
  3610. } else {
  3611. snippet = `${ target } = ${ source }`;
  3612. if ( output === 'void' || sourceType === 'void' ) {
  3613. builder.addLineFlowCode( snippet, this );
  3614. if ( output !== 'void' ) {
  3615. snippet = target;
  3616. }
  3617. }
  3618. }
  3619. nodeData.initialized = true;
  3620. return builder.format( snippet, targetType, output );
  3621. }
  3622. }
  3623. /**
  3624. * TSL function for creating an assign node.
  3625. *
  3626. * @tsl
  3627. * @function
  3628. * @param {Node} targetNode - The target node.
  3629. * @param {Node} sourceNode - The source type.
  3630. * @returns {AssignNode}
  3631. */
  3632. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3633. addMethodChaining( 'assign', assign );
  3634. /**
  3635. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3636. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3637. * this logic.
  3638. *
  3639. * @augments TempNode
  3640. */
  3641. class FunctionCallNode extends TempNode {
  3642. static get type() {
  3643. return 'FunctionCallNode';
  3644. }
  3645. /**
  3646. * Constructs a new function call node.
  3647. *
  3648. * @param {?FunctionNode} functionNode - The function node.
  3649. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3650. */
  3651. constructor( functionNode = null, parameters = {} ) {
  3652. super();
  3653. /**
  3654. * The function node.
  3655. *
  3656. * @type {?FunctionNode}
  3657. * @default null
  3658. */
  3659. this.functionNode = functionNode;
  3660. /**
  3661. * The parameters of the function call.
  3662. *
  3663. * @type {Object<string, Node>}
  3664. * @default {}
  3665. */
  3666. this.parameters = parameters;
  3667. }
  3668. /**
  3669. * Sets the parameters of the function call node.
  3670. *
  3671. * @param {Object<string, Node>} parameters - The parameters to set.
  3672. * @return {FunctionCallNode} A reference to this node.
  3673. */
  3674. setParameters( parameters ) {
  3675. this.parameters = parameters;
  3676. return this;
  3677. }
  3678. /**
  3679. * Returns the parameters of the function call node.
  3680. *
  3681. * @return {Object<string, Node>} The parameters of this node.
  3682. */
  3683. getParameters() {
  3684. return this.parameters;
  3685. }
  3686. /**
  3687. * Returns the type of this function call node.
  3688. *
  3689. * @param {NodeBuilder} builder - The current node builder.
  3690. * @returns {string} The type of this node.
  3691. */
  3692. getNodeType( builder ) {
  3693. return this.functionNode.getNodeType( builder );
  3694. }
  3695. /**
  3696. * Returns the function node of this function call node.
  3697. *
  3698. * @param {NodeBuilder} builder - The current node builder.
  3699. * @param {string} [name] - The name of the member.
  3700. * @returns {string} The type of the member.
  3701. */
  3702. getMemberType( builder, name ) {
  3703. return this.functionNode.getMemberType( builder, name );
  3704. }
  3705. generate( builder ) {
  3706. const params = [];
  3707. const functionNode = this.functionNode;
  3708. const inputs = functionNode.getInputs( builder );
  3709. const parameters = this.parameters;
  3710. const generateInput = ( node, inputNode ) => {
  3711. const type = inputNode.type;
  3712. const pointer = type === 'pointer';
  3713. let output;
  3714. if ( pointer ) output = '&' + node.build( builder );
  3715. else output = node.build( builder, type );
  3716. return output;
  3717. };
  3718. if ( Array.isArray( parameters ) ) {
  3719. if ( parameters.length > inputs.length ) {
  3720. console.error( 'THREE.TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3721. parameters.length = inputs.length;
  3722. } else if ( parameters.length < inputs.length ) {
  3723. console.error( 'THREE.TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3724. while ( parameters.length < inputs.length ) {
  3725. parameters.push( float( 0 ) );
  3726. }
  3727. }
  3728. for ( let i = 0; i < parameters.length; i ++ ) {
  3729. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3730. }
  3731. } else {
  3732. for ( const inputNode of inputs ) {
  3733. const node = parameters[ inputNode.name ];
  3734. if ( node !== undefined ) {
  3735. params.push( generateInput( node, inputNode ) );
  3736. } else {
  3737. console.error( `THREE.TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3738. params.push( generateInput( float( 0 ), inputNode ) );
  3739. }
  3740. }
  3741. }
  3742. const functionName = functionNode.build( builder, 'property' );
  3743. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3744. }
  3745. }
  3746. const call = ( func, ...params ) => {
  3747. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3748. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3749. };
  3750. addMethodChaining( 'call', call );
  3751. const _vectorOperators = {
  3752. '==': 'equal',
  3753. '!=': 'notEqual',
  3754. '<': 'lessThan',
  3755. '>': 'greaterThan',
  3756. '<=': 'lessThanEqual',
  3757. '>=': 'greaterThanEqual',
  3758. '%': 'mod'
  3759. };
  3760. /**
  3761. * This node represents basic mathematical and logical operations like addition,
  3762. * subtraction or comparisons (e.g. `equal()`).
  3763. *
  3764. * @augments TempNode
  3765. */
  3766. class OperatorNode extends TempNode {
  3767. static get type() {
  3768. return 'OperatorNode';
  3769. }
  3770. /**
  3771. * Constructs a new operator node.
  3772. *
  3773. * @param {string} op - The operator.
  3774. * @param {Node} aNode - The first input.
  3775. * @param {Node} bNode - The second input.
  3776. * @param {...Node} params - Additional input parameters.
  3777. */
  3778. constructor( op, aNode, bNode, ...params ) {
  3779. super();
  3780. if ( params.length > 0 ) {
  3781. let finalOp = new OperatorNode( op, aNode, bNode );
  3782. for ( let i = 0; i < params.length - 1; i ++ ) {
  3783. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3784. }
  3785. aNode = finalOp;
  3786. bNode = params[ params.length - 1 ];
  3787. }
  3788. /**
  3789. * The operator.
  3790. *
  3791. * @type {string}
  3792. */
  3793. this.op = op;
  3794. /**
  3795. * The first input.
  3796. *
  3797. * @type {Node}
  3798. */
  3799. this.aNode = aNode;
  3800. /**
  3801. * The second input.
  3802. *
  3803. * @type {Node}
  3804. */
  3805. this.bNode = bNode;
  3806. /**
  3807. * This flag can be used for type testing.
  3808. *
  3809. * @type {boolean}
  3810. * @readonly
  3811. * @default true
  3812. */
  3813. this.isOperatorNode = true;
  3814. }
  3815. /**
  3816. * Returns the operator method name.
  3817. *
  3818. * @param {NodeBuilder} builder - The current node builder.
  3819. * @param {string} output - The output type.
  3820. * @returns {string} The operator method name.
  3821. */
  3822. getOperatorMethod( builder, output ) {
  3823. return builder.getMethod( _vectorOperators[ this.op ], output );
  3824. }
  3825. /**
  3826. * This method is overwritten since the node type is inferred from the operator
  3827. * and the input node types.
  3828. *
  3829. * @param {NodeBuilder} builder - The current node builder.
  3830. * @param {?string} [output=null] - The output type.
  3831. * @return {string} The node type.
  3832. */
  3833. getNodeType( builder, output = null ) {
  3834. const op = this.op;
  3835. const aNode = this.aNode;
  3836. const bNode = this.bNode;
  3837. const typeA = aNode.getNodeType( builder );
  3838. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3839. if ( typeA === 'void' || typeB === 'void' ) {
  3840. return output || 'void';
  3841. } else if ( op === '%' ) {
  3842. return typeA;
  3843. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3844. return builder.getIntegerType( typeA );
  3845. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3846. return 'bool';
  3847. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3848. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3849. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3850. } else {
  3851. // Handle matrix operations
  3852. if ( builder.isMatrix( typeA ) ) {
  3853. if ( typeB === 'float' ) {
  3854. return typeA; // matrix * scalar = matrix
  3855. } else if ( builder.isVector( typeB ) ) {
  3856. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3857. } else if ( builder.isMatrix( typeB ) ) {
  3858. return typeA; // matrix * matrix
  3859. }
  3860. } else if ( builder.isMatrix( typeB ) ) {
  3861. if ( typeA === 'float' ) {
  3862. return typeB; // scalar * matrix = matrix
  3863. } else if ( builder.isVector( typeA ) ) {
  3864. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3865. }
  3866. }
  3867. // Handle non-matrix cases
  3868. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3869. // anytype x anytype: use the greater length vector
  3870. return typeB;
  3871. }
  3872. return typeA;
  3873. }
  3874. }
  3875. generate( builder, output ) {
  3876. const op = this.op;
  3877. const { aNode, bNode } = this;
  3878. const type = this.getNodeType( builder, output );
  3879. let typeA = null;
  3880. let typeB = null;
  3881. if ( type !== 'void' ) {
  3882. typeA = aNode.getNodeType( builder );
  3883. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3884. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3885. if ( builder.isVector( typeA ) ) {
  3886. typeB = typeA;
  3887. } else if ( builder.isVector( typeB ) ) {
  3888. typeA = typeB;
  3889. } else if ( typeA !== typeB ) {
  3890. typeA = typeB = 'float';
  3891. }
  3892. } else if ( op === '>>' || op === '<<' ) {
  3893. typeA = type;
  3894. typeB = builder.changeComponentType( typeB, 'uint' );
  3895. } else if ( op === '%' ) {
  3896. typeA = type;
  3897. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3898. } else if ( builder.isMatrix( typeA ) ) {
  3899. if ( typeB === 'float' ) {
  3900. // Keep matrix type for typeA, but ensure typeB stays float
  3901. typeB = 'float';
  3902. } else if ( builder.isVector( typeB ) ) {
  3903. // matrix x vector
  3904. typeB = builder.getVectorFromMatrix( typeA );
  3905. } else if ( builder.isMatrix( typeB ) ) ; else {
  3906. typeA = typeB = type;
  3907. }
  3908. } else if ( builder.isMatrix( typeB ) ) {
  3909. if ( typeA === 'float' ) {
  3910. // Keep matrix type for typeB, but ensure typeA stays float
  3911. typeA = 'float';
  3912. } else if ( builder.isVector( typeA ) ) {
  3913. // vector x matrix
  3914. typeA = builder.getVectorFromMatrix( typeB );
  3915. } else {
  3916. typeA = typeB = type;
  3917. }
  3918. } else {
  3919. // anytype x anytype
  3920. typeA = typeB = type;
  3921. }
  3922. } else {
  3923. typeA = typeB = type;
  3924. }
  3925. const a = aNode.build( builder, typeA );
  3926. const b = bNode ? bNode.build( builder, typeB ) : null;
  3927. const fnOpSnippet = builder.getFunctionOperator( op );
  3928. if ( output !== 'void' ) {
  3929. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3930. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3931. if ( isGLSL ) {
  3932. if ( builder.isVector( typeA ) ) {
  3933. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3934. } else {
  3935. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3936. }
  3937. } else {
  3938. // WGSL
  3939. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3940. }
  3941. } else if ( op === '%' ) {
  3942. if ( builder.isInteger( typeB ) ) {
  3943. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3944. } else {
  3945. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3946. }
  3947. } else if ( op === '!' || op === '~' ) {
  3948. return builder.format( `(${op}${a})`, typeA, output );
  3949. } else if ( fnOpSnippet ) {
  3950. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3951. } else {
  3952. // Handle matrix operations
  3953. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3954. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3955. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3956. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3957. } else {
  3958. let snippet = `( ${ a } ${ op } ${ b } )`;
  3959. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  3960. snippet = `all${ snippet }`;
  3961. }
  3962. return builder.format( snippet, type, output );
  3963. }
  3964. }
  3965. } else if ( typeA !== 'void' ) {
  3966. if ( fnOpSnippet ) {
  3967. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3968. } else {
  3969. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3970. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3971. } else {
  3972. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3973. }
  3974. }
  3975. }
  3976. }
  3977. serialize( data ) {
  3978. super.serialize( data );
  3979. data.op = this.op;
  3980. }
  3981. deserialize( data ) {
  3982. super.deserialize( data );
  3983. this.op = data.op;
  3984. }
  3985. }
  3986. /**
  3987. * Returns the addition of two or more value.
  3988. *
  3989. * @tsl
  3990. * @function
  3991. * @param {Node} a - The first input.
  3992. * @param {Node} b - The second input.
  3993. * @param {...Node} params - Additional input parameters.
  3994. * @returns {OperatorNode}
  3995. */
  3996. const add = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  3997. /**
  3998. * Returns the subtraction of two or more value.
  3999. *
  4000. * @tsl
  4001. * @function
  4002. * @param {Node} a - The first input.
  4003. * @param {Node} b - The second input.
  4004. * @param {...Node} params - Additional input parameters.
  4005. * @returns {OperatorNode}
  4006. */
  4007. const sub = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  4008. /**
  4009. * Returns the multiplication of two or more value.
  4010. *
  4011. * @tsl
  4012. * @function
  4013. * @param {Node} a - The first input.
  4014. * @param {Node} b - The second input.
  4015. * @param {...Node} params - Additional input parameters.
  4016. * @returns {OperatorNode}
  4017. */
  4018. const mul = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  4019. /**
  4020. * Returns the division of two or more value.
  4021. *
  4022. * @tsl
  4023. * @function
  4024. * @param {Node} a - The first input.
  4025. * @param {Node} b - The second input.
  4026. * @param {...Node} params - Additional input parameters.
  4027. * @returns {OperatorNode}
  4028. */
  4029. const div = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  4030. /**
  4031. * Computes the remainder of dividing the first node by the second one.
  4032. *
  4033. * @tsl
  4034. * @function
  4035. * @param {Node} a - The first input.
  4036. * @param {Node} b - The second input.
  4037. * @returns {OperatorNode}
  4038. */
  4039. const mod = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  4040. /**
  4041. * Checks if two nodes are equal.
  4042. *
  4043. * @tsl
  4044. * @function
  4045. * @param {Node} a - The first input.
  4046. * @param {Node} b - The second input.
  4047. * @returns {OperatorNode}
  4048. */
  4049. const equal = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  4050. /**
  4051. * Checks if two nodes are not equal.
  4052. *
  4053. * @tsl
  4054. * @function
  4055. * @param {Node} a - The first input.
  4056. * @param {Node} b - The second input.
  4057. * @returns {OperatorNode}
  4058. */
  4059. const notEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  4060. /**
  4061. * Checks if the first node is less than the second.
  4062. *
  4063. * @tsl
  4064. * @function
  4065. * @param {Node} a - The first input.
  4066. * @param {Node} b - The second input.
  4067. * @returns {OperatorNode}
  4068. */
  4069. const lessThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  4070. /**
  4071. * Checks if the first node is greater than the second.
  4072. *
  4073. * @tsl
  4074. * @function
  4075. * @param {Node} a - The first input.
  4076. * @param {Node} b - The second input.
  4077. * @returns {OperatorNode}
  4078. */
  4079. const greaterThan = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  4080. /**
  4081. * Checks if the first node is less than or equal to the second.
  4082. *
  4083. * @tsl
  4084. * @function
  4085. * @param {Node} a - The first input.
  4086. * @param {Node} b - The second input.
  4087. * @returns {OperatorNode}
  4088. */
  4089. const lessThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  4090. /**
  4091. * Checks if the first node is greater than or equal to the second.
  4092. *
  4093. * @tsl
  4094. * @function
  4095. * @param {Node} a - The first input.
  4096. * @param {Node} b - The second input.
  4097. * @returns {OperatorNode}
  4098. */
  4099. const greaterThanEqual = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  4100. /**
  4101. * Performs a logical AND operation on multiple nodes.
  4102. *
  4103. * @tsl
  4104. * @function
  4105. * @param {...Node} nodes - The input nodes to be combined using AND.
  4106. * @returns {OperatorNode}
  4107. */
  4108. const and = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  4109. /**
  4110. * Performs a logical OR operation on multiple nodes.
  4111. *
  4112. * @tsl
  4113. * @function
  4114. * @param {...Node} nodes - The input nodes to be combined using OR.
  4115. * @returns {OperatorNode}
  4116. */
  4117. const or = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  4118. /**
  4119. * Performs logical NOT on a node.
  4120. *
  4121. * @tsl
  4122. * @function
  4123. * @param {Node} value - The value.
  4124. * @returns {OperatorNode}
  4125. */
  4126. const not = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  4127. /**
  4128. * Performs logical XOR on two nodes.
  4129. *
  4130. * @tsl
  4131. * @function
  4132. * @param {Node} a - The first input.
  4133. * @param {Node} b - The second input.
  4134. * @returns {OperatorNode}
  4135. */
  4136. const xor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  4137. /**
  4138. * Performs bitwise AND on two nodes.
  4139. *
  4140. * @tsl
  4141. * @function
  4142. * @param {Node} a - The first input.
  4143. * @param {Node} b - The second input.
  4144. * @returns {OperatorNode}
  4145. */
  4146. const bitAnd = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  4147. /**
  4148. * Performs bitwise NOT on a node.
  4149. *
  4150. * @tsl
  4151. * @function
  4152. * @param {Node} a - The first input.
  4153. * @param {Node} b - The second input.
  4154. * @returns {OperatorNode}
  4155. */
  4156. const bitNot = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '~' ).setParameterLength( 2 ).setName( 'bitNot' );
  4157. /**
  4158. * Performs bitwise OR on two nodes.
  4159. *
  4160. * @tsl
  4161. * @function
  4162. * @param {Node} a - The first input.
  4163. * @param {Node} b - The second input.
  4164. * @returns {OperatorNode}
  4165. */
  4166. const bitOr = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  4167. /**
  4168. * Performs bitwise XOR on two nodes.
  4169. *
  4170. * @tsl
  4171. * @function
  4172. * @param {Node} a - The first input.
  4173. * @param {Node} b - The second input.
  4174. * @returns {OperatorNode}
  4175. */
  4176. const bitXor = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  4177. /**
  4178. * Shifts a node to the left.
  4179. *
  4180. * @tsl
  4181. * @function
  4182. * @param {Node} a - The node to shift.
  4183. * @param {Node} b - The value to shift.
  4184. * @returns {OperatorNode}
  4185. */
  4186. const shiftLeft = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  4187. /**
  4188. * Shifts a node to the right.
  4189. *
  4190. * @tsl
  4191. * @function
  4192. * @param {Node} a - The node to shift.
  4193. * @param {Node} b - The value to shift.
  4194. * @returns {OperatorNode}
  4195. */
  4196. const shiftRight = /*@__PURE__*/ nodeProxyIntent( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  4197. /**
  4198. * Increments a node by 1.
  4199. *
  4200. * @tsl
  4201. * @function
  4202. * @param {Node} a - The node to increment.
  4203. * @returns {OperatorNode}
  4204. */
  4205. const incrementBefore = Fn( ( [ a ] ) => {
  4206. a.addAssign( 1 );
  4207. return a;
  4208. } );
  4209. /**
  4210. * Decrements a node by 1.
  4211. *
  4212. * @tsl
  4213. * @function
  4214. * @param {Node} a - The node to decrement.
  4215. * @returns {OperatorNode}
  4216. */
  4217. const decrementBefore = Fn( ( [ a ] ) => {
  4218. a.subAssign( 1 );
  4219. return a;
  4220. } );
  4221. /**
  4222. * Increments a node by 1 and returns the previous value.
  4223. *
  4224. * @tsl
  4225. * @function
  4226. * @param {Node} a - The node to increment.
  4227. * @returns {OperatorNode}
  4228. */
  4229. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4230. const temp = int( a ).toConst();
  4231. a.addAssign( 1 );
  4232. return temp;
  4233. } );
  4234. /**
  4235. * Decrements a node by 1 and returns the previous value.
  4236. *
  4237. * @tsl
  4238. * @function
  4239. * @param {Node} a - The node to decrement.
  4240. * @returns {OperatorNode}
  4241. */
  4242. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  4243. const temp = int( a ).toConst();
  4244. a.subAssign( 1 );
  4245. return temp;
  4246. } );
  4247. addMethodChaining( 'add', add );
  4248. addMethodChaining( 'sub', sub );
  4249. addMethodChaining( 'mul', mul );
  4250. addMethodChaining( 'div', div );
  4251. addMethodChaining( 'mod', mod );
  4252. addMethodChaining( 'equal', equal );
  4253. addMethodChaining( 'notEqual', notEqual );
  4254. addMethodChaining( 'lessThan', lessThan );
  4255. addMethodChaining( 'greaterThan', greaterThan );
  4256. addMethodChaining( 'lessThanEqual', lessThanEqual );
  4257. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  4258. addMethodChaining( 'and', and );
  4259. addMethodChaining( 'or', or );
  4260. addMethodChaining( 'not', not );
  4261. addMethodChaining( 'xor', xor );
  4262. addMethodChaining( 'bitAnd', bitAnd );
  4263. addMethodChaining( 'bitNot', bitNot );
  4264. addMethodChaining( 'bitOr', bitOr );
  4265. addMethodChaining( 'bitXor', bitXor );
  4266. addMethodChaining( 'shiftLeft', shiftLeft );
  4267. addMethodChaining( 'shiftRight', shiftRight );
  4268. addMethodChaining( 'incrementBefore', incrementBefore );
  4269. addMethodChaining( 'decrementBefore', decrementBefore );
  4270. addMethodChaining( 'increment', increment );
  4271. addMethodChaining( 'decrement', decrement );
  4272. /**
  4273. * @tsl
  4274. * @function
  4275. * @deprecated since r175. Use {@link mod} instead.
  4276. *
  4277. * @param {Node} a - The first input.
  4278. * @param {Node} b - The second input.
  4279. * @returns {OperatorNode}
  4280. */
  4281. const modInt = ( a, b ) => { // @deprecated, r175
  4282. console.warn( 'THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  4283. return mod( int( a ), int( b ) );
  4284. };
  4285. addMethodChaining( 'modInt', modInt );
  4286. /**
  4287. * This node represents a variety of mathematical methods available in shaders.
  4288. * They are divided into three categories:
  4289. *
  4290. * - Methods with one input like `sin`, `cos` or `normalize`.
  4291. * - Methods with two inputs like `dot`, `cross` or `pow`.
  4292. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  4293. *
  4294. * @augments TempNode
  4295. */
  4296. class MathNode extends TempNode {
  4297. static get type() {
  4298. return 'MathNode';
  4299. }
  4300. /**
  4301. * Constructs a new math node.
  4302. *
  4303. * @param {string} method - The method name.
  4304. * @param {Node} aNode - The first input.
  4305. * @param {?Node} [bNode=null] - The second input.
  4306. * @param {?Node} [cNode=null] - The third input.
  4307. */
  4308. constructor( method, aNode, bNode = null, cNode = null ) {
  4309. super();
  4310. // Allow the max() and min() functions to take an arbitrary number of arguments.
  4311. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  4312. let finalOp = new MathNode( method, aNode, bNode );
  4313. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4314. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4315. }
  4316. aNode = finalOp;
  4317. bNode = arguments[ arguments.length - 1 ];
  4318. cNode = null;
  4319. }
  4320. /**
  4321. * The method name.
  4322. *
  4323. * @type {string}
  4324. */
  4325. this.method = method;
  4326. /**
  4327. * The first input.
  4328. *
  4329. * @type {Node}
  4330. */
  4331. this.aNode = aNode;
  4332. /**
  4333. * The second input.
  4334. *
  4335. * @type {?Node}
  4336. * @default null
  4337. */
  4338. this.bNode = bNode;
  4339. /**
  4340. * The third input.
  4341. *
  4342. * @type {?Node}
  4343. * @default null
  4344. */
  4345. this.cNode = cNode;
  4346. /**
  4347. * This flag can be used for type testing.
  4348. *
  4349. * @type {boolean}
  4350. * @readonly
  4351. * @default true
  4352. */
  4353. this.isMathNode = true;
  4354. }
  4355. /**
  4356. * The input type is inferred from the node types of the input nodes.
  4357. *
  4358. * @param {NodeBuilder} builder - The current node builder.
  4359. * @return {string} The input type.
  4360. */
  4361. getInputType( builder ) {
  4362. const aType = this.aNode.getNodeType( builder );
  4363. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4364. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4365. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4366. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4367. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4368. if ( aLen > bLen && aLen > cLen ) {
  4369. return aType;
  4370. } else if ( bLen > cLen ) {
  4371. return bType;
  4372. } else if ( cLen > aLen ) {
  4373. return cType;
  4374. }
  4375. return aType;
  4376. }
  4377. /**
  4378. * The selected method as well as the input type determine the node type of this node.
  4379. *
  4380. * @param {NodeBuilder} builder - The current node builder.
  4381. * @return {string} The node type.
  4382. */
  4383. getNodeType( builder ) {
  4384. const method = this.method;
  4385. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4386. return 'float';
  4387. } else if ( method === MathNode.CROSS ) {
  4388. return 'vec3';
  4389. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4390. return 'bool';
  4391. } else if ( method === MathNode.EQUALS ) {
  4392. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4393. } else {
  4394. return this.getInputType( builder );
  4395. }
  4396. }
  4397. setup( builder ) {
  4398. const { aNode, bNode, method } = this;
  4399. let outputNode = null;
  4400. if ( method === MathNode.ONE_MINUS ) {
  4401. outputNode = sub( 1.0, aNode );
  4402. } else if ( method === MathNode.RECIPROCAL ) {
  4403. outputNode = div( 1.0, aNode );
  4404. } else if ( method === MathNode.DIFFERENCE ) {
  4405. outputNode = abs( sub( aNode, bNode ) );
  4406. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4407. // dir can be either a direction vector or a normal vector
  4408. // upper-left 3x3 of matrix is assumed to be orthogonal
  4409. let tA = aNode;
  4410. let tB = bNode;
  4411. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4412. tB = vec4( vec3( tB ), 0.0 );
  4413. } else {
  4414. tA = vec4( vec3( tA ), 0.0 );
  4415. }
  4416. const mulNode = mul( tA, tB ).xyz;
  4417. outputNode = normalize( mulNode );
  4418. }
  4419. if ( outputNode !== null ) {
  4420. return outputNode;
  4421. } else {
  4422. return super.setup( builder );
  4423. }
  4424. }
  4425. generate( builder, output ) {
  4426. const properties = builder.getNodeProperties( this );
  4427. if ( properties.outputNode ) {
  4428. return super.generate( builder, output );
  4429. }
  4430. let method = this.method;
  4431. const type = this.getNodeType( builder );
  4432. const inputType = this.getInputType( builder );
  4433. const a = this.aNode;
  4434. const b = this.bNode;
  4435. const c = this.cNode;
  4436. const coordinateSystem = builder.renderer.coordinateSystem;
  4437. if ( method === MathNode.NEGATE ) {
  4438. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4439. } else {
  4440. const params = [];
  4441. if ( method === MathNode.CROSS ) {
  4442. params.push(
  4443. a.build( builder, type ),
  4444. b.build( builder, type )
  4445. );
  4446. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4447. params.push(
  4448. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4449. b.build( builder, inputType )
  4450. );
  4451. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4452. params.push(
  4453. a.build( builder, inputType ),
  4454. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4455. );
  4456. } else if ( method === MathNode.REFRACT ) {
  4457. params.push(
  4458. a.build( builder, inputType ),
  4459. b.build( builder, inputType ),
  4460. c.build( builder, 'float' )
  4461. );
  4462. } else if ( method === MathNode.MIX ) {
  4463. params.push(
  4464. a.build( builder, inputType ),
  4465. b.build( builder, inputType ),
  4466. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4467. );
  4468. } else {
  4469. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4470. method = 'atan2';
  4471. }
  4472. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4473. console.warn( `THREE.TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4474. method = '/*' + method + '*/';
  4475. }
  4476. params.push( a.build( builder, inputType ) );
  4477. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4478. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4479. }
  4480. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4481. }
  4482. }
  4483. serialize( data ) {
  4484. super.serialize( data );
  4485. data.method = this.method;
  4486. }
  4487. deserialize( data ) {
  4488. super.deserialize( data );
  4489. this.method = data.method;
  4490. }
  4491. }
  4492. // 1 input
  4493. MathNode.ALL = 'all';
  4494. MathNode.ANY = 'any';
  4495. MathNode.RADIANS = 'radians';
  4496. MathNode.DEGREES = 'degrees';
  4497. MathNode.EXP = 'exp';
  4498. MathNode.EXP2 = 'exp2';
  4499. MathNode.LOG = 'log';
  4500. MathNode.LOG2 = 'log2';
  4501. MathNode.SQRT = 'sqrt';
  4502. MathNode.INVERSE_SQRT = 'inversesqrt';
  4503. MathNode.FLOOR = 'floor';
  4504. MathNode.CEIL = 'ceil';
  4505. MathNode.NORMALIZE = 'normalize';
  4506. MathNode.FRACT = 'fract';
  4507. MathNode.SIN = 'sin';
  4508. MathNode.COS = 'cos';
  4509. MathNode.TAN = 'tan';
  4510. MathNode.ASIN = 'asin';
  4511. MathNode.ACOS = 'acos';
  4512. MathNode.ATAN = 'atan';
  4513. MathNode.ABS = 'abs';
  4514. MathNode.SIGN = 'sign';
  4515. MathNode.LENGTH = 'length';
  4516. MathNode.NEGATE = 'negate';
  4517. MathNode.ONE_MINUS = 'oneMinus';
  4518. MathNode.DFDX = 'dFdx';
  4519. MathNode.DFDY = 'dFdy';
  4520. MathNode.ROUND = 'round';
  4521. MathNode.RECIPROCAL = 'reciprocal';
  4522. MathNode.TRUNC = 'trunc';
  4523. MathNode.FWIDTH = 'fwidth';
  4524. MathNode.TRANSPOSE = 'transpose';
  4525. MathNode.DETERMINANT = 'determinant';
  4526. MathNode.INVERSE = 'inverse';
  4527. // 2 inputs
  4528. MathNode.EQUALS = 'equals';
  4529. MathNode.MIN = 'min';
  4530. MathNode.MAX = 'max';
  4531. MathNode.STEP = 'step';
  4532. MathNode.REFLECT = 'reflect';
  4533. MathNode.DISTANCE = 'distance';
  4534. MathNode.DIFFERENCE = 'difference';
  4535. MathNode.DOT = 'dot';
  4536. MathNode.CROSS = 'cross';
  4537. MathNode.POW = 'pow';
  4538. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4539. // 3 inputs
  4540. MathNode.MIX = 'mix';
  4541. MathNode.CLAMP = 'clamp';
  4542. MathNode.REFRACT = 'refract';
  4543. MathNode.SMOOTHSTEP = 'smoothstep';
  4544. MathNode.FACEFORWARD = 'faceforward';
  4545. // 1 inputs
  4546. /**
  4547. * A small value used to handle floating-point precision errors.
  4548. *
  4549. * @tsl
  4550. * @type {Node<float>}
  4551. */
  4552. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4553. /**
  4554. * Represents infinity.
  4555. *
  4556. * @tsl
  4557. * @type {Node<float>}
  4558. */
  4559. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4560. /**
  4561. * Represents PI.
  4562. *
  4563. * @tsl
  4564. * @type {Node<float>}
  4565. */
  4566. const PI = /*@__PURE__*/ float( Math.PI );
  4567. /**
  4568. * Represents PI * 2.
  4569. *
  4570. * @tsl
  4571. * @type {Node<float>}
  4572. */
  4573. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  4574. /**
  4575. * Returns `true` if all components of `x` are `true`.
  4576. *
  4577. * @tsl
  4578. * @function
  4579. * @param {Node | number} x - The parameter.
  4580. * @returns {Node<bool>}
  4581. */
  4582. const all = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4583. /**
  4584. * Returns `true` if any components of `x` are `true`.
  4585. *
  4586. * @tsl
  4587. * @function
  4588. * @param {Node | number} x - The parameter.
  4589. * @returns {Node<bool>}
  4590. */
  4591. const any = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4592. /**
  4593. * Converts a quantity in degrees to radians.
  4594. *
  4595. * @tsl
  4596. * @function
  4597. * @param {Node | number} x - The input in degrees.
  4598. * @returns {Node}
  4599. */
  4600. const radians = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4601. /**
  4602. * Convert a quantity in radians to degrees.
  4603. *
  4604. * @tsl
  4605. * @function
  4606. * @param {Node | number} x - The input in radians.
  4607. * @returns {Node}
  4608. */
  4609. const degrees = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4610. /**
  4611. * Returns the natural exponentiation of the parameter.
  4612. *
  4613. * @tsl
  4614. * @function
  4615. * @param {Node | number} x - The parameter.
  4616. * @returns {Node}
  4617. */
  4618. const exp = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4619. /**
  4620. * Returns 2 raised to the power of the parameter.
  4621. *
  4622. * @tsl
  4623. * @function
  4624. * @param {Node | number} x - The parameter.
  4625. * @returns {Node}
  4626. */
  4627. const exp2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4628. /**
  4629. * Returns the natural logarithm of the parameter.
  4630. *
  4631. * @tsl
  4632. * @function
  4633. * @param {Node | number} x - The parameter.
  4634. * @returns {Node}
  4635. */
  4636. const log = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4637. /**
  4638. * Returns the base 2 logarithm of the parameter.
  4639. *
  4640. * @tsl
  4641. * @function
  4642. * @param {Node | number} x - The parameter.
  4643. * @returns {Node}
  4644. */
  4645. const log2 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4646. /**
  4647. * Returns the square root of the parameter.
  4648. *
  4649. * @tsl
  4650. * @function
  4651. * @param {Node | number} x - The parameter.
  4652. * @returns {Node}
  4653. */
  4654. const sqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4655. /**
  4656. * Returns the inverse of the square root of the parameter.
  4657. *
  4658. * @tsl
  4659. * @function
  4660. * @param {Node | number} x - The parameter.
  4661. * @returns {Node}
  4662. */
  4663. const inverseSqrt = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4664. /**
  4665. * Finds the nearest integer less than or equal to the parameter.
  4666. *
  4667. * @tsl
  4668. * @function
  4669. * @param {Node | number} x - The parameter.
  4670. * @returns {Node}
  4671. */
  4672. const floor = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4673. /**
  4674. * Finds the nearest integer that is greater than or equal to the parameter.
  4675. *
  4676. * @tsl
  4677. * @function
  4678. * @param {Node | number} x - The parameter.
  4679. * @returns {Node}
  4680. */
  4681. const ceil = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4682. /**
  4683. * Calculates the unit vector in the same direction as the original vector.
  4684. *
  4685. * @tsl
  4686. * @function
  4687. * @param {Node} x - The input vector.
  4688. * @returns {Node}
  4689. */
  4690. const normalize = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4691. /**
  4692. * Computes the fractional part of the parameter.
  4693. *
  4694. * @tsl
  4695. * @function
  4696. * @param {Node | number} x - The parameter.
  4697. * @returns {Node}
  4698. */
  4699. const fract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4700. /**
  4701. * Returns the sine of the parameter.
  4702. *
  4703. * @tsl
  4704. * @function
  4705. * @param {Node | number} x - The parameter.
  4706. * @returns {Node}
  4707. */
  4708. const sin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4709. /**
  4710. * Returns the cosine of the parameter.
  4711. *
  4712. * @tsl
  4713. * @function
  4714. * @param {Node | number} x - The parameter.
  4715. * @returns {Node}
  4716. */
  4717. const cos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.COS ).setParameterLength( 1 );
  4718. /**
  4719. * Returns the tangent of the parameter.
  4720. *
  4721. * @tsl
  4722. * @function
  4723. * @param {Node | number} x - The parameter.
  4724. * @returns {Node}
  4725. */
  4726. const tan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4727. /**
  4728. * Returns the arcsine of the parameter.
  4729. *
  4730. * @tsl
  4731. * @function
  4732. * @param {Node | number} x - The parameter.
  4733. * @returns {Node}
  4734. */
  4735. const asin = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4736. /**
  4737. * Returns the arccosine of the parameter.
  4738. *
  4739. * @tsl
  4740. * @function
  4741. * @param {Node | number} x - The parameter.
  4742. * @returns {Node}
  4743. */
  4744. const acos = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4745. /**
  4746. * Returns the arc-tangent of the parameter.
  4747. * If two parameters are provided, the result is `atan2(y/x)`.
  4748. *
  4749. * @tsl
  4750. * @function
  4751. * @param {Node | number} y - The y parameter.
  4752. * @param {?(Node | number)} x - The x parameter.
  4753. * @returns {Node}
  4754. */
  4755. const atan = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4756. /**
  4757. * Returns the absolute value of the parameter.
  4758. *
  4759. * @tsl
  4760. * @function
  4761. * @param {Node | number} x - The parameter.
  4762. * @returns {Node}
  4763. */
  4764. const abs = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4765. /**
  4766. * Extracts the sign of the parameter.
  4767. *
  4768. * @tsl
  4769. * @function
  4770. * @param {Node | number} x - The parameter.
  4771. * @returns {Node}
  4772. */
  4773. const sign = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4774. /**
  4775. * Calculates the length of a vector.
  4776. *
  4777. * @tsl
  4778. * @function
  4779. * @param {Node} x - The parameter.
  4780. * @returns {Node<float>}
  4781. */
  4782. const length = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4783. /**
  4784. * Negates the value of the parameter (-x).
  4785. *
  4786. * @tsl
  4787. * @function
  4788. * @param {Node | number} x - The parameter.
  4789. * @returns {Node}
  4790. */
  4791. const negate = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4792. /**
  4793. * Return `1` minus the parameter.
  4794. *
  4795. * @tsl
  4796. * @function
  4797. * @param {Node | number} x - The parameter.
  4798. * @returns {Node}
  4799. */
  4800. const oneMinus = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4801. /**
  4802. * Returns the partial derivative of the parameter with respect to x.
  4803. *
  4804. * @tsl
  4805. * @function
  4806. * @param {Node | number} x - The parameter.
  4807. * @returns {Node}
  4808. */
  4809. const dFdx = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4810. /**
  4811. * Returns the partial derivative of the parameter with respect to y.
  4812. *
  4813. * @tsl
  4814. * @function
  4815. * @param {Node | number} x - The parameter.
  4816. * @returns {Node}
  4817. */
  4818. const dFdy = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4819. /**
  4820. * Rounds the parameter to the nearest integer.
  4821. *
  4822. * @tsl
  4823. * @function
  4824. * @param {Node | number} x - The parameter.
  4825. * @returns {Node}
  4826. */
  4827. const round = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4828. /**
  4829. * Returns the reciprocal of the parameter `(1/x)`.
  4830. *
  4831. * @tsl
  4832. * @function
  4833. * @param {Node | number} x - The parameter.
  4834. * @returns {Node}
  4835. */
  4836. const reciprocal = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4837. /**
  4838. * Truncates the parameter, removing the fractional part.
  4839. *
  4840. * @tsl
  4841. * @function
  4842. * @param {Node | number} x - The parameter.
  4843. * @returns {Node}
  4844. */
  4845. const trunc = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4846. /**
  4847. * Returns the sum of the absolute derivatives in x and y.
  4848. *
  4849. * @tsl
  4850. * @function
  4851. * @param {Node | number} x - The parameter.
  4852. * @returns {Node}
  4853. */
  4854. const fwidth = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4855. /**
  4856. * Returns the transpose of a matrix.
  4857. *
  4858. * @tsl
  4859. * @function
  4860. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4861. * @returns {Node}
  4862. */
  4863. const transpose = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4864. /**
  4865. * Returns the determinant of a matrix.
  4866. *
  4867. * @tsl
  4868. * @function
  4869. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4870. * @returns {Node<float>}
  4871. */
  4872. const determinant = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DETERMINANT ).setParameterLength( 1 );
  4873. /**
  4874. * Returns the inverse of a matrix.
  4875. *
  4876. * @tsl
  4877. * @function
  4878. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4879. * @returns {Node<mat2|mat3|mat4>}
  4880. */
  4881. const inverse = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.INVERSE ).setParameterLength( 1 );
  4882. // 2 inputs
  4883. /**
  4884. * Returns `true` if `x` equals `y`.
  4885. *
  4886. * @tsl
  4887. * @function
  4888. * @param {Node | number} x - The first parameter.
  4889. * @param {Node | number} y - The second parameter.
  4890. * @deprecated since r175. Use {@link equal} instead.
  4891. * @returns {Node<bool>}
  4892. */
  4893. const equals = ( x, y ) => { // @deprecated, r172
  4894. console.warn( 'THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4895. return equal( x, y );
  4896. };
  4897. /**
  4898. * Returns the least of the given values.
  4899. *
  4900. * @tsl
  4901. * @function
  4902. * @param {...(Node | number)} values - The values to compare.
  4903. * @returns {Node}
  4904. */
  4905. const min$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4906. /**
  4907. * Returns the greatest of the given values.
  4908. *
  4909. * @tsl
  4910. * @function
  4911. * @param {...(Node | number)} values - The values to compare.
  4912. * @returns {Node}
  4913. */
  4914. const max$1 = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4915. /**
  4916. * Generate a step function by comparing two values.
  4917. *
  4918. * @tsl
  4919. * @function
  4920. * @param {Node | number} x - The y parameter.
  4921. * @param {Node | number} y - The x parameter.
  4922. * @returns {Node}
  4923. */
  4924. const step = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4925. /**
  4926. * Calculates the reflection direction for an incident vector.
  4927. *
  4928. * @tsl
  4929. * @function
  4930. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4931. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4932. * @returns {Node<vec2|vec3|vec4>}
  4933. */
  4934. const reflect = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  4935. /**
  4936. * Calculates the distance between two points.
  4937. *
  4938. * @tsl
  4939. * @function
  4940. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4941. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4942. * @returns {Node<float>}
  4943. */
  4944. const distance = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  4945. /**
  4946. * Calculates the absolute difference between two values.
  4947. *
  4948. * @tsl
  4949. * @function
  4950. * @param {Node | number} x - The first parameter.
  4951. * @param {Node | number} y - The second parameter.
  4952. * @returns {Node}
  4953. */
  4954. const difference = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  4955. /**
  4956. * Calculates the dot product of two vectors.
  4957. *
  4958. * @tsl
  4959. * @function
  4960. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4961. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4962. * @returns {Node<float>}
  4963. */
  4964. const dot = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.DOT ).setParameterLength( 2 );
  4965. /**
  4966. * Calculates the cross product of two vectors.
  4967. *
  4968. * @tsl
  4969. * @function
  4970. * @param {Node<vec2|vec3>} x - The first vector.
  4971. * @param {Node<vec2|vec3>} y - The second vector.
  4972. * @returns {Node<float|vec3>}
  4973. */
  4974. const cross = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  4975. /**
  4976. * Return the value of the first parameter raised to the power of the second one.
  4977. *
  4978. * @tsl
  4979. * @function
  4980. * @param {Node | number} x - The first parameter.
  4981. * @param {Node | number} y - The second parameter.
  4982. * @returns {Node}
  4983. */
  4984. const pow = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.POW ).setParameterLength( 2 );
  4985. /**
  4986. * Returns the square of the parameter.
  4987. *
  4988. * @tsl
  4989. * @function
  4990. * @param {Node | number} x - The first parameter.
  4991. * @returns {Node}
  4992. */
  4993. const pow2 = ( x ) => mul( x, x );
  4994. /**
  4995. * Returns the cube of the parameter.
  4996. *
  4997. * @tsl
  4998. * @function
  4999. * @param {Node | number} x - The first parameter.
  5000. * @returns {Node}
  5001. */
  5002. const pow3 = ( x ) => mul( x, x, x );
  5003. /**
  5004. * Returns the fourth power of the parameter.
  5005. *
  5006. * @tsl
  5007. * @function
  5008. * @param {Node | number} x - The first parameter.
  5009. * @returns {Node}
  5010. */
  5011. const pow4 = ( x ) => mul( x, x, x, x );
  5012. /**
  5013. * Transforms the direction of a vector by a matrix and then normalizes the result.
  5014. *
  5015. * @tsl
  5016. * @function
  5017. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  5018. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  5019. * @returns {Node}
  5020. */
  5021. const transformDirection = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  5022. /**
  5023. * Returns the cube root of a number.
  5024. *
  5025. * @tsl
  5026. * @function
  5027. * @param {Node | number} a - The first parameter.
  5028. * @returns {Node}
  5029. */
  5030. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  5031. /**
  5032. * Calculate the squared length of a vector.
  5033. *
  5034. * @tsl
  5035. * @function
  5036. * @param {Node<vec2|vec3|vec4>} a - The vector.
  5037. * @returns {Node<float>}
  5038. */
  5039. const lengthSq = ( a ) => dot( a, a );
  5040. /**
  5041. * Linearly interpolates between two values.
  5042. *
  5043. * @tsl
  5044. * @function
  5045. * @param {Node | number} a - The first parameter.
  5046. * @param {Node | number} b - The second parameter.
  5047. * @param {Node | number} t - The interpolation value.
  5048. * @returns {Node}
  5049. */
  5050. const mix = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.MIX ).setParameterLength( 3 );
  5051. /**
  5052. * Constrains a value to lie between two further values.
  5053. *
  5054. * @tsl
  5055. * @function
  5056. * @param {Node | number} value - The value to constrain.
  5057. * @param {Node | number} [low=0] - The lower bound.
  5058. * @param {Node | number} [high=1] - The upper bound.
  5059. * @returns {Node}
  5060. */
  5061. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  5062. /**
  5063. * Constrains a value between `0` and `1`.
  5064. *
  5065. * @tsl
  5066. * @function
  5067. * @param {Node | number} value - The value to constrain.
  5068. * @returns {Node}
  5069. */
  5070. const saturate = ( value ) => clamp( value );
  5071. /**
  5072. * Calculates the refraction direction for an incident vector.
  5073. *
  5074. * @tsl
  5075. * @function
  5076. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5077. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  5078. * @param {Node<float>} eta - The ratio of indices of refraction.
  5079. * @returns {Node<vec2|vec3|vec4>}
  5080. */
  5081. const refract = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  5082. /**
  5083. * Performs a Hermite interpolation between two values.
  5084. *
  5085. * @tsl
  5086. * @function
  5087. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5088. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5089. * @param {Node | number} x - The source value for interpolation.
  5090. * @returns {Node}
  5091. */
  5092. const smoothstep = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  5093. /**
  5094. * Returns a vector pointing in the same direction as another.
  5095. *
  5096. * @tsl
  5097. * @function
  5098. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  5099. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  5100. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  5101. * @returns {Node<vec2|vec3|vec4>}
  5102. */
  5103. const faceForward = /*@__PURE__*/ nodeProxyIntent( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  5104. /**
  5105. * Returns a random value for the given uv.
  5106. *
  5107. * @tsl
  5108. * @function
  5109. * @param {Node<vec2>} uv - The uv node.
  5110. * @returns {Node<float>}
  5111. */
  5112. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  5113. const a = 12.9898, b = 78.233, c = 43758.5453;
  5114. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  5115. return fract( sin( sn ).mul( c ) );
  5116. } );
  5117. /**
  5118. * Alias for `mix()` with a different parameter order.
  5119. *
  5120. * @tsl
  5121. * @function
  5122. * @param {Node | number} t - The interpolation value.
  5123. * @param {Node | number} e1 - The first parameter.
  5124. * @param {Node | number} e2 - The second parameter.
  5125. * @returns {Node}
  5126. */
  5127. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  5128. /**
  5129. * Alias for `smoothstep()` with a different parameter order.
  5130. *
  5131. * @tsl
  5132. * @function
  5133. * @param {Node | number} x - The source value for interpolation.
  5134. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  5135. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  5136. * @returns {Node}
  5137. */
  5138. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  5139. /**
  5140. * Alias for `step()` with a different parameter order.
  5141. *
  5142. * @tsl
  5143. * @function
  5144. * @param {Node | number} x - The source value for interpolation.
  5145. * @param {Node | number} edge - The edge value.
  5146. * @returns {Node}
  5147. */
  5148. const stepElement = ( x, edge ) => step( edge, x );
  5149. /**
  5150. * Returns the arc-tangent of the quotient of its parameters.
  5151. *
  5152. * @tsl
  5153. * @function
  5154. * @deprecated since r172. Use {@link atan} instead.
  5155. *
  5156. * @param {Node | number} y - The y parameter.
  5157. * @param {Node | number} x - The x parameter.
  5158. * @returns {Node}
  5159. */
  5160. const atan2 = ( y, x ) => { // @deprecated, r172
  5161. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  5162. return atan( y, x );
  5163. };
  5164. // GLSL alias function
  5165. const faceforward = faceForward;
  5166. const inversesqrt = inverseSqrt;
  5167. // Method chaining
  5168. addMethodChaining( 'all', all );
  5169. addMethodChaining( 'any', any );
  5170. addMethodChaining( 'equals', equals );
  5171. addMethodChaining( 'radians', radians );
  5172. addMethodChaining( 'degrees', degrees );
  5173. addMethodChaining( 'exp', exp );
  5174. addMethodChaining( 'exp2', exp2 );
  5175. addMethodChaining( 'log', log );
  5176. addMethodChaining( 'log2', log2 );
  5177. addMethodChaining( 'sqrt', sqrt );
  5178. addMethodChaining( 'inverseSqrt', inverseSqrt );
  5179. addMethodChaining( 'floor', floor );
  5180. addMethodChaining( 'ceil', ceil );
  5181. addMethodChaining( 'normalize', normalize );
  5182. addMethodChaining( 'fract', fract );
  5183. addMethodChaining( 'sin', sin );
  5184. addMethodChaining( 'cos', cos );
  5185. addMethodChaining( 'tan', tan );
  5186. addMethodChaining( 'asin', asin );
  5187. addMethodChaining( 'acos', acos );
  5188. addMethodChaining( 'atan', atan );
  5189. addMethodChaining( 'abs', abs );
  5190. addMethodChaining( 'sign', sign );
  5191. addMethodChaining( 'length', length );
  5192. addMethodChaining( 'lengthSq', lengthSq );
  5193. addMethodChaining( 'negate', negate );
  5194. addMethodChaining( 'oneMinus', oneMinus );
  5195. addMethodChaining( 'dFdx', dFdx );
  5196. addMethodChaining( 'dFdy', dFdy );
  5197. addMethodChaining( 'round', round );
  5198. addMethodChaining( 'reciprocal', reciprocal );
  5199. addMethodChaining( 'trunc', trunc );
  5200. addMethodChaining( 'fwidth', fwidth );
  5201. addMethodChaining( 'atan2', atan2 );
  5202. addMethodChaining( 'min', min$1 );
  5203. addMethodChaining( 'max', max$1 );
  5204. addMethodChaining( 'step', stepElement );
  5205. addMethodChaining( 'reflect', reflect );
  5206. addMethodChaining( 'distance', distance );
  5207. addMethodChaining( 'dot', dot );
  5208. addMethodChaining( 'cross', cross );
  5209. addMethodChaining( 'pow', pow );
  5210. addMethodChaining( 'pow2', pow2 );
  5211. addMethodChaining( 'pow3', pow3 );
  5212. addMethodChaining( 'pow4', pow4 );
  5213. addMethodChaining( 'transformDirection', transformDirection );
  5214. addMethodChaining( 'mix', mixElement );
  5215. addMethodChaining( 'clamp', clamp );
  5216. addMethodChaining( 'refract', refract );
  5217. addMethodChaining( 'smoothstep', smoothstepElement );
  5218. addMethodChaining( 'faceForward', faceForward );
  5219. addMethodChaining( 'difference', difference );
  5220. addMethodChaining( 'saturate', saturate );
  5221. addMethodChaining( 'cbrt', cbrt );
  5222. addMethodChaining( 'transpose', transpose );
  5223. addMethodChaining( 'determinant', determinant );
  5224. addMethodChaining( 'inverse', inverse );
  5225. addMethodChaining( 'rand', rand );
  5226. /**
  5227. * Represents a logical `if/else` statement. Can be used as an alternative
  5228. * to the `If()`/`Else()` syntax.
  5229. *
  5230. * The corresponding TSL `select()` looks like so:
  5231. * ```js
  5232. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  5233. * ```
  5234. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  5235. * determine the outcome of the entire statement.
  5236. *
  5237. * @augments Node
  5238. */
  5239. class ConditionalNode extends Node {
  5240. static get type() {
  5241. return 'ConditionalNode';
  5242. }
  5243. /**
  5244. * Constructs a new conditional node.
  5245. *
  5246. * @param {Node} condNode - The node that defines the condition.
  5247. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5248. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5249. */
  5250. constructor( condNode, ifNode, elseNode = null ) {
  5251. super();
  5252. /**
  5253. * The node that defines the condition.
  5254. *
  5255. * @type {Node}
  5256. */
  5257. this.condNode = condNode;
  5258. /**
  5259. * The node that is evaluate when the condition ends up `true`.
  5260. *
  5261. * @type {Node}
  5262. */
  5263. this.ifNode = ifNode;
  5264. /**
  5265. * The node that is evaluate when the condition ends up `false`.
  5266. *
  5267. * @type {?Node}
  5268. * @default null
  5269. */
  5270. this.elseNode = elseNode;
  5271. }
  5272. /**
  5273. * This method is overwritten since the node type is inferred from the if/else
  5274. * nodes.
  5275. *
  5276. * @param {NodeBuilder} builder - The current node builder.
  5277. * @return {string} The node type.
  5278. */
  5279. getNodeType( builder ) {
  5280. const { ifNode, elseNode } = builder.getNodeProperties( this );
  5281. if ( ifNode === undefined ) {
  5282. // fallback setup
  5283. builder.flowBuildStage( this, 'setup' );
  5284. return this.getNodeType( builder );
  5285. }
  5286. const ifType = ifNode.getNodeType( builder );
  5287. if ( elseNode !== null ) {
  5288. const elseType = elseNode.getNodeType( builder );
  5289. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  5290. return elseType;
  5291. }
  5292. }
  5293. return ifType;
  5294. }
  5295. setup( builder ) {
  5296. const condNode = this.condNode.cache();
  5297. const ifNode = this.ifNode.cache();
  5298. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  5299. //
  5300. const currentNodeBlock = builder.context.nodeBlock;
  5301. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  5302. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  5303. //
  5304. const isUniformFlow = builder.context.uniformFlow;
  5305. const properties = builder.getNodeProperties( this );
  5306. properties.condNode = condNode;
  5307. properties.ifNode = isUniformFlow ? ifNode : ifNode.context( { nodeBlock: ifNode } );
  5308. properties.elseNode = elseNode ? ( isUniformFlow ? elseNode : elseNode.context( { nodeBlock: elseNode } ) ) : null;
  5309. }
  5310. generate( builder, output ) {
  5311. const type = this.getNodeType( builder );
  5312. const nodeData = builder.getDataFromNode( this );
  5313. if ( nodeData.nodeProperty !== undefined ) {
  5314. return nodeData.nodeProperty;
  5315. }
  5316. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  5317. const functionNode = builder.currentFunctionNode;
  5318. const needsOutput = output !== 'void';
  5319. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  5320. nodeData.nodeProperty = nodeProperty;
  5321. const nodeSnippet = condNode.build( builder, 'bool' );
  5322. const isUniformFlow = builder.context.uniformFlow;
  5323. if ( isUniformFlow && elseNode !== null ) {
  5324. const ifSnippet = ifNode.build( builder, type );
  5325. const elseSnippet = elseNode.build( builder, type );
  5326. const mathSnippet = builder.getTernary( nodeSnippet, ifSnippet, elseSnippet );
  5327. // TODO: If node property already exists return something else
  5328. return builder.format( mathSnippet, type, output );
  5329. }
  5330. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  5331. let ifSnippet = ifNode.build( builder, type );
  5332. if ( ifSnippet ) {
  5333. if ( needsOutput ) {
  5334. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  5335. } else {
  5336. ifSnippet = 'return ' + ifSnippet + ';';
  5337. if ( functionNode === null ) {
  5338. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5339. ifSnippet = '// ' + ifSnippet;
  5340. }
  5341. }
  5342. }
  5343. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5344. if ( elseNode !== null ) {
  5345. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5346. let elseSnippet = elseNode.build( builder, type );
  5347. if ( elseSnippet ) {
  5348. if ( needsOutput ) {
  5349. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5350. } else {
  5351. elseSnippet = 'return ' + elseSnippet + ';';
  5352. if ( functionNode === null ) {
  5353. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5354. elseSnippet = '// ' + elseSnippet;
  5355. }
  5356. }
  5357. }
  5358. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5359. } else {
  5360. builder.addFlowCode( '\n\n' );
  5361. }
  5362. return builder.format( nodeProperty, type, output );
  5363. }
  5364. }
  5365. /**
  5366. * TSL function for creating a conditional node.
  5367. *
  5368. * @tsl
  5369. * @function
  5370. * @param {Node} condNode - The node that defines the condition.
  5371. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5372. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5373. * @returns {ConditionalNode}
  5374. */
  5375. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5376. addMethodChaining( 'select', select );
  5377. /**
  5378. * This node can be used as a context management component for another node.
  5379. * {@link NodeBuilder} performs its node building process in a specific context and
  5380. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5381. *
  5382. * ```js
  5383. *node.context( { getUV: () => customCoord } );
  5384. *```
  5385. * @augments Node
  5386. */
  5387. class ContextNode extends Node {
  5388. static get type() {
  5389. return 'ContextNode';
  5390. }
  5391. /**
  5392. * Constructs a new context node.
  5393. *
  5394. * @param {Node} node - The node whose context should be modified.
  5395. * @param {Object} [value={}] - The modified context data.
  5396. */
  5397. constructor( node, value = {} ) {
  5398. super();
  5399. /**
  5400. * This flag can be used for type testing.
  5401. *
  5402. * @type {boolean}
  5403. * @readonly
  5404. * @default true
  5405. */
  5406. this.isContextNode = true;
  5407. /**
  5408. * The node whose context should be modified.
  5409. *
  5410. * @type {Node}
  5411. */
  5412. this.node = node;
  5413. /**
  5414. * The modified context data.
  5415. *
  5416. * @type {Object}
  5417. * @default {}
  5418. */
  5419. this.value = value;
  5420. }
  5421. /**
  5422. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5423. *
  5424. * @return {Node} A reference to {@link ContextNode#node}.
  5425. */
  5426. getScope() {
  5427. return this.node.getScope();
  5428. }
  5429. /**
  5430. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5431. *
  5432. * @param {NodeBuilder} builder - The current node builder.
  5433. * @return {string} The node type.
  5434. */
  5435. getNodeType( builder ) {
  5436. return this.node.getNodeType( builder );
  5437. }
  5438. /**
  5439. * This method is overwritten to ensure it returns the member type of {@link ContextNode#node}.
  5440. *
  5441. * @param {NodeBuilder} builder - The current node builder.
  5442. * @param {string} name - The member name.
  5443. * @returns {string} The member type.
  5444. */
  5445. getMemberType( builder, name ) {
  5446. return this.node.getMemberType( builder, name );
  5447. }
  5448. analyze( builder ) {
  5449. const previousContext = builder.getContext();
  5450. builder.setContext( { ...builder.context, ...this.value } );
  5451. this.node.build( builder );
  5452. builder.setContext( previousContext );
  5453. }
  5454. setup( builder ) {
  5455. const previousContext = builder.getContext();
  5456. builder.setContext( { ...builder.context, ...this.value } );
  5457. this.node.build( builder );
  5458. builder.setContext( previousContext );
  5459. }
  5460. generate( builder, output ) {
  5461. const previousContext = builder.getContext();
  5462. builder.setContext( { ...builder.context, ...this.value } );
  5463. const snippet = this.node.build( builder, output );
  5464. builder.setContext( previousContext );
  5465. return snippet;
  5466. }
  5467. }
  5468. /**
  5469. * TSL function for creating a context node.
  5470. *
  5471. * @tsl
  5472. * @function
  5473. * @param {Node} node - The node whose context should be modified.
  5474. * @param {Object} [value={}] - The modified context data.
  5475. * @returns {ContextNode}
  5476. */
  5477. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5478. /**
  5479. * TSL function for defining a uniformFlow context value for a given node.
  5480. *
  5481. * @tsl
  5482. * @function
  5483. * @param {Node} node - The node whose dependencies should all execute within a uniform control-flow path.
  5484. * @returns {ContextNode}
  5485. */
  5486. const uniformFlow = ( node ) => context( node, { uniformFlow: true } );
  5487. /**
  5488. * TSL function for defining a name for the context value for a given node.
  5489. *
  5490. * @tsl
  5491. * @function
  5492. * @param {Node} node - The node whose context should be modified.
  5493. * @param {string} name - The name to set.
  5494. * @returns {ContextNode}
  5495. */
  5496. const setName = ( node, name ) => context( node, { nodeName: name } );
  5497. /**
  5498. * TSL function for defining a label context value for a given node.
  5499. *
  5500. * @tsl
  5501. * @function
  5502. * @deprecated
  5503. * @param {Node} node - The node whose context should be modified.
  5504. * @param {string} name - The name/label to set.
  5505. * @returns {ContextNode}
  5506. */
  5507. function label( node, name ) {
  5508. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  5509. return setName( node, name );
  5510. }
  5511. addMethodChaining( 'context', context );
  5512. addMethodChaining( 'label', label );
  5513. addMethodChaining( 'uniformFlow', uniformFlow );
  5514. addMethodChaining( 'setName', setName );
  5515. /**
  5516. * Class for representing shader variables as nodes. Variables are created from
  5517. * existing nodes like the following:
  5518. *
  5519. * ```js
  5520. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5521. * ```
  5522. *
  5523. * @augments Node
  5524. */
  5525. class VarNode extends Node {
  5526. static get type() {
  5527. return 'VarNode';
  5528. }
  5529. /**
  5530. * Constructs a new variable node.
  5531. *
  5532. * @param {Node} node - The node for which a variable should be created.
  5533. * @param {?string} [name=null] - The name of the variable in the shader.
  5534. * @param {boolean} [readOnly=false] - The read-only flag.
  5535. */
  5536. constructor( node, name = null, readOnly = false ) {
  5537. super();
  5538. /**
  5539. * The node for which a variable should be created.
  5540. *
  5541. * @type {Node}
  5542. */
  5543. this.node = node;
  5544. /**
  5545. * The name of the variable in the shader. If no name is defined,
  5546. * the node system auto-generates one.
  5547. *
  5548. * @type {?string}
  5549. * @default null
  5550. */
  5551. this.name = name;
  5552. /**
  5553. * `VarNode` sets this property to `true` by default.
  5554. *
  5555. * @type {boolean}
  5556. * @default true
  5557. */
  5558. this.global = true;
  5559. /**
  5560. * This flag can be used for type testing.
  5561. *
  5562. * @type {boolean}
  5563. * @readonly
  5564. * @default true
  5565. */
  5566. this.isVarNode = true;
  5567. /**
  5568. *
  5569. * The read-only flag.
  5570. *
  5571. * @type {boolean}
  5572. * @default false
  5573. */
  5574. this.readOnly = readOnly;
  5575. /**
  5576. *
  5577. * Add this flag to the node system to indicate that this node require parents.
  5578. *
  5579. * @type {boolean}
  5580. * @default true
  5581. */
  5582. this.parents = true;
  5583. /**
  5584. * This flag is used to indicate that this node is used for intent.
  5585. *
  5586. * @type {boolean}
  5587. * @default false
  5588. */
  5589. this.intent = false;
  5590. }
  5591. /**
  5592. * Sets the intent flag for this node.
  5593. *
  5594. * This flag is used to indicate that this node is used for intent
  5595. * and should not be built directly. Instead, it is used to indicate that
  5596. * the node should be treated as a variable intent.
  5597. *
  5598. * It's useful for assigning variables without needing creating a new variable node.
  5599. *
  5600. * @param {boolean} value - The value to set for the intent flag.
  5601. * @returns {VarNode} This node.
  5602. */
  5603. setIntent( value ) {
  5604. this.intent = value;
  5605. return this;
  5606. }
  5607. /**
  5608. * Returns the intent flag of this node.
  5609. *
  5610. * @return {boolean} The intent flag.
  5611. */
  5612. getIntent() {
  5613. return this.intent;
  5614. }
  5615. getMemberType( builder, name ) {
  5616. return this.node.getMemberType( builder, name );
  5617. }
  5618. getElementType( builder ) {
  5619. return this.node.getElementType( builder );
  5620. }
  5621. getNodeType( builder ) {
  5622. return this.node.getNodeType( builder );
  5623. }
  5624. getArrayCount( builder ) {
  5625. return this.node.getArrayCount( builder );
  5626. }
  5627. build( ...params ) {
  5628. if ( this.intent === true ) {
  5629. const builder = params[ 0 ];
  5630. const properties = builder.getNodeProperties( this );
  5631. if ( properties.assign !== true ) {
  5632. return this.node.build( ...params );
  5633. }
  5634. }
  5635. return super.build( ...params );
  5636. }
  5637. generate( builder ) {
  5638. const { node, name, readOnly } = this;
  5639. const { renderer } = builder;
  5640. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5641. let isDeterministic = false;
  5642. let shouldTreatAsReadOnly = false;
  5643. if ( readOnly ) {
  5644. isDeterministic = builder.isDeterministic( node );
  5645. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5646. }
  5647. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  5648. const snippet = node.build( builder, vectorType );
  5649. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5650. const propertyName = builder.getPropertyName( nodeVar );
  5651. let declarationPrefix = propertyName;
  5652. if ( shouldTreatAsReadOnly ) {
  5653. if ( isWebGPUBackend ) {
  5654. declarationPrefix = isDeterministic
  5655. ? `const ${ propertyName }`
  5656. : `let ${ propertyName }`;
  5657. } else {
  5658. const count = node.getArrayCount( builder );
  5659. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5660. }
  5661. }
  5662. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5663. return propertyName;
  5664. }
  5665. }
  5666. /**
  5667. * TSL function for creating a var node.
  5668. *
  5669. * @tsl
  5670. * @function
  5671. * @param {Node} node - The node for which a variable should be created.
  5672. * @param {?string} name - The name of the variable in the shader.
  5673. * @returns {VarNode}
  5674. */
  5675. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5676. /**
  5677. * TSL function for creating a var node.
  5678. *
  5679. * @tsl
  5680. * @function
  5681. * @param {Node} node - The node for which a variable should be created.
  5682. * @param {?string} name - The name of the variable in the shader.
  5683. * @returns {VarNode}
  5684. */
  5685. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5686. /**
  5687. * TSL function for creating a const node.
  5688. *
  5689. * @tsl
  5690. * @function
  5691. * @param {Node} node - The node for which a constant should be created.
  5692. * @param {?string} name - The name of the constant in the shader.
  5693. * @returns {VarNode}
  5694. */
  5695. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5696. //
  5697. //
  5698. /**
  5699. * TSL function for creating a var intent node.
  5700. *
  5701. * @tsl
  5702. * @function
  5703. * @param {Node} node - The node for which a variable should be created.
  5704. * @param {?string} name - The name of the variable in the shader.
  5705. * @returns {VarNode}
  5706. */
  5707. const VarIntent = ( node ) => {
  5708. if ( getCurrentStack() === null ) {
  5709. return node;
  5710. }
  5711. return createVar( node ).setIntent( true ).toStack();
  5712. };
  5713. // Method chaining
  5714. addMethodChaining( 'toVar', Var );
  5715. addMethodChaining( 'toConst', Const );
  5716. addMethodChaining( 'toVarIntent', VarIntent );
  5717. /**
  5718. * This node is used to build a sub-build in the node system.
  5719. *
  5720. * @augments Node
  5721. * @param {Node} node - The node to be built in the sub-build.
  5722. * @param {string} name - The name of the sub-build.
  5723. * @param {?string} [nodeType=null] - The type of the node, if known.
  5724. */
  5725. class SubBuildNode extends Node {
  5726. static get type() {
  5727. return 'SubBuild';
  5728. }
  5729. constructor( node, name, nodeType = null ) {
  5730. super( nodeType );
  5731. /**
  5732. * The node to be built in the sub-build.
  5733. *
  5734. * @type {Node}
  5735. */
  5736. this.node = node;
  5737. /**
  5738. * The name of the sub-build.
  5739. *
  5740. * @type {string}
  5741. */
  5742. this.name = name;
  5743. /**
  5744. * This flag can be used for type testing.
  5745. *
  5746. * @type {boolean}
  5747. * @readonly
  5748. * @default true
  5749. */
  5750. this.isSubBuildNode = true;
  5751. }
  5752. getNodeType( builder ) {
  5753. if ( this.nodeType !== null ) return this.nodeType;
  5754. builder.addSubBuild( this.name );
  5755. const nodeType = this.node.getNodeType( builder );
  5756. builder.removeSubBuild();
  5757. return nodeType;
  5758. }
  5759. build( builder, ...params ) {
  5760. builder.addSubBuild( this.name );
  5761. const data = this.node.build( builder, ...params );
  5762. builder.removeSubBuild();
  5763. return data;
  5764. }
  5765. }
  5766. /**
  5767. * Creates a new sub-build node.
  5768. *
  5769. * @tsl
  5770. * @function
  5771. * @param {Node} node - The node to be built in the sub-build.
  5772. * @param {string} name - The name of the sub-build.
  5773. * @param {?string} [type=null] - The type of the node, if known.
  5774. * @returns {Node} A node object wrapping the SubBuildNode instance.
  5775. */
  5776. const subBuild = ( node, name, type = null ) => nodeObject( new SubBuildNode( nodeObject( node ), name, type ) );
  5777. /**
  5778. * Class for representing shader varyings as nodes. Varyings are create from
  5779. * existing nodes like the following:
  5780. *
  5781. * ```js
  5782. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5783. * ```
  5784. *
  5785. * @augments Node
  5786. */
  5787. class VaryingNode extends Node {
  5788. static get type() {
  5789. return 'VaryingNode';
  5790. }
  5791. /**
  5792. * Constructs a new varying node.
  5793. *
  5794. * @param {Node} node - The node for which a varying should be created.
  5795. * @param {?string} name - The name of the varying in the shader.
  5796. */
  5797. constructor( node, name = null ) {
  5798. super();
  5799. /**
  5800. * The node for which a varying should be created.
  5801. *
  5802. * @type {Node}
  5803. */
  5804. this.node = node;
  5805. /**
  5806. * The name of the varying in the shader. If no name is defined,
  5807. * the node system auto-generates one.
  5808. *
  5809. * @type {?string}
  5810. * @default null
  5811. */
  5812. this.name = name;
  5813. /**
  5814. * This flag can be used for type testing.
  5815. *
  5816. * @type {boolean}
  5817. * @readonly
  5818. * @default true
  5819. */
  5820. this.isVaryingNode = true;
  5821. /**
  5822. * The interpolation type of the varying data.
  5823. *
  5824. * @type {?string}
  5825. * @default null
  5826. */
  5827. this.interpolationType = null;
  5828. /**
  5829. * The interpolation sampling type of varying data.
  5830. *
  5831. * @type {?string}
  5832. * @default null
  5833. */
  5834. this.interpolationSampling = null;
  5835. /**
  5836. * This flag is used for global cache.
  5837. *
  5838. * @type {boolean}
  5839. * @default true
  5840. */
  5841. this.global = true;
  5842. }
  5843. /**
  5844. * Defines the interpolation type of the varying.
  5845. *
  5846. * @param {string} type - The interpolation type.
  5847. * @param {?string} sampling - The interpolation sampling type
  5848. * @return {VaryingNode} A reference to this node.
  5849. */
  5850. setInterpolation( type, sampling = null ) {
  5851. this.interpolationType = type;
  5852. this.interpolationSampling = sampling;
  5853. return this;
  5854. }
  5855. getHash( builder ) {
  5856. return this.name || super.getHash( builder );
  5857. }
  5858. getNodeType( builder ) {
  5859. // VaryingNode is auto type
  5860. return this.node.getNodeType( builder );
  5861. }
  5862. /**
  5863. * This method performs the setup of a varying node with the current node builder.
  5864. *
  5865. * @param {NodeBuilder} builder - The current node builder.
  5866. * @return {NodeVarying} The node varying from the node builder.
  5867. */
  5868. setupVarying( builder ) {
  5869. const properties = builder.getNodeProperties( this );
  5870. let varying = properties.varying;
  5871. if ( varying === undefined ) {
  5872. const name = this.name;
  5873. const type = this.getNodeType( builder );
  5874. const interpolationType = this.interpolationType;
  5875. const interpolationSampling = this.interpolationSampling;
  5876. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5877. properties.node = subBuild( this.node, 'VERTEX' );
  5878. }
  5879. // this property can be used to check if the varying can be optimized for a variable
  5880. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5881. return varying;
  5882. }
  5883. setup( builder ) {
  5884. this.setupVarying( builder );
  5885. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5886. }
  5887. analyze( builder ) {
  5888. this.setupVarying( builder );
  5889. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5890. }
  5891. generate( builder ) {
  5892. const propertyKey = builder.getSubBuildProperty( 'property', builder.currentStack );
  5893. const properties = builder.getNodeProperties( this );
  5894. const varying = this.setupVarying( builder );
  5895. if ( properties[ propertyKey ] === undefined ) {
  5896. const type = this.getNodeType( builder );
  5897. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5898. // force node run in vertex stage
  5899. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, properties.node, type, propertyName );
  5900. properties[ propertyKey ] = propertyName;
  5901. }
  5902. return builder.getPropertyName( varying );
  5903. }
  5904. }
  5905. /**
  5906. * TSL function for creating a varying node.
  5907. *
  5908. * @tsl
  5909. * @function
  5910. * @param {Node} node - The node for which a varying should be created.
  5911. * @param {?string} name - The name of the varying in the shader.
  5912. * @returns {VaryingNode}
  5913. */
  5914. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  5915. /**
  5916. * Computes a node in the vertex stage.
  5917. *
  5918. * @tsl
  5919. * @function
  5920. * @param {Node} node - The node which should be executed in the vertex stage.
  5921. * @returns {VaryingNode}
  5922. */
  5923. const vertexStage = ( node ) => varying( node );
  5924. addMethodChaining( 'toVarying', varying );
  5925. addMethodChaining( 'toVertexStage', vertexStage );
  5926. // Deprecated
  5927. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5928. console.warn( 'THREE.TSL: .varying() has been renamed to .toVarying().' );
  5929. return varying( ...params );
  5930. } );
  5931. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5932. console.warn( 'THREE.TSL: .vertexStage() has been renamed to .toVertexStage().' );
  5933. return varying( ...params );
  5934. } );
  5935. /**
  5936. * Converts the given color value from sRGB to linear-sRGB color space.
  5937. *
  5938. * @tsl
  5939. * @function
  5940. * @param {Node<vec3>} color - The sRGB color.
  5941. * @return {Node<vec3>} The linear-sRGB color.
  5942. */
  5943. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5944. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5945. const b = color.mul( 0.0773993808 );
  5946. const factor = color.lessThanEqual( 0.04045 );
  5947. const rgbResult = mix( a, b, factor );
  5948. return rgbResult;
  5949. } ).setLayout( {
  5950. name: 'sRGBTransferEOTF',
  5951. type: 'vec3',
  5952. inputs: [
  5953. { name: 'color', type: 'vec3' }
  5954. ]
  5955. } );
  5956. /**
  5957. * Converts the given color value from linear-sRGB to sRGB color space.
  5958. *
  5959. * @tsl
  5960. * @function
  5961. * @param {Node<vec3>} color - The linear-sRGB color.
  5962. * @return {Node<vec3>} The sRGB color.
  5963. */
  5964. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5965. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  5966. const b = color.mul( 12.92 );
  5967. const factor = color.lessThanEqual( 0.0031308 );
  5968. const rgbResult = mix( a, b, factor );
  5969. return rgbResult;
  5970. } ).setLayout( {
  5971. name: 'sRGBTransferOETF',
  5972. type: 'vec3',
  5973. inputs: [
  5974. { name: 'color', type: 'vec3' }
  5975. ]
  5976. } );
  5977. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  5978. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  5979. /**
  5980. * This node represents a color space conversion. Meaning it converts
  5981. * a color value from a source to a target color space.
  5982. *
  5983. * @augments TempNode
  5984. */
  5985. class ColorSpaceNode extends TempNode {
  5986. static get type() {
  5987. return 'ColorSpaceNode';
  5988. }
  5989. /**
  5990. * Constructs a new color space node.
  5991. *
  5992. * @param {Node} colorNode - Represents the color to convert.
  5993. * @param {string} source - The source color space.
  5994. * @param {string} target - The target color space.
  5995. */
  5996. constructor( colorNode, source, target ) {
  5997. super( 'vec4' );
  5998. /**
  5999. * Represents the color to convert.
  6000. *
  6001. * @type {Node}
  6002. */
  6003. this.colorNode = colorNode;
  6004. /**
  6005. * The source color space.
  6006. *
  6007. * @type {string}
  6008. */
  6009. this.source = source;
  6010. /**
  6011. * The target color space.
  6012. *
  6013. * @type {string}
  6014. */
  6015. this.target = target;
  6016. }
  6017. /**
  6018. * This method resolves the constants `WORKING_COLOR_SPACE` and
  6019. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  6020. * color management and renderer.
  6021. *
  6022. * @param {NodeBuilder} builder - The current node builder.
  6023. * @param {string} colorSpace - The color space to resolve.
  6024. * @return {string} The resolved color space.
  6025. */
  6026. resolveColorSpace( builder, colorSpace ) {
  6027. if ( colorSpace === WORKING_COLOR_SPACE ) {
  6028. return ColorManagement.workingColorSpace;
  6029. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  6030. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  6031. }
  6032. return colorSpace;
  6033. }
  6034. setup( builder ) {
  6035. const { colorNode } = this;
  6036. const source = this.resolveColorSpace( builder, this.source );
  6037. const target = this.resolveColorSpace( builder, this.target );
  6038. let outputNode = colorNode;
  6039. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  6040. return outputNode;
  6041. }
  6042. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  6043. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  6044. }
  6045. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  6046. outputNode = vec4(
  6047. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  6048. outputNode.a
  6049. );
  6050. }
  6051. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  6052. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  6053. }
  6054. return outputNode;
  6055. }
  6056. }
  6057. /**
  6058. * TSL function for converting a given color node from the current working color space to the given color space.
  6059. *
  6060. * @tsl
  6061. * @function
  6062. * @param {Node} node - Represents the node to convert.
  6063. * @param {string} targetColorSpace - The target color space.
  6064. * @returns {ColorSpaceNode}
  6065. */
  6066. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  6067. /**
  6068. * TSL function for converting a given color node from the given color space to the current working color space.
  6069. *
  6070. * @tsl
  6071. * @function
  6072. * @param {Node} node - Represents the node to convert.
  6073. * @param {string} sourceColorSpace - The source color space.
  6074. * @returns {ColorSpaceNode}
  6075. */
  6076. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  6077. /**
  6078. * TSL function for converting a given color node from one color space to another one.
  6079. *
  6080. * @tsl
  6081. * @function
  6082. * @param {Node} node - Represents the node to convert.
  6083. * @param {string} sourceColorSpace - The source color space.
  6084. * @param {string} targetColorSpace - The target color space.
  6085. * @returns {ColorSpaceNode}
  6086. */
  6087. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  6088. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  6089. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  6090. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  6091. /**
  6092. * This class is only relevant if the referenced property is array-like.
  6093. * In this case, `ReferenceElementNode` allows to refer to a specific
  6094. * element inside the data structure via an index.
  6095. *
  6096. * @augments ArrayElementNode
  6097. */
  6098. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  6099. static get type() {
  6100. return 'ReferenceElementNode';
  6101. }
  6102. /**
  6103. * Constructs a new reference element node.
  6104. *
  6105. * @param {ReferenceBaseNode} referenceNode - The reference node.
  6106. * @param {Node} indexNode - The index node that defines the element access.
  6107. */
  6108. constructor( referenceNode, indexNode ) {
  6109. super( referenceNode, indexNode );
  6110. /**
  6111. * Similar to {@link ReferenceBaseNode#reference}, an additional
  6112. * property references to the current node.
  6113. *
  6114. * @type {?ReferenceBaseNode}
  6115. * @default null
  6116. */
  6117. this.referenceNode = referenceNode;
  6118. /**
  6119. * This flag can be used for type testing.
  6120. *
  6121. * @type {boolean}
  6122. * @readonly
  6123. * @default true
  6124. */
  6125. this.isReferenceElementNode = true;
  6126. }
  6127. /**
  6128. * This method is overwritten since the node type is inferred from
  6129. * the uniform type of the reference node.
  6130. *
  6131. * @return {string} The node type.
  6132. */
  6133. getNodeType() {
  6134. return this.referenceNode.uniformType;
  6135. }
  6136. generate( builder ) {
  6137. const snippet = super.generate( builder );
  6138. const arrayType = this.referenceNode.getNodeType();
  6139. const elementType = this.getNodeType();
  6140. return builder.format( snippet, arrayType, elementType );
  6141. }
  6142. };
  6143. /**
  6144. * Base class for nodes which establishes a reference to a property of another object.
  6145. * In this way, the value of the node is automatically linked to the value of
  6146. * referenced object. Reference nodes internally represent the linked value
  6147. * as a uniform.
  6148. *
  6149. * @augments Node
  6150. */
  6151. class ReferenceBaseNode extends Node {
  6152. static get type() {
  6153. return 'ReferenceBaseNode';
  6154. }
  6155. /**
  6156. * Constructs a new reference base node.
  6157. *
  6158. * @param {string} property - The name of the property the node refers to.
  6159. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  6160. * @param {?Object} [object=null] - The object the property belongs to.
  6161. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  6162. */
  6163. constructor( property, uniformType, object = null, count = null ) {
  6164. super();
  6165. /**
  6166. * The name of the property the node refers to.
  6167. *
  6168. * @type {string}
  6169. */
  6170. this.property = property;
  6171. /**
  6172. * The uniform type that should be used to represent the property value.
  6173. *
  6174. * @type {string}
  6175. */
  6176. this.uniformType = uniformType;
  6177. /**
  6178. * The object the property belongs to.
  6179. *
  6180. * @type {?Object}
  6181. * @default null
  6182. */
  6183. this.object = object;
  6184. /**
  6185. * When the linked property is an array, this parameter defines its length.
  6186. *
  6187. * @type {?number}
  6188. * @default null
  6189. */
  6190. this.count = count;
  6191. /**
  6192. * The property name might have dots so nested properties can be referred.
  6193. * The hierarchy of the names is stored inside this array.
  6194. *
  6195. * @type {Array<string>}
  6196. */
  6197. this.properties = property.split( '.' );
  6198. /**
  6199. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  6200. * since the final reference might be updated from calling code.
  6201. *
  6202. * @type {?Object}
  6203. * @default null
  6204. */
  6205. this.reference = object;
  6206. /**
  6207. * The uniform node that holds the value of the reference node.
  6208. *
  6209. * @type {UniformNode}
  6210. * @default null
  6211. */
  6212. this.node = null;
  6213. /**
  6214. * The uniform group of the internal uniform.
  6215. *
  6216. * @type {UniformGroupNode}
  6217. * @default null
  6218. */
  6219. this.group = null;
  6220. /**
  6221. * Overwritten since reference nodes are updated per object.
  6222. *
  6223. * @type {string}
  6224. * @default 'object'
  6225. */
  6226. this.updateType = NodeUpdateType.OBJECT;
  6227. }
  6228. /**
  6229. * Sets the uniform group for this reference node.
  6230. *
  6231. * @param {UniformGroupNode} group - The uniform group to set.
  6232. * @return {ReferenceBaseNode} A reference to this node.
  6233. */
  6234. setGroup( group ) {
  6235. this.group = group;
  6236. return this;
  6237. }
  6238. /**
  6239. * When the referred property is array-like, this method can be used
  6240. * to access elements via an index node.
  6241. *
  6242. * @param {IndexNode} indexNode - indexNode.
  6243. * @return {ReferenceElementNode} A reference to an element.
  6244. */
  6245. element( indexNode ) {
  6246. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  6247. }
  6248. /**
  6249. * Sets the node type which automatically defines the internal
  6250. * uniform type.
  6251. *
  6252. * @param {string} uniformType - The type to set.
  6253. */
  6254. setNodeType( uniformType ) {
  6255. const node = uniform( null, uniformType );
  6256. if ( this.group !== null ) {
  6257. node.setGroup( this.group );
  6258. }
  6259. this.node = node;
  6260. }
  6261. /**
  6262. * This method is overwritten since the node type is inferred from
  6263. * the type of the reference node.
  6264. *
  6265. * @param {NodeBuilder} builder - The current node builder.
  6266. * @return {string} The node type.
  6267. */
  6268. getNodeType( builder ) {
  6269. if ( this.node === null ) {
  6270. this.updateReference( builder );
  6271. this.updateValue();
  6272. }
  6273. return this.node.getNodeType( builder );
  6274. }
  6275. /**
  6276. * Returns the property value from the given referred object.
  6277. *
  6278. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  6279. * @return {any} The value.
  6280. */
  6281. getValueFromReference( object = this.reference ) {
  6282. const { properties } = this;
  6283. let value = object[ properties[ 0 ] ];
  6284. for ( let i = 1; i < properties.length; i ++ ) {
  6285. value = value[ properties[ i ] ];
  6286. }
  6287. return value;
  6288. }
  6289. /**
  6290. * Allows to update the reference based on the given state. The state is only
  6291. * evaluated {@link ReferenceBaseNode#object} is not set.
  6292. *
  6293. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6294. * @return {Object} The updated reference.
  6295. */
  6296. updateReference( state ) {
  6297. this.reference = this.object !== null ? this.object : state.object;
  6298. return this.reference;
  6299. }
  6300. /**
  6301. * The output of the reference node is the internal uniform node.
  6302. *
  6303. * @return {UniformNode} The output node.
  6304. */
  6305. setup() {
  6306. this.updateValue();
  6307. return this.node;
  6308. }
  6309. /**
  6310. * Overwritten to update the internal uniform value.
  6311. *
  6312. * @param {NodeFrame} frame - A reference to the current node frame.
  6313. */
  6314. update( /*frame*/ ) {
  6315. this.updateValue();
  6316. }
  6317. /**
  6318. * Retrieves the value from the referred object property and uses it
  6319. * to updated the internal uniform.
  6320. */
  6321. updateValue() {
  6322. if ( this.node === null ) this.setNodeType( this.uniformType );
  6323. const value = this.getValueFromReference();
  6324. if ( Array.isArray( value ) ) {
  6325. this.node.array = value;
  6326. } else {
  6327. this.node.value = value;
  6328. }
  6329. }
  6330. }
  6331. /**
  6332. * TSL function for creating a reference base node.
  6333. *
  6334. * @tsl
  6335. * @function
  6336. * @param {string} name - The name of the property the node refers to.
  6337. * @param {string} type - The uniform type that should be used to represent the property value.
  6338. * @param {Object} object - The object the property belongs to.
  6339. * @returns {ReferenceBaseNode}
  6340. */
  6341. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  6342. /**
  6343. * This node is a special type of reference node which is intended
  6344. * for linking renderer properties with node values.
  6345. * ```js
  6346. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  6347. * ```
  6348. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  6349. * automatically be updated.
  6350. *
  6351. * @augments ReferenceBaseNode
  6352. */
  6353. class RendererReferenceNode extends ReferenceBaseNode {
  6354. static get type() {
  6355. return 'RendererReferenceNode';
  6356. }
  6357. /**
  6358. * Constructs a new renderer reference node.
  6359. *
  6360. * @param {string} property - The name of the property the node refers to.
  6361. * @param {string} inputType - The uniform type that should be used to represent the property value.
  6362. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6363. * the node refers to the renderer of the current state.
  6364. */
  6365. constructor( property, inputType, renderer = null ) {
  6366. super( property, inputType, renderer );
  6367. /**
  6368. * The renderer the property belongs to. When no renderer is set,
  6369. * the node refers to the renderer of the current state.
  6370. *
  6371. * @type {?Renderer}
  6372. * @default null
  6373. */
  6374. this.renderer = renderer;
  6375. this.setGroup( renderGroup );
  6376. }
  6377. /**
  6378. * Updates the reference based on the given state. The state is only evaluated
  6379. * {@link RendererReferenceNode#renderer} is not set.
  6380. *
  6381. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  6382. * @return {Object} The updated reference.
  6383. */
  6384. updateReference( state ) {
  6385. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  6386. return this.reference;
  6387. }
  6388. }
  6389. /**
  6390. * TSL function for creating a renderer reference node.
  6391. *
  6392. * @tsl
  6393. * @function
  6394. * @param {string} name - The name of the property the node refers to.
  6395. * @param {string} type - The uniform type that should be used to represent the property value.
  6396. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  6397. * the node refers to the renderer of the current state.
  6398. * @returns {RendererReferenceNode}
  6399. */
  6400. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  6401. /**
  6402. * This node represents a tone mapping operation.
  6403. *
  6404. * @augments TempNode
  6405. */
  6406. class ToneMappingNode extends TempNode {
  6407. static get type() {
  6408. return 'ToneMappingNode';
  6409. }
  6410. /**
  6411. * Constructs a new tone mapping node.
  6412. *
  6413. * @param {number} toneMapping - The tone mapping type.
  6414. * @param {Node} exposureNode - The tone mapping exposure.
  6415. * @param {Node} [colorNode=null] - The color node to process.
  6416. */
  6417. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  6418. super( 'vec3' );
  6419. /**
  6420. * The tone mapping type.
  6421. *
  6422. * @type {number}
  6423. */
  6424. this.toneMapping = toneMapping;
  6425. /**
  6426. * The tone mapping exposure.
  6427. *
  6428. * @type {Node}
  6429. * @default null
  6430. */
  6431. this.exposureNode = exposureNode;
  6432. /**
  6433. * Represents the color to process.
  6434. *
  6435. * @type {?Node}
  6436. * @default null
  6437. */
  6438. this.colorNode = colorNode;
  6439. }
  6440. /**
  6441. * Overwrites the default `customCacheKey()` implementation by including the tone
  6442. * mapping type into the cache key.
  6443. *
  6444. * @return {number} The hash.
  6445. */
  6446. customCacheKey() {
  6447. return hash$1( this.toneMapping );
  6448. }
  6449. setup( builder ) {
  6450. const colorNode = this.colorNode || builder.context.color;
  6451. const toneMapping = this.toneMapping;
  6452. if ( toneMapping === NoToneMapping ) return colorNode;
  6453. let outputNode = null;
  6454. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  6455. if ( toneMappingFn !== null ) {
  6456. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  6457. } else {
  6458. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  6459. outputNode = colorNode;
  6460. }
  6461. return outputNode;
  6462. }
  6463. }
  6464. /**
  6465. * TSL function for creating a tone mapping node.
  6466. *
  6467. * @tsl
  6468. * @function
  6469. * @param {number} mapping - The tone mapping type.
  6470. * @param {Node<float> | number} exposure - The tone mapping exposure.
  6471. * @param {Node<vec3> | Color} color - The color node to process.
  6472. * @returns {ToneMappingNode<vec3>}
  6473. */
  6474. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6475. /**
  6476. * TSL object that represents the global tone mapping exposure of the renderer.
  6477. *
  6478. * @tsl
  6479. * @type {RendererReferenceNode<vec3>}
  6480. */
  6481. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6482. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6483. /**
  6484. * In earlier `three.js` versions it was only possible to define attribute data
  6485. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6486. * on the node level.
  6487. * ```js
  6488. * const geometry = new THREE.PlaneGeometry();
  6489. * const positionAttribute = geometry.getAttribute( 'position' );
  6490. *
  6491. * const colors = [];
  6492. * for ( let i = 0; i < position.count; i ++ ) {
  6493. * colors.push( 1, 0, 0 );
  6494. * }
  6495. *
  6496. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6497. * ```
  6498. * This new approach is especially interesting when geometry data are generated via
  6499. * compute shaders. The below line converts a storage buffer into an attribute node.
  6500. * ```js
  6501. * material.positionNode = positionBuffer.toAttribute();
  6502. * ```
  6503. * @augments InputNode
  6504. */
  6505. class BufferAttributeNode extends InputNode {
  6506. static get type() {
  6507. return 'BufferAttributeNode';
  6508. }
  6509. /**
  6510. * Constructs a new buffer attribute node.
  6511. *
  6512. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6513. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6514. * @param {number} [bufferStride=0] - The buffer stride.
  6515. * @param {number} [bufferOffset=0] - The buffer offset.
  6516. */
  6517. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6518. super( value, bufferType );
  6519. /**
  6520. * This flag can be used for type testing.
  6521. *
  6522. * @type {boolean}
  6523. * @readonly
  6524. * @default true
  6525. */
  6526. this.isBufferNode = true;
  6527. /**
  6528. * The buffer type (e.g. `'vec3'`).
  6529. *
  6530. * @type {?string}
  6531. * @default null
  6532. */
  6533. this.bufferType = bufferType;
  6534. /**
  6535. * The buffer stride.
  6536. *
  6537. * @type {number}
  6538. * @default 0
  6539. */
  6540. this.bufferStride = bufferStride;
  6541. /**
  6542. * The buffer offset.
  6543. *
  6544. * @type {number}
  6545. * @default 0
  6546. */
  6547. this.bufferOffset = bufferOffset;
  6548. /**
  6549. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6550. * if you are planning to update the attribute data per frame.
  6551. *
  6552. * @type {number}
  6553. * @default StaticDrawUsage
  6554. */
  6555. this.usage = StaticDrawUsage;
  6556. /**
  6557. * Whether the attribute is instanced or not.
  6558. *
  6559. * @type {boolean}
  6560. * @default false
  6561. */
  6562. this.instanced = false;
  6563. /**
  6564. * A reference to the buffer attribute.
  6565. *
  6566. * @type {?BufferAttribute}
  6567. * @default null
  6568. */
  6569. this.attribute = null;
  6570. /**
  6571. * `BufferAttributeNode` sets this property to `true` by default.
  6572. *
  6573. * @type {boolean}
  6574. * @default true
  6575. */
  6576. this.global = true;
  6577. if ( value && value.isBufferAttribute === true ) {
  6578. this.attribute = value;
  6579. this.usage = value.usage;
  6580. this.instanced = value.isInstancedBufferAttribute;
  6581. }
  6582. }
  6583. /**
  6584. * This method is overwritten since the attribute data might be shared
  6585. * and thus the hash should be shared as well.
  6586. *
  6587. * @param {NodeBuilder} builder - The current node builder.
  6588. * @return {string} The hash.
  6589. */
  6590. getHash( builder ) {
  6591. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6592. let bufferData = builder.globalCache.getData( this.value );
  6593. if ( bufferData === undefined ) {
  6594. bufferData = {
  6595. node: this
  6596. };
  6597. builder.globalCache.setData( this.value, bufferData );
  6598. }
  6599. return bufferData.node.uuid;
  6600. }
  6601. return this.uuid;
  6602. }
  6603. /**
  6604. * This method is overwritten since the node type is inferred from
  6605. * the buffer attribute.
  6606. *
  6607. * @param {NodeBuilder} builder - The current node builder.
  6608. * @return {string} The node type.
  6609. */
  6610. getNodeType( builder ) {
  6611. if ( this.bufferType === null ) {
  6612. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6613. }
  6614. return this.bufferType;
  6615. }
  6616. /**
  6617. * Depending on which value was passed to the node, `setup()` behaves
  6618. * differently. If no instance of `BufferAttribute` was passed, the method
  6619. * creates an internal attribute and configures it respectively.
  6620. *
  6621. * @param {NodeBuilder} builder - The current node builder.
  6622. */
  6623. setup( builder ) {
  6624. if ( this.attribute !== null ) return;
  6625. const type = this.getNodeType( builder );
  6626. const array = this.value;
  6627. const itemSize = builder.getTypeLength( type );
  6628. const stride = this.bufferStride || itemSize;
  6629. const offset = this.bufferOffset;
  6630. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6631. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6632. buffer.setUsage( this.usage );
  6633. this.attribute = bufferAttribute;
  6634. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6635. }
  6636. /**
  6637. * Generates the code snippet of the buffer attribute node.
  6638. *
  6639. * @param {NodeBuilder} builder - The current node builder.
  6640. * @return {string} The generated code snippet.
  6641. */
  6642. generate( builder ) {
  6643. const nodeType = this.getNodeType( builder );
  6644. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6645. const propertyName = builder.getPropertyName( nodeAttribute );
  6646. let output = null;
  6647. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6648. this.name = propertyName;
  6649. output = propertyName;
  6650. } else {
  6651. const nodeVarying = varying( this );
  6652. output = nodeVarying.build( builder, nodeType );
  6653. }
  6654. return output;
  6655. }
  6656. /**
  6657. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6658. *
  6659. * @param {NodeBuilder} builder - The current node builder.
  6660. * @return {string} The input type.
  6661. */
  6662. getInputType( /*builder*/ ) {
  6663. return 'bufferAttribute';
  6664. }
  6665. /**
  6666. * Sets the `usage` property to the given value.
  6667. *
  6668. * @param {number} value - The usage to set.
  6669. * @return {BufferAttributeNode} A reference to this node.
  6670. */
  6671. setUsage( value ) {
  6672. this.usage = value;
  6673. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6674. this.attribute.usage = value;
  6675. }
  6676. return this;
  6677. }
  6678. /**
  6679. * Sets the `instanced` property to the given value.
  6680. *
  6681. * @param {boolean} value - The value to set.
  6682. * @return {BufferAttributeNode} A reference to this node.
  6683. */
  6684. setInstanced( value ) {
  6685. this.instanced = value;
  6686. return this;
  6687. }
  6688. }
  6689. /**
  6690. * TSL function for creating a buffer attribute node.
  6691. *
  6692. * @tsl
  6693. * @function
  6694. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6695. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6696. * @param {number} [stride=0] - The buffer stride.
  6697. * @param {number} [offset=0] - The buffer offset.
  6698. * @returns {BufferAttributeNode}
  6699. */
  6700. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6701. /**
  6702. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6703. * Use this function if attribute data are updated per frame.
  6704. *
  6705. * @tsl
  6706. * @function
  6707. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6708. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6709. * @param {number} [stride=0] - The buffer stride.
  6710. * @param {number} [offset=0] - The buffer offset.
  6711. * @returns {BufferAttributeNode}
  6712. */
  6713. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6714. /**
  6715. * TSL function for creating a buffer attribute node but with enabled instancing
  6716. *
  6717. * @tsl
  6718. * @function
  6719. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6720. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6721. * @param {number} [stride=0] - The buffer stride.
  6722. * @param {number} [offset=0] - The buffer offset.
  6723. * @returns {BufferAttributeNode}
  6724. */
  6725. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6726. /**
  6727. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6728. *
  6729. * @tsl
  6730. * @function
  6731. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6732. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6733. * @param {number} [stride=0] - The buffer stride.
  6734. * @param {number} [offset=0] - The buffer offset.
  6735. * @returns {BufferAttributeNode}
  6736. */
  6737. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6738. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6739. /**
  6740. * TODO
  6741. *
  6742. * @augments Node
  6743. */
  6744. class ComputeNode extends Node {
  6745. static get type() {
  6746. return 'ComputeNode';
  6747. }
  6748. /**
  6749. * Constructs a new compute node.
  6750. *
  6751. * @param {Node} computeNode - TODO
  6752. * @param {Array<number>} workgroupSize - TODO.
  6753. */
  6754. constructor( computeNode, workgroupSize ) {
  6755. super( 'void' );
  6756. /**
  6757. * This flag can be used for type testing.
  6758. *
  6759. * @type {boolean}
  6760. * @readonly
  6761. * @default true
  6762. */
  6763. this.isComputeNode = true;
  6764. /**
  6765. * TODO
  6766. *
  6767. * @type {Node}
  6768. */
  6769. this.computeNode = computeNode;
  6770. /**
  6771. * TODO
  6772. *
  6773. * @type {Array<number>}
  6774. * @default [ 64 ]
  6775. */
  6776. this.workgroupSize = workgroupSize;
  6777. /**
  6778. * TODO
  6779. *
  6780. * @type {number}
  6781. */
  6782. this.count = null;
  6783. /**
  6784. * TODO
  6785. *
  6786. * @type {number}
  6787. */
  6788. this.version = 1;
  6789. /**
  6790. * The name or label of the uniform.
  6791. *
  6792. * @type {string}
  6793. * @default ''
  6794. */
  6795. this.name = '';
  6796. /**
  6797. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6798. * is executed once per object by default.
  6799. *
  6800. * @type {string}
  6801. * @default 'object'
  6802. */
  6803. this.updateBeforeType = NodeUpdateType.OBJECT;
  6804. /**
  6805. * TODO
  6806. *
  6807. * @type {?Function}
  6808. */
  6809. this.onInitFunction = null;
  6810. }
  6811. setCount( count ) {
  6812. this.count = count;
  6813. return this;
  6814. }
  6815. getCount() {
  6816. return this.count;
  6817. }
  6818. /**
  6819. * Executes the `dispose` event for this node.
  6820. */
  6821. dispose() {
  6822. this.dispatchEvent( { type: 'dispose' } );
  6823. }
  6824. /**
  6825. * Sets the {@link ComputeNode#name} property.
  6826. *
  6827. * @param {string} name - The name of the uniform.
  6828. * @return {ComputeNode} A reference to this node.
  6829. */
  6830. setName( name ) {
  6831. this.name = name;
  6832. return this;
  6833. }
  6834. /**
  6835. * Sets the {@link ComputeNode#name} property.
  6836. *
  6837. * @deprecated
  6838. * @param {string} name - The name of the uniform.
  6839. * @return {ComputeNode} A reference to this node.
  6840. */
  6841. label( name ) {
  6842. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  6843. return this.setName( name );
  6844. }
  6845. /**
  6846. * TODO
  6847. *
  6848. * @param {Function} callback - TODO.
  6849. * @return {ComputeNode} A reference to this node.
  6850. */
  6851. onInit( callback ) {
  6852. this.onInitFunction = callback;
  6853. return this;
  6854. }
  6855. /**
  6856. * The method execute the compute for this node.
  6857. *
  6858. * @param {NodeFrame} frame - A reference to the current node frame.
  6859. */
  6860. updateBefore( { renderer } ) {
  6861. renderer.compute( this );
  6862. }
  6863. setup( builder ) {
  6864. const result = this.computeNode.build( builder );
  6865. if ( result ) {
  6866. const properties = builder.getNodeProperties( this );
  6867. properties.outputComputeNode = result.outputNode;
  6868. result.outputNode = null;
  6869. }
  6870. return result;
  6871. }
  6872. generate( builder, output ) {
  6873. const { shaderStage } = builder;
  6874. if ( shaderStage === 'compute' ) {
  6875. const snippet = this.computeNode.build( builder, 'void' );
  6876. if ( snippet !== '' ) {
  6877. builder.addLineFlowCode( snippet, this );
  6878. }
  6879. } else {
  6880. const properties = builder.getNodeProperties( this );
  6881. const outputComputeNode = properties.outputComputeNode;
  6882. if ( outputComputeNode ) {
  6883. return outputComputeNode.build( builder, output );
  6884. }
  6885. }
  6886. }
  6887. }
  6888. /**
  6889. * TSL function for creating a compute kernel node.
  6890. *
  6891. * @tsl
  6892. * @function
  6893. * @param {Node} node - TODO
  6894. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6895. * @returns {AtomicFunctionNode}
  6896. */
  6897. const computeKernel = ( node, workgroupSize = [ 64 ] ) => {
  6898. if ( workgroupSize.length === 0 || workgroupSize.length > 3 ) {
  6899. console.error( 'THREE.TSL: compute() workgroupSize must have 1, 2, or 3 elements' );
  6900. }
  6901. for ( let i = 0; i < workgroupSize.length; i ++ ) {
  6902. const val = workgroupSize[ i ];
  6903. if ( typeof val !== 'number' || val <= 0 || ! Number.isInteger( val ) ) {
  6904. console.error( `THREE.TSL: compute() workgroupSize element at index [ ${ i } ] must be a positive integer` );
  6905. }
  6906. }
  6907. // Implicit fill-up to [ x, y, z ] with 1s, just like WGSL treats @workgroup_size when fewer dimensions are specified
  6908. while ( workgroupSize.length < 3 ) workgroupSize.push( 1 );
  6909. //
  6910. return nodeObject( new ComputeNode( nodeObject( node ), workgroupSize ) );
  6911. };
  6912. /**
  6913. * TSL function for creating a compute node.
  6914. *
  6915. * @tsl
  6916. * @function
  6917. * @param {Node} node - TODO
  6918. * @param {number} count - TODO.
  6919. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6920. * @returns {AtomicFunctionNode}
  6921. */
  6922. const compute = ( node, count, workgroupSize ) => computeKernel( node, workgroupSize ).setCount( count );
  6923. addMethodChaining( 'compute', compute );
  6924. addMethodChaining( 'computeKernel', computeKernel );
  6925. /**
  6926. * This node can be used as a cache management component for another node.
  6927. * Caching is in general used by default in {@link NodeBuilder} but this node
  6928. * allows the usage of a shared parent cache during the build process.
  6929. *
  6930. * @augments Node
  6931. */
  6932. class CacheNode extends Node {
  6933. static get type() {
  6934. return 'CacheNode';
  6935. }
  6936. /**
  6937. * Constructs a new cache node.
  6938. *
  6939. * @param {Node} node - The node that should be cached.
  6940. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  6941. */
  6942. constructor( node, parent = true ) {
  6943. super();
  6944. /**
  6945. * The node that should be cached.
  6946. *
  6947. * @type {Node}
  6948. */
  6949. this.node = node;
  6950. /**
  6951. * Whether this node refers to a shared parent cache or not.
  6952. *
  6953. * @type {boolean}
  6954. * @default true
  6955. */
  6956. this.parent = parent;
  6957. /**
  6958. * This flag can be used for type testing.
  6959. *
  6960. * @type {boolean}
  6961. * @readonly
  6962. * @default true
  6963. */
  6964. this.isCacheNode = true;
  6965. }
  6966. getNodeType( builder ) {
  6967. const previousCache = builder.getCache();
  6968. const cache = builder.getCacheFromNode( this, this.parent );
  6969. builder.setCache( cache );
  6970. const nodeType = this.node.getNodeType( builder );
  6971. builder.setCache( previousCache );
  6972. return nodeType;
  6973. }
  6974. build( builder, ...params ) {
  6975. const previousCache = builder.getCache();
  6976. const cache = builder.getCacheFromNode( this, this.parent );
  6977. builder.setCache( cache );
  6978. const data = this.node.build( builder, ...params );
  6979. builder.setCache( previousCache );
  6980. return data;
  6981. }
  6982. }
  6983. /**
  6984. * TSL function for creating a cache node.
  6985. *
  6986. * @tsl
  6987. * @function
  6988. * @param {Node} node - The node that should be cached.
  6989. * @param {boolean} [parent] - Whether this node refers to a shared parent cache or not.
  6990. * @returns {CacheNode}
  6991. */
  6992. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  6993. addMethodChaining( 'cache', cache );
  6994. /**
  6995. * The class generates the code of a given node but returns another node in the output.
  6996. * This can be used to call a method or node that does not return a value, i.e.
  6997. * type `void` on an input where returning a value is required. Example:
  6998. *
  6999. * ```js
  7000. * material.colorNode = myColor.bypass( runVoidFn() )
  7001. *```
  7002. *
  7003. * @augments Node
  7004. */
  7005. class BypassNode extends Node {
  7006. static get type() {
  7007. return 'BypassNode';
  7008. }
  7009. /**
  7010. * Constructs a new bypass node.
  7011. *
  7012. * @param {Node} outputNode - The output node.
  7013. * @param {Node} callNode - The call node.
  7014. */
  7015. constructor( outputNode, callNode ) {
  7016. super();
  7017. /**
  7018. * This flag can be used for type testing.
  7019. *
  7020. * @type {boolean}
  7021. * @readonly
  7022. * @default true
  7023. */
  7024. this.isBypassNode = true;
  7025. /**
  7026. * The output node.
  7027. *
  7028. * @type {Node}
  7029. */
  7030. this.outputNode = outputNode;
  7031. /**
  7032. * The call node.
  7033. *
  7034. * @type {Node}
  7035. */
  7036. this.callNode = callNode;
  7037. }
  7038. getNodeType( builder ) {
  7039. return this.outputNode.getNodeType( builder );
  7040. }
  7041. generate( builder ) {
  7042. const snippet = this.callNode.build( builder, 'void' );
  7043. if ( snippet !== '' ) {
  7044. builder.addLineFlowCode( snippet, this );
  7045. }
  7046. return this.outputNode.build( builder );
  7047. }
  7048. }
  7049. /**
  7050. * TSL function for creating a bypass node.
  7051. *
  7052. * @tsl
  7053. * @function
  7054. * @param {Node} outputNode - The output node.
  7055. * @param {Node} callNode - The call node.
  7056. * @returns {BypassNode}
  7057. */
  7058. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  7059. addMethodChaining( 'bypass', bypass );
  7060. /**
  7061. * This node allows to remap a node value from one range into another. E.g a value of
  7062. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  7063. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  7064. *
  7065. * @augments Node
  7066. */
  7067. class RemapNode extends Node {
  7068. static get type() {
  7069. return 'RemapNode';
  7070. }
  7071. /**
  7072. * Constructs a new remap node.
  7073. *
  7074. * @param {Node} node - The node that should be remapped.
  7075. * @param {Node} inLowNode - The source or current lower bound of the range.
  7076. * @param {Node} inHighNode - The source or current upper bound of the range.
  7077. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  7078. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  7079. */
  7080. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  7081. super();
  7082. /**
  7083. * The node that should be remapped.
  7084. *
  7085. * @type {Node}
  7086. */
  7087. this.node = node;
  7088. /**
  7089. * The source or current lower bound of the range.
  7090. *
  7091. * @type {Node}
  7092. */
  7093. this.inLowNode = inLowNode;
  7094. /**
  7095. * The source or current upper bound of the range.
  7096. *
  7097. * @type {Node}
  7098. */
  7099. this.inHighNode = inHighNode;
  7100. /**
  7101. * The target lower bound of the range.
  7102. *
  7103. * @type {Node}
  7104. * @default float(0)
  7105. */
  7106. this.outLowNode = outLowNode;
  7107. /**
  7108. * The target upper bound of the range.
  7109. *
  7110. * @type {Node}
  7111. * @default float(1)
  7112. */
  7113. this.outHighNode = outHighNode;
  7114. /**
  7115. * Whether the node value should be clamped before
  7116. * remapping it to the target range.
  7117. *
  7118. * @type {boolean}
  7119. * @default true
  7120. */
  7121. this.doClamp = true;
  7122. }
  7123. setup() {
  7124. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  7125. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  7126. if ( doClamp === true ) t = t.clamp();
  7127. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  7128. }
  7129. }
  7130. /**
  7131. * TSL function for creating a remap node.
  7132. *
  7133. * @tsl
  7134. * @function
  7135. * @param {Node} node - The node that should be remapped.
  7136. * @param {Node} inLowNode - The source or current lower bound of the range.
  7137. * @param {Node} inHighNode - The source or current upper bound of the range.
  7138. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7139. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7140. * @returns {RemapNode}
  7141. */
  7142. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  7143. /**
  7144. * TSL function for creating a remap node, but with enabled clamping.
  7145. *
  7146. * @tsl
  7147. * @function
  7148. * @param {Node} node - The node that should be remapped.
  7149. * @param {Node} inLowNode - The source or current lower bound of the range.
  7150. * @param {Node} inHighNode - The source or current upper bound of the range.
  7151. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  7152. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  7153. * @returns {RemapNode}
  7154. */
  7155. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  7156. addMethodChaining( 'remap', remap );
  7157. addMethodChaining( 'remapClamp', remapClamp );
  7158. /**
  7159. * This class can be used to implement basic expressions in shader code.
  7160. * Basic examples for that are `return`, `continue` or `discard` statements.
  7161. *
  7162. * @augments Node
  7163. */
  7164. class ExpressionNode extends Node {
  7165. static get type() {
  7166. return 'ExpressionNode';
  7167. }
  7168. /**
  7169. * Constructs a new expression node.
  7170. *
  7171. * @param {string} [snippet=''] - The native code snippet.
  7172. * @param {string} [nodeType='void'] - The node type.
  7173. */
  7174. constructor( snippet = '', nodeType = 'void' ) {
  7175. super( nodeType );
  7176. /**
  7177. * The native code snippet.
  7178. *
  7179. * @type {string}
  7180. * @default ''
  7181. */
  7182. this.snippet = snippet;
  7183. }
  7184. generate( builder, output ) {
  7185. const type = this.getNodeType( builder );
  7186. const snippet = this.snippet;
  7187. if ( type === 'void' ) {
  7188. builder.addLineFlowCode( snippet, this );
  7189. } else {
  7190. return builder.format( snippet, type, output );
  7191. }
  7192. }
  7193. }
  7194. /**
  7195. * TSL function for creating an expression node.
  7196. *
  7197. * @tsl
  7198. * @function
  7199. * @param {string} [snippet] - The native code snippet.
  7200. * @param {?string} [nodeType='void'] - The node type.
  7201. * @returns {ExpressionNode}
  7202. */
  7203. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  7204. /**
  7205. * Represents a `discard` shader operation in TSL.
  7206. *
  7207. * @tsl
  7208. * @function
  7209. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  7210. * @return {Node} The `discard` expression.
  7211. */
  7212. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  7213. /**
  7214. * Represents a `return` shader operation in TSL.
  7215. *
  7216. * @tsl
  7217. * @function
  7218. * @return {ExpressionNode} The `return` expression.
  7219. */
  7220. const Return = () => expression( 'return' ).toStack();
  7221. addMethodChaining( 'discard', Discard );
  7222. /**
  7223. * Normally, tone mapping and color conversion happens automatically
  7224. * before outputting pixel too the default (screen) framebuffer. In certain
  7225. * post processing setups this happens to late because certain effects
  7226. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  7227. * to apply tone mapping and color space conversion at an arbitrary point
  7228. * in the effect chain.
  7229. *
  7230. * When applying tone mapping and color space conversion manually with this node,
  7231. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  7232. *
  7233. * ```js
  7234. * const postProcessing = new PostProcessing( renderer );
  7235. * postProcessing.outputColorTransform = false;
  7236. *
  7237. * const scenePass = pass( scene, camera );
  7238. * const outputPass = renderOutput( scenePass );
  7239. *
  7240. * postProcessing.outputNode = outputPass;
  7241. * ```
  7242. *
  7243. * @augments TempNode
  7244. */
  7245. class RenderOutputNode extends TempNode {
  7246. static get type() {
  7247. return 'RenderOutputNode';
  7248. }
  7249. /**
  7250. * Constructs a new render output node.
  7251. *
  7252. * @param {Node} colorNode - The color node to process.
  7253. * @param {?number} toneMapping - The tone mapping type.
  7254. * @param {?string} outputColorSpace - The output color space.
  7255. */
  7256. constructor( colorNode, toneMapping, outputColorSpace ) {
  7257. super( 'vec4' );
  7258. /**
  7259. * The color node to process.
  7260. *
  7261. * @type {Node}
  7262. */
  7263. this.colorNode = colorNode;
  7264. /**
  7265. * The tone mapping type.
  7266. *
  7267. * @type {?number}
  7268. */
  7269. this.toneMapping = toneMapping;
  7270. /**
  7271. * The output color space.
  7272. *
  7273. * @type {?string}
  7274. */
  7275. this.outputColorSpace = outputColorSpace;
  7276. /**
  7277. * This flag can be used for type testing.
  7278. *
  7279. * @type {boolean}
  7280. * @readonly
  7281. * @default true
  7282. */
  7283. this.isRenderOutputNode = true;
  7284. }
  7285. setup( { context } ) {
  7286. let outputNode = this.colorNode || context.color;
  7287. // tone mapping
  7288. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  7289. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  7290. if ( toneMapping !== NoToneMapping ) {
  7291. outputNode = outputNode.toneMapping( toneMapping );
  7292. }
  7293. // working to output color space
  7294. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  7295. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  7296. }
  7297. return outputNode;
  7298. }
  7299. }
  7300. /**
  7301. * TSL function for creating a posterize node.
  7302. *
  7303. * @tsl
  7304. * @function
  7305. * @param {Node} color - The color node to process.
  7306. * @param {?number} [toneMapping=null] - The tone mapping type.
  7307. * @param {?string} [outputColorSpace=null] - The output color space.
  7308. * @returns {RenderOutputNode}
  7309. */
  7310. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  7311. addMethodChaining( 'renderOutput', renderOutput );
  7312. class DebugNode extends TempNode {
  7313. static get type() {
  7314. return 'DebugNode';
  7315. }
  7316. constructor( node, callback = null ) {
  7317. super();
  7318. this.node = node;
  7319. this.callback = callback;
  7320. }
  7321. getNodeType( builder ) {
  7322. return this.node.getNodeType( builder );
  7323. }
  7324. setup( builder ) {
  7325. return this.node.build( builder );
  7326. }
  7327. analyze( builder ) {
  7328. return this.node.build( builder );
  7329. }
  7330. generate( builder ) {
  7331. const callback = this.callback;
  7332. const snippet = this.node.build( builder );
  7333. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  7334. const border = '-'.repeat( title.length );
  7335. let code = '';
  7336. code += '// #' + title + '#\n';
  7337. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  7338. code += '/* ... */ ' + snippet + ' /* ... */\n';
  7339. code += '// #' + border + '#\n';
  7340. if ( callback !== null ) {
  7341. callback( builder, code );
  7342. } else {
  7343. console.log( code );
  7344. }
  7345. return snippet;
  7346. }
  7347. }
  7348. /**
  7349. * TSL function for creating a debug node.
  7350. *
  7351. * @tsl
  7352. * @function
  7353. * @param {Node} node - The node to debug.
  7354. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  7355. * @returns {DebugNode}
  7356. */
  7357. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) ).toStack();
  7358. addMethodChaining( 'debug', debug );
  7359. // Non-PURE exports list, side-effects are required here.
  7360. // TSL Base Syntax
  7361. function addNodeElement( name/*, nodeElement*/ ) {
  7362. console.warn( 'THREE.TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  7363. }
  7364. /**
  7365. * Base class for representing shader attributes as nodes.
  7366. *
  7367. * @augments Node
  7368. */
  7369. class AttributeNode extends Node {
  7370. static get type() {
  7371. return 'AttributeNode';
  7372. }
  7373. /**
  7374. * Constructs a new attribute node.
  7375. *
  7376. * @param {string} attributeName - The name of the attribute.
  7377. * @param {?string} nodeType - The node type.
  7378. */
  7379. constructor( attributeName, nodeType = null ) {
  7380. super( nodeType );
  7381. /**
  7382. * `AttributeNode` sets this property to `true` by default.
  7383. *
  7384. * @type {boolean}
  7385. * @default true
  7386. */
  7387. this.global = true;
  7388. this._attributeName = attributeName;
  7389. }
  7390. getHash( builder ) {
  7391. return this.getAttributeName( builder );
  7392. }
  7393. getNodeType( builder ) {
  7394. let nodeType = this.nodeType;
  7395. if ( nodeType === null ) {
  7396. const attributeName = this.getAttributeName( builder );
  7397. if ( builder.hasGeometryAttribute( attributeName ) ) {
  7398. const attribute = builder.geometry.getAttribute( attributeName );
  7399. nodeType = builder.getTypeFromAttribute( attribute );
  7400. } else {
  7401. nodeType = 'float';
  7402. }
  7403. }
  7404. return nodeType;
  7405. }
  7406. /**
  7407. * Sets the attribute name to the given value. The method can be
  7408. * overwritten in derived classes if the final name must be computed
  7409. * analytically.
  7410. *
  7411. * @param {string} attributeName - The name of the attribute.
  7412. * @return {AttributeNode} A reference to this node.
  7413. */
  7414. setAttributeName( attributeName ) {
  7415. this._attributeName = attributeName;
  7416. return this;
  7417. }
  7418. /**
  7419. * Returns the attribute name of this node. The method can be
  7420. * overwritten in derived classes if the final name must be computed
  7421. * analytically.
  7422. *
  7423. * @param {NodeBuilder} builder - The current node builder.
  7424. * @return {string} The attribute name.
  7425. */
  7426. getAttributeName( /*builder*/ ) {
  7427. return this._attributeName;
  7428. }
  7429. generate( builder ) {
  7430. const attributeName = this.getAttributeName( builder );
  7431. const nodeType = this.getNodeType( builder );
  7432. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  7433. if ( geometryAttribute === true ) {
  7434. const attribute = builder.geometry.getAttribute( attributeName );
  7435. const attributeType = builder.getTypeFromAttribute( attribute );
  7436. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  7437. if ( builder.shaderStage === 'vertex' ) {
  7438. return builder.format( nodeAttribute.name, attributeType, nodeType );
  7439. } else {
  7440. const nodeVarying = varying( this );
  7441. return nodeVarying.build( builder, nodeType );
  7442. }
  7443. } else {
  7444. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  7445. return builder.generateConst( nodeType );
  7446. }
  7447. }
  7448. serialize( data ) {
  7449. super.serialize( data );
  7450. data.global = this.global;
  7451. data._attributeName = this._attributeName;
  7452. }
  7453. deserialize( data ) {
  7454. super.deserialize( data );
  7455. this.global = data.global;
  7456. this._attributeName = data._attributeName;
  7457. }
  7458. }
  7459. /**
  7460. * TSL function for creating an attribute node.
  7461. *
  7462. * @tsl
  7463. * @function
  7464. * @param {string} name - The name of the attribute.
  7465. * @param {?string} [nodeType=null] - The node type.
  7466. * @returns {AttributeNode}
  7467. */
  7468. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  7469. /**
  7470. * TSL function for creating an uv attribute node with the given index.
  7471. *
  7472. * @tsl
  7473. * @function
  7474. * @param {number} [index=0] - The uv index.
  7475. * @return {AttributeNode<vec2>} The uv attribute node.
  7476. */
  7477. const uv$1 = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  7478. /**
  7479. * A node that represents the dimensions of a texture. The texture size is
  7480. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  7481. * or `textureSize()`.
  7482. *
  7483. * @augments Node
  7484. */
  7485. class TextureSizeNode extends Node {
  7486. static get type() {
  7487. return 'TextureSizeNode';
  7488. }
  7489. /**
  7490. * Constructs a new texture size node.
  7491. *
  7492. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7493. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7494. */
  7495. constructor( textureNode, levelNode = null ) {
  7496. super( 'uvec2' );
  7497. /**
  7498. * This flag can be used for type testing.
  7499. *
  7500. * @type {boolean}
  7501. * @readonly
  7502. * @default true
  7503. */
  7504. this.isTextureSizeNode = true;
  7505. /**
  7506. * A texture node which size should be retrieved.
  7507. *
  7508. * @type {TextureNode}
  7509. */
  7510. this.textureNode = textureNode;
  7511. /**
  7512. * A level node which defines the requested mip.
  7513. *
  7514. * @type {Node<int>}
  7515. * @default null
  7516. */
  7517. this.levelNode = levelNode;
  7518. }
  7519. generate( builder, output ) {
  7520. const textureProperty = this.textureNode.build( builder, 'property' );
  7521. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7522. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7523. }
  7524. }
  7525. /**
  7526. * TSL function for creating a texture size node.
  7527. *
  7528. * @tsl
  7529. * @function
  7530. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7531. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7532. * @returns {TextureSizeNode}
  7533. */
  7534. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  7535. /**
  7536. * A special type of uniform node that computes the
  7537. * maximum mipmap level for a given texture node.
  7538. *
  7539. * ```js
  7540. * const level = maxMipLevel( textureNode );
  7541. * ```
  7542. *
  7543. * @augments UniformNode
  7544. */
  7545. class MaxMipLevelNode extends UniformNode {
  7546. static get type() {
  7547. return 'MaxMipLevelNode';
  7548. }
  7549. /**
  7550. * Constructs a new max mip level node.
  7551. *
  7552. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7553. */
  7554. constructor( textureNode ) {
  7555. super( 0 );
  7556. /**
  7557. * The texture node to compute the max mip level for.
  7558. *
  7559. * @private
  7560. * @type {TextureNode}
  7561. */
  7562. this._textureNode = textureNode;
  7563. /**
  7564. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  7565. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  7566. *
  7567. * @type {string}
  7568. * @default 'frame'
  7569. */
  7570. this.updateType = NodeUpdateType.FRAME;
  7571. }
  7572. /**
  7573. * The texture node to compute the max mip level for.
  7574. *
  7575. * @readonly
  7576. * @type {TextureNode}
  7577. */
  7578. get textureNode() {
  7579. return this._textureNode;
  7580. }
  7581. /**
  7582. * The texture.
  7583. *
  7584. * @readonly
  7585. * @type {Texture}
  7586. */
  7587. get texture() {
  7588. return this._textureNode.value;
  7589. }
  7590. update() {
  7591. const texture = this.texture;
  7592. const images = texture.images;
  7593. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7594. if ( image && image.width !== undefined ) {
  7595. const { width, height } = image;
  7596. this.value = Math.log2( Math.max( width, height ) );
  7597. }
  7598. }
  7599. }
  7600. /**
  7601. * TSL function for creating a max mip level node.
  7602. *
  7603. * @tsl
  7604. * @function
  7605. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7606. * @returns {MaxMipLevelNode}
  7607. */
  7608. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7609. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  7610. /**
  7611. * This type of uniform node represents a 2D texture.
  7612. *
  7613. * @augments UniformNode
  7614. */
  7615. class TextureNode extends UniformNode {
  7616. static get type() {
  7617. return 'TextureNode';
  7618. }
  7619. /**
  7620. * Constructs a new texture node.
  7621. *
  7622. * @param {Texture} [value=EmptyTexture] - The texture.
  7623. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7624. * @param {?Node<int>} [levelNode=null] - The level node.
  7625. * @param {?Node<float>} [biasNode=null] - The bias node.
  7626. */
  7627. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  7628. super( value );
  7629. /**
  7630. * This flag can be used for type testing.
  7631. *
  7632. * @type {boolean}
  7633. * @readonly
  7634. * @default true
  7635. */
  7636. this.isTextureNode = true;
  7637. /**
  7638. * Represents the texture coordinates.
  7639. *
  7640. * @type {?Node<vec2|vec3>}
  7641. * @default null
  7642. */
  7643. this.uvNode = uvNode;
  7644. /**
  7645. * Represents the mip level that should be selected.
  7646. *
  7647. * @type {?Node<int>}
  7648. * @default null
  7649. */
  7650. this.levelNode = levelNode;
  7651. /**
  7652. * Represents the bias to be applied during level-of-detail computation.
  7653. *
  7654. * @type {?Node<float>}
  7655. * @default null
  7656. */
  7657. this.biasNode = biasNode;
  7658. /**
  7659. * Represents a reference value a texture sample is compared to.
  7660. *
  7661. * @type {?Node<float>}
  7662. * @default null
  7663. */
  7664. this.compareNode = null;
  7665. /**
  7666. * When using texture arrays, the depth node defines the layer to select.
  7667. *
  7668. * @type {?Node<int>}
  7669. * @default null
  7670. */
  7671. this.depthNode = null;
  7672. /**
  7673. * When defined, a texture is sampled using explicit gradients.
  7674. *
  7675. * @type {?Array<Node<vec2>>}
  7676. * @default null
  7677. */
  7678. this.gradNode = null;
  7679. /**
  7680. * Represents the optional texel offset applied to the unnormalized texture
  7681. * coordinate before sampling the texture.
  7682. *
  7683. * @type {?Node<ivec2|ivec3>}
  7684. * @default null
  7685. */
  7686. this.offsetNode = null;
  7687. /**
  7688. * Whether texture values should be sampled or fetched.
  7689. *
  7690. * @type {boolean}
  7691. * @default true
  7692. */
  7693. this.sampler = true;
  7694. /**
  7695. * Whether the uv transformation matrix should be
  7696. * automatically updated or not. Use `setUpdateMatrix()`
  7697. * if you want to change the value of the property.
  7698. *
  7699. * @type {boolean}
  7700. * @default false
  7701. */
  7702. this.updateMatrix = false;
  7703. /**
  7704. * By default the `update()` method is not executed. `setUpdateMatrix()`
  7705. * sets the value to `frame` when the uv transformation matrix should
  7706. * automatically be updated.
  7707. *
  7708. * @type {string}
  7709. * @default 'none'
  7710. */
  7711. this.updateType = NodeUpdateType.NONE;
  7712. /**
  7713. * The reference node.
  7714. *
  7715. * @type {?Node}
  7716. * @default null
  7717. */
  7718. this.referenceNode = null;
  7719. /**
  7720. * The texture value is stored in a private property.
  7721. *
  7722. * @private
  7723. * @type {Texture}
  7724. */
  7725. this._value = value;
  7726. /**
  7727. * The uniform node that represents the uv transformation matrix.
  7728. *
  7729. * @private
  7730. * @type {?UniformNode<mat3>}
  7731. */
  7732. this._matrixUniform = null;
  7733. this.setUpdateMatrix( uvNode === null );
  7734. }
  7735. set value( value ) {
  7736. if ( this.referenceNode ) {
  7737. this.referenceNode.value = value;
  7738. } else {
  7739. this._value = value;
  7740. }
  7741. }
  7742. /**
  7743. * The texture value.
  7744. *
  7745. * @type {Texture}
  7746. */
  7747. get value() {
  7748. return this.referenceNode ? this.referenceNode.value : this._value;
  7749. }
  7750. /**
  7751. * Overwritten since the uniform hash is defined by the texture's UUID.
  7752. *
  7753. * @param {NodeBuilder} builder - The current node builder.
  7754. * @return {string} The uniform hash.
  7755. */
  7756. getUniformHash( /*builder*/ ) {
  7757. return this.value.uuid;
  7758. }
  7759. /**
  7760. * Overwritten since the node type is inferred from the texture type.
  7761. *
  7762. * @param {NodeBuilder} builder - The current node builder.
  7763. * @return {string} The node type.
  7764. */
  7765. getNodeType( /*builder*/ ) {
  7766. if ( this.value.isDepthTexture === true ) return 'float';
  7767. if ( this.value.type === UnsignedIntType ) {
  7768. return 'uvec4';
  7769. } else if ( this.value.type === IntType ) {
  7770. return 'ivec4';
  7771. }
  7772. return 'vec4';
  7773. }
  7774. /**
  7775. * Overwrites the default implementation to return a fixed value `'texture'`.
  7776. *
  7777. * @param {NodeBuilder} builder - The current node builder.
  7778. * @return {string} The input type.
  7779. */
  7780. getInputType( /*builder*/ ) {
  7781. return 'texture';
  7782. }
  7783. /**
  7784. * Returns a default uvs based on the current texture's channel.
  7785. *
  7786. * @return {AttributeNode<vec2>} The default uvs.
  7787. */
  7788. getDefaultUV() {
  7789. return uv$1( this.value.channel );
  7790. }
  7791. /**
  7792. * Overwritten to always return the texture reference of the node.
  7793. *
  7794. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  7795. * @return {Texture} The texture reference.
  7796. */
  7797. updateReference( /*state*/ ) {
  7798. return this.value;
  7799. }
  7800. /**
  7801. * Transforms the given uv node with the texture transformation matrix.
  7802. *
  7803. * @param {Node} uvNode - The uv node to transform.
  7804. * @return {Node} The transformed uv node.
  7805. */
  7806. getTransformedUV( uvNode ) {
  7807. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  7808. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  7809. }
  7810. /**
  7811. * Defines whether the uv transformation matrix should automatically be updated or not.
  7812. *
  7813. * @param {boolean} value - The update toggle.
  7814. * @return {TextureNode} A reference to this node.
  7815. */
  7816. setUpdateMatrix( value ) {
  7817. this.updateMatrix = value;
  7818. this.updateType = value ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  7819. return this;
  7820. }
  7821. /**
  7822. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  7823. * to modify the uv node for correct sampling.
  7824. *
  7825. * @param {NodeBuilder} builder - The current node builder.
  7826. * @param {Node} uvNode - The uv node to setup.
  7827. * @return {Node} The updated uv node.
  7828. */
  7829. setupUV( builder, uvNode ) {
  7830. const texture = this.value;
  7831. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  7832. if ( this.sampler ) {
  7833. uvNode = uvNode.flipY();
  7834. } else {
  7835. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  7836. }
  7837. }
  7838. return uvNode;
  7839. }
  7840. /**
  7841. * Setups texture node by preparing the internal nodes for code generation.
  7842. *
  7843. * @param {NodeBuilder} builder - The current node builder.
  7844. */
  7845. setup( builder ) {
  7846. const properties = builder.getNodeProperties( this );
  7847. properties.referenceNode = this.referenceNode;
  7848. //
  7849. const texture = this.value;
  7850. if ( ! texture || texture.isTexture !== true ) {
  7851. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  7852. }
  7853. //
  7854. let uvNode = this.uvNode;
  7855. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  7856. uvNode = builder.context.getUV( this, builder );
  7857. }
  7858. if ( ! uvNode ) uvNode = this.getDefaultUV();
  7859. if ( this.updateMatrix === true ) {
  7860. uvNode = this.getTransformedUV( uvNode );
  7861. }
  7862. uvNode = this.setupUV( builder, uvNode );
  7863. //
  7864. let levelNode = this.levelNode;
  7865. if ( levelNode === null && builder.context.getTextureLevel ) {
  7866. levelNode = builder.context.getTextureLevel( this );
  7867. }
  7868. //
  7869. properties.uvNode = uvNode;
  7870. properties.levelNode = levelNode;
  7871. properties.biasNode = this.biasNode;
  7872. properties.compareNode = this.compareNode;
  7873. properties.gradNode = this.gradNode;
  7874. properties.depthNode = this.depthNode;
  7875. properties.offsetNode = this.offsetNode;
  7876. }
  7877. /**
  7878. * Generates the uv code snippet.
  7879. *
  7880. * @param {NodeBuilder} builder - The current node builder.
  7881. * @param {Node} uvNode - The uv node to generate code for.
  7882. * @return {string} The generated code snippet.
  7883. */
  7884. generateUV( builder, uvNode ) {
  7885. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  7886. }
  7887. /**
  7888. * Generates the offset code snippet.
  7889. *
  7890. * @param {NodeBuilder} builder - The current node builder.
  7891. * @param {Node} offsetNode - The offset node to generate code for.
  7892. * @return {string} The generated code snippet.
  7893. */
  7894. generateOffset( builder, offsetNode ) {
  7895. return offsetNode.build( builder, 'ivec2' );
  7896. }
  7897. /**
  7898. * Generates the snippet for the texture sampling.
  7899. *
  7900. * @param {NodeBuilder} builder - The current node builder.
  7901. * @param {string} textureProperty - The texture property.
  7902. * @param {string} uvSnippet - The uv snippet.
  7903. * @param {?string} levelSnippet - The level snippet.
  7904. * @param {?string} biasSnippet - The bias snippet.
  7905. * @param {?string} depthSnippet - The depth snippet.
  7906. * @param {?string} compareSnippet - The compare snippet.
  7907. * @param {?Array<string>} gradSnippet - The grad snippet.
  7908. * @param {?string} offsetSnippet - The offset snippet.
  7909. * @return {string} The generated code snippet.
  7910. */
  7911. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet ) {
  7912. const texture = this.value;
  7913. let snippet;
  7914. if ( levelSnippet ) {
  7915. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet );
  7916. } else if ( biasSnippet ) {
  7917. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet );
  7918. } else if ( gradSnippet ) {
  7919. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet );
  7920. } else if ( compareSnippet ) {
  7921. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet );
  7922. } else if ( this.sampler === false ) {
  7923. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  7924. } else {
  7925. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet );
  7926. }
  7927. return snippet;
  7928. }
  7929. /**
  7930. * Generates the code snippet of the texture node.
  7931. *
  7932. * @param {NodeBuilder} builder - The current node builder.
  7933. * @param {string} output - The current output.
  7934. * @return {string} The generated code snippet.
  7935. */
  7936. generate( builder, output ) {
  7937. const texture = this.value;
  7938. const properties = builder.getNodeProperties( this );
  7939. const textureProperty = super.generate( builder, 'property' );
  7940. if ( /^sampler/.test( output ) ) {
  7941. return textureProperty + '_sampler';
  7942. } else if ( builder.isReference( output ) ) {
  7943. return textureProperty;
  7944. } else {
  7945. const nodeData = builder.getDataFromNode( this );
  7946. let propertyName = nodeData.propertyName;
  7947. if ( propertyName === undefined ) {
  7948. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode, offsetNode } = properties;
  7949. const uvSnippet = this.generateUV( builder, uvNode );
  7950. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  7951. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  7952. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  7953. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  7954. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  7955. const offsetSnippet = offsetNode ? this.generateOffset( builder, offsetNode ) : null;
  7956. const nodeVar = builder.getVarFromNode( this );
  7957. propertyName = builder.getPropertyName( nodeVar );
  7958. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet, offsetSnippet );
  7959. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  7960. nodeData.snippet = snippet;
  7961. nodeData.propertyName = propertyName;
  7962. }
  7963. let snippet = propertyName;
  7964. const nodeType = this.getNodeType( builder );
  7965. if ( builder.needsToWorkingColorSpace( texture ) ) {
  7966. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  7967. }
  7968. return builder.format( snippet, nodeType, output );
  7969. }
  7970. }
  7971. /**
  7972. * Sets the sampler value.
  7973. *
  7974. * @param {boolean} value - The sampler value to set.
  7975. * @return {TextureNode} A reference to this texture node.
  7976. */
  7977. setSampler( value ) {
  7978. this.sampler = value;
  7979. return this;
  7980. }
  7981. /**
  7982. * Returns the sampler value.
  7983. *
  7984. * @return {boolean} The sampler value.
  7985. */
  7986. getSampler() {
  7987. return this.sampler;
  7988. }
  7989. // @TODO: Move to TSL
  7990. /**
  7991. * @function
  7992. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  7993. *
  7994. * @param {Node} uvNode - The uv node.
  7995. * @return {TextureNode} A texture node representing the texture sample.
  7996. */
  7997. uv( uvNode ) { // @deprecated, r172
  7998. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  7999. return this.sample( uvNode );
  8000. }
  8001. /**
  8002. * Samples the texture with the given uv node.
  8003. *
  8004. * @param {Node} uvNode - The uv node.
  8005. * @return {TextureNode} A texture node representing the texture sample.
  8006. */
  8007. sample( uvNode ) {
  8008. const textureNode = this.clone();
  8009. textureNode.uvNode = nodeObject( uvNode );
  8010. textureNode.referenceNode = this.getBase();
  8011. return nodeObject( textureNode );
  8012. }
  8013. /**
  8014. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8015. *
  8016. * @param {Node<uvec2>} uvNode - The uv node.
  8017. * @returns {TextureNode} A texture node representing the texture load.
  8018. */
  8019. load( uvNode ) {
  8020. return this.sample( uvNode ).setSampler( false );
  8021. }
  8022. /**
  8023. * Samples a blurred version of the texture by defining an internal bias.
  8024. *
  8025. * @param {Node<float>} amountNode - How blurred the texture should be.
  8026. * @return {TextureNode} A texture node representing the texture sample.
  8027. */
  8028. blur( amountNode ) {
  8029. const textureNode = this.clone();
  8030. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  8031. textureNode.referenceNode = this.getBase();
  8032. const map = textureNode.value;
  8033. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  8034. console.warn( 'THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  8035. textureNode.biasNode = null;
  8036. }
  8037. return nodeObject( textureNode );
  8038. }
  8039. /**
  8040. * Samples a specific mip of the texture.
  8041. *
  8042. * @param {Node<int>} levelNode - The mip level to sample.
  8043. * @return {TextureNode} A texture node representing the texture sample.
  8044. */
  8045. level( levelNode ) {
  8046. const textureNode = this.clone();
  8047. textureNode.levelNode = nodeObject( levelNode );
  8048. textureNode.referenceNode = this.getBase();
  8049. return nodeObject( textureNode );
  8050. }
  8051. /**
  8052. * Returns the texture size of the requested level.
  8053. *
  8054. * @param {Node<int>} levelNode - The level to compute the size for.
  8055. * @return {TextureSizeNode} The texture size.
  8056. */
  8057. size( levelNode ) {
  8058. return textureSize( this, levelNode );
  8059. }
  8060. /**
  8061. * Samples the texture with the given bias.
  8062. *
  8063. * @param {Node<float>} biasNode - The bias node.
  8064. * @return {TextureNode} A texture node representing the texture sample.
  8065. */
  8066. bias( biasNode ) {
  8067. const textureNode = this.clone();
  8068. textureNode.biasNode = nodeObject( biasNode );
  8069. textureNode.referenceNode = this.getBase();
  8070. return nodeObject( textureNode );
  8071. }
  8072. /**
  8073. * Returns the base texture of this node.
  8074. * @return {TextureNode} The base texture node.
  8075. */
  8076. getBase() {
  8077. return this.referenceNode ? this.referenceNode.getBase() : this;
  8078. }
  8079. /**
  8080. * Samples the texture by executing a compare operation.
  8081. *
  8082. * @param {Node<float>} compareNode - The node that defines the compare value.
  8083. * @return {TextureNode} A texture node representing the texture sample.
  8084. */
  8085. compare( compareNode ) {
  8086. const textureNode = this.clone();
  8087. textureNode.compareNode = nodeObject( compareNode );
  8088. textureNode.referenceNode = this.getBase();
  8089. return nodeObject( textureNode );
  8090. }
  8091. /**
  8092. * Samples the texture using an explicit gradient.
  8093. *
  8094. * @param {Node<vec2>} gradNodeX - The gradX node.
  8095. * @param {Node<vec2>} gradNodeY - The gradY node.
  8096. * @return {TextureNode} A texture node representing the texture sample.
  8097. */
  8098. grad( gradNodeX, gradNodeY ) {
  8099. const textureNode = this.clone();
  8100. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  8101. textureNode.referenceNode = this.getBase();
  8102. return nodeObject( textureNode );
  8103. }
  8104. /**
  8105. * Samples the texture by defining a depth node.
  8106. *
  8107. * @param {Node<int>} depthNode - The depth node.
  8108. * @return {TextureNode} A texture node representing the texture sample.
  8109. */
  8110. depth( depthNode ) {
  8111. const textureNode = this.clone();
  8112. textureNode.depthNode = nodeObject( depthNode );
  8113. textureNode.referenceNode = this.getBase();
  8114. return nodeObject( textureNode );
  8115. }
  8116. /**
  8117. * Samples the texture by defining an offset node.
  8118. *
  8119. * @param {Node<ivec2>} offsetNode - The offset node.
  8120. * @return {TextureNode} A texture node representing the texture sample.
  8121. */
  8122. offset( offsetNode ) {
  8123. const textureNode = this.clone();
  8124. textureNode.offsetNode = nodeObject( offsetNode );
  8125. textureNode.referenceNode = this.getBase();
  8126. return nodeObject( textureNode );
  8127. }
  8128. // --
  8129. serialize( data ) {
  8130. super.serialize( data );
  8131. data.value = this.value.toJSON( data.meta ).uuid;
  8132. data.sampler = this.sampler;
  8133. data.updateMatrix = this.updateMatrix;
  8134. data.updateType = this.updateType;
  8135. }
  8136. deserialize( data ) {
  8137. super.deserialize( data );
  8138. this.value = data.meta.textures[ data.value ];
  8139. this.sampler = data.sampler;
  8140. this.updateMatrix = data.updateMatrix;
  8141. this.updateType = data.updateType;
  8142. }
  8143. /**
  8144. * The update is used to implement the update of the uv transformation matrix.
  8145. */
  8146. update() {
  8147. const texture = this.value;
  8148. const matrixUniform = this._matrixUniform;
  8149. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  8150. if ( texture.matrixAutoUpdate === true ) {
  8151. texture.updateMatrix();
  8152. }
  8153. }
  8154. /**
  8155. * Clones the texture node.
  8156. *
  8157. * @return {TextureNode} The cloned texture node.
  8158. */
  8159. clone() {
  8160. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  8161. newNode.sampler = this.sampler;
  8162. newNode.depthNode = this.depthNode;
  8163. newNode.compareNode = this.compareNode;
  8164. newNode.gradNode = this.gradNode;
  8165. newNode.offsetNode = this.offsetNode;
  8166. return newNode;
  8167. }
  8168. }
  8169. /**
  8170. * TSL function for creating a texture node.
  8171. *
  8172. * @tsl
  8173. * @function
  8174. * @param {?Texture} value - The texture.
  8175. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8176. * @param {?Node<int>} [levelNode=null] - The level node.
  8177. * @param {?Node<float>} [biasNode=null] - The bias node.
  8178. * @returns {TextureNode}
  8179. */
  8180. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  8181. /**
  8182. * TSL function for creating a texture node or sample a texture node already existing.
  8183. *
  8184. * @tsl
  8185. * @function
  8186. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8187. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8188. * @param {?Node<int>} [levelNode=null] - The level node.
  8189. * @param {?Node<float>} [biasNode=null] - The bias node.
  8190. * @returns {TextureNode}
  8191. */
  8192. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  8193. let textureNode;
  8194. if ( value && value.isTextureNode === true ) {
  8195. textureNode = nodeObject( value.clone() );
  8196. textureNode.referenceNode = value.getBase(); // Ensure the reference is set to the original node
  8197. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8198. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8199. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8200. } else {
  8201. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  8202. }
  8203. return textureNode;
  8204. };
  8205. /**
  8206. * TSL function for creating a uniform texture node.
  8207. *
  8208. * @tsl
  8209. * @function
  8210. * @param {?Texture} value - The texture.
  8211. * @returns {TextureNode}
  8212. */
  8213. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  8214. /**
  8215. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  8216. *
  8217. * @tsl
  8218. * @function
  8219. * @param {?(Texture|TextureNode)} [value=EmptyTexture] - The texture.
  8220. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  8221. * @param {?Node<int>} [levelNode=null] - The level node.
  8222. * @param {?Node<float>} [biasNode=null] - The bias node.
  8223. * @returns {TextureNode}
  8224. */
  8225. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  8226. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  8227. /**
  8228. * Converts a texture or texture node to a sampler.
  8229. *
  8230. * @tsl
  8231. * @function
  8232. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8233. * @returns {Node}
  8234. */
  8235. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  8236. /**
  8237. * Converts a texture or texture node to a sampler comparison.
  8238. *
  8239. * @tsl
  8240. * @function
  8241. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  8242. * @returns {Node}
  8243. */
  8244. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  8245. /**
  8246. * A special type of uniform node which represents array-like data
  8247. * as uniform buffers. The access usually happens via `element()`
  8248. * which returns an instance of {@link ArrayElementNode}. For example:
  8249. *
  8250. * ```js
  8251. * const bufferNode = buffer( array, 'mat4', count );
  8252. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  8253. * ```
  8254. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  8255. * since it handles more input types and automatically cares about buffer paddings.
  8256. *
  8257. * @augments UniformNode
  8258. */
  8259. class BufferNode extends UniformNode {
  8260. static get type() {
  8261. return 'BufferNode';
  8262. }
  8263. /**
  8264. * Constructs a new buffer node.
  8265. *
  8266. * @param {Array<number>} value - Array-like buffer data.
  8267. * @param {string} bufferType - The data type of the buffer.
  8268. * @param {number} [bufferCount=0] - The count of buffer elements.
  8269. */
  8270. constructor( value, bufferType, bufferCount = 0 ) {
  8271. super( value, bufferType );
  8272. /**
  8273. * This flag can be used for type testing.
  8274. *
  8275. * @type {boolean}
  8276. * @readonly
  8277. * @default true
  8278. */
  8279. this.isBufferNode = true;
  8280. /**
  8281. * The data type of the buffer.
  8282. *
  8283. * @type {string}
  8284. */
  8285. this.bufferType = bufferType;
  8286. /**
  8287. * The uniform node that holds the value of the reference node.
  8288. *
  8289. * @type {number}
  8290. * @default 0
  8291. */
  8292. this.bufferCount = bufferCount;
  8293. }
  8294. /**
  8295. * The data type of the buffer elements.
  8296. *
  8297. * @param {NodeBuilder} builder - The current node builder.
  8298. * @return {string} The element type.
  8299. */
  8300. getElementType( builder ) {
  8301. return this.getNodeType( builder );
  8302. }
  8303. /**
  8304. * Overwrites the default implementation to return a fixed value `'buffer'`.
  8305. *
  8306. * @param {NodeBuilder} builder - The current node builder.
  8307. * @return {string} The input type.
  8308. */
  8309. getInputType( /*builder*/ ) {
  8310. return 'buffer';
  8311. }
  8312. }
  8313. /**
  8314. * TSL function for creating a buffer node.
  8315. *
  8316. * @tsl
  8317. * @function
  8318. * @param {Array<number>} value - Array-like buffer data.
  8319. * @param {string} type - The data type of a buffer element.
  8320. * @param {number} count - The count of buffer elements.
  8321. * @returns {BufferNode}
  8322. */
  8323. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  8324. /**
  8325. * Represents the element access on uniform array nodes.
  8326. *
  8327. * @augments ArrayElementNode
  8328. */
  8329. class UniformArrayElementNode extends ArrayElementNode {
  8330. static get type() {
  8331. return 'UniformArrayElementNode';
  8332. }
  8333. /**
  8334. * Constructs a new buffer node.
  8335. *
  8336. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  8337. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  8338. */
  8339. constructor( uniformArrayNode, indexNode ) {
  8340. super( uniformArrayNode, indexNode );
  8341. /**
  8342. * This flag can be used for type testing.
  8343. *
  8344. * @type {boolean}
  8345. * @readonly
  8346. * @default true
  8347. */
  8348. this.isArrayBufferElementNode = true;
  8349. }
  8350. generate( builder ) {
  8351. const snippet = super.generate( builder );
  8352. const type = this.getNodeType();
  8353. const paddedType = this.node.getPaddedType();
  8354. return builder.format( snippet, paddedType, type );
  8355. }
  8356. }
  8357. /**
  8358. * Similar to {@link BufferNode} this module represents array-like data as
  8359. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  8360. * data types in the array (e.g `three.js` primitives) and automatically
  8361. * manage buffer padding. It should be the first choice when working with
  8362. * uniforms buffers.
  8363. * ```js
  8364. * const tintColors = uniformArray( [
  8365. * new Color( 1, 0, 0 ),
  8366. * new Color( 0, 1, 0 ),
  8367. * new Color( 0, 0, 1 )
  8368. * ], 'color' );
  8369. *
  8370. * const redColor = tintColors.element( 0 );
  8371. *
  8372. * @augments BufferNode
  8373. */
  8374. class UniformArrayNode extends BufferNode {
  8375. static get type() {
  8376. return 'UniformArrayNode';
  8377. }
  8378. /**
  8379. * Constructs a new uniform array node.
  8380. *
  8381. * @param {Array<any>} value - Array holding the buffer data.
  8382. * @param {?string} [elementType=null] - The data type of a buffer element.
  8383. */
  8384. constructor( value, elementType = null ) {
  8385. super( null );
  8386. /**
  8387. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  8388. * hold number primitives as well as three.js objects like vectors, matrices
  8389. * or colors.
  8390. *
  8391. * @type {Array<any>}
  8392. */
  8393. this.array = value;
  8394. /**
  8395. * The data type of an array element.
  8396. *
  8397. * @type {string}
  8398. */
  8399. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  8400. /**
  8401. * The padded type. Uniform buffers must conform to a certain buffer layout
  8402. * so a separate type is computed to ensure correct buffer size.
  8403. *
  8404. * @type {string}
  8405. */
  8406. this.paddedType = this.getPaddedType();
  8407. /**
  8408. * Overwritten since uniform array nodes are updated per render.
  8409. *
  8410. * @type {string}
  8411. * @default 'render'
  8412. */
  8413. this.updateType = NodeUpdateType.RENDER;
  8414. /**
  8415. * This flag can be used for type testing.
  8416. *
  8417. * @type {boolean}
  8418. * @readonly
  8419. * @default true
  8420. */
  8421. this.isArrayBufferNode = true;
  8422. }
  8423. /**
  8424. * This method is overwritten since the node type is inferred from the
  8425. * {@link UniformArrayNode#paddedType}.
  8426. *
  8427. * @param {NodeBuilder} builder - The current node builder.
  8428. * @return {string} The node type.
  8429. */
  8430. getNodeType( /*builder*/ ) {
  8431. return this.paddedType;
  8432. }
  8433. /**
  8434. * The data type of the array elements.
  8435. *
  8436. * @param {NodeBuilder} builder - The current node builder.
  8437. * @return {string} The element type.
  8438. */
  8439. getElementType() {
  8440. return this.elementType;
  8441. }
  8442. /**
  8443. * Returns the padded type based on the element type.
  8444. *
  8445. * @return {string} The padded type.
  8446. */
  8447. getPaddedType() {
  8448. const elementType = this.elementType;
  8449. let paddedType = 'vec4';
  8450. if ( elementType === 'mat2' ) {
  8451. paddedType = 'mat2';
  8452. } else if ( /mat/.test( elementType ) === true ) {
  8453. paddedType = 'mat4';
  8454. } else if ( elementType.charAt( 0 ) === 'i' ) {
  8455. paddedType = 'ivec4';
  8456. } else if ( elementType.charAt( 0 ) === 'u' ) {
  8457. paddedType = 'uvec4';
  8458. }
  8459. return paddedType;
  8460. }
  8461. /**
  8462. * The update makes sure to correctly transfer the data from the (complex) objects
  8463. * in the array to the internal, correctly padded value buffer.
  8464. *
  8465. * @param {NodeFrame} frame - A reference to the current node frame.
  8466. */
  8467. update( /*frame*/ ) {
  8468. const { array, value } = this;
  8469. const elementType = this.elementType;
  8470. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  8471. for ( let i = 0; i < array.length; i ++ ) {
  8472. const index = i * 4;
  8473. value[ index ] = array[ i ];
  8474. }
  8475. } else if ( elementType === 'color' ) {
  8476. for ( let i = 0; i < array.length; i ++ ) {
  8477. const index = i * 4;
  8478. const vector = array[ i ];
  8479. value[ index ] = vector.r;
  8480. value[ index + 1 ] = vector.g;
  8481. value[ index + 2 ] = vector.b || 0;
  8482. //value[ index + 3 ] = vector.a || 0;
  8483. }
  8484. } else if ( elementType === 'mat2' ) {
  8485. for ( let i = 0; i < array.length; i ++ ) {
  8486. const index = i * 4;
  8487. const matrix = array[ i ];
  8488. value[ index ] = matrix.elements[ 0 ];
  8489. value[ index + 1 ] = matrix.elements[ 1 ];
  8490. value[ index + 2 ] = matrix.elements[ 2 ];
  8491. value[ index + 3 ] = matrix.elements[ 3 ];
  8492. }
  8493. } else if ( elementType === 'mat3' ) {
  8494. for ( let i = 0; i < array.length; i ++ ) {
  8495. const index = i * 16;
  8496. const matrix = array[ i ];
  8497. value[ index ] = matrix.elements[ 0 ];
  8498. value[ index + 1 ] = matrix.elements[ 1 ];
  8499. value[ index + 2 ] = matrix.elements[ 2 ];
  8500. value[ index + 4 ] = matrix.elements[ 3 ];
  8501. value[ index + 5 ] = matrix.elements[ 4 ];
  8502. value[ index + 6 ] = matrix.elements[ 5 ];
  8503. value[ index + 8 ] = matrix.elements[ 6 ];
  8504. value[ index + 9 ] = matrix.elements[ 7 ];
  8505. value[ index + 10 ] = matrix.elements[ 8 ];
  8506. value[ index + 15 ] = 1;
  8507. }
  8508. } else if ( elementType === 'mat4' ) {
  8509. for ( let i = 0; i < array.length; i ++ ) {
  8510. const index = i * 16;
  8511. const matrix = array[ i ];
  8512. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  8513. value[ index + i ] = matrix.elements[ i ];
  8514. }
  8515. }
  8516. } else {
  8517. for ( let i = 0; i < array.length; i ++ ) {
  8518. const index = i * 4;
  8519. const vector = array[ i ];
  8520. value[ index ] = vector.x;
  8521. value[ index + 1 ] = vector.y;
  8522. value[ index + 2 ] = vector.z || 0;
  8523. value[ index + 3 ] = vector.w || 0;
  8524. }
  8525. }
  8526. }
  8527. /**
  8528. * Implement the value buffer creation based on the array data.
  8529. *
  8530. * @param {NodeBuilder} builder - A reference to the current node builder.
  8531. * @return {null}
  8532. */
  8533. setup( builder ) {
  8534. const length = this.array.length;
  8535. const elementType = this.elementType;
  8536. let arrayType = Float32Array;
  8537. const paddedType = this.paddedType;
  8538. const paddedElementLength = builder.getTypeLength( paddedType );
  8539. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  8540. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  8541. this.value = new arrayType( length * paddedElementLength );
  8542. this.bufferCount = length;
  8543. this.bufferType = paddedType;
  8544. return super.setup( builder );
  8545. }
  8546. /**
  8547. * Overwrites the default `element()` method to provide element access
  8548. * based on {@link UniformArrayNode}.
  8549. *
  8550. * @param {IndexNode} indexNode - The index node.
  8551. * @return {UniformArrayElementNode}
  8552. */
  8553. element( indexNode ) {
  8554. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  8555. }
  8556. }
  8557. /**
  8558. * TSL function for creating an uniform array node.
  8559. *
  8560. * @tsl
  8561. * @function
  8562. * @param {Array<any>} values - Array-like data.
  8563. * @param {?string} [nodeType] - The data type of the array elements.
  8564. * @returns {UniformArrayNode}
  8565. */
  8566. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  8567. /**
  8568. * The node allows to set values for built-in shader variables. That is
  8569. * required for features like hardware-accelerated vertex clipping.
  8570. *
  8571. * @augments Node
  8572. */
  8573. class BuiltinNode extends Node {
  8574. /**
  8575. * Constructs a new builtin node.
  8576. *
  8577. * @param {string} name - The name of the built-in shader variable.
  8578. */
  8579. constructor( name ) {
  8580. super( 'float' );
  8581. /**
  8582. * The name of the built-in shader variable.
  8583. *
  8584. * @type {string}
  8585. */
  8586. this.name = name;
  8587. /**
  8588. * This flag can be used for type testing.
  8589. *
  8590. * @type {boolean}
  8591. * @readonly
  8592. * @default true
  8593. */
  8594. this.isBuiltinNode = true;
  8595. }
  8596. /**
  8597. * Generates the code snippet of the builtin node.
  8598. *
  8599. * @param {NodeBuilder} builder - The current node builder.
  8600. * @return {string} The generated code snippet.
  8601. */
  8602. generate( /* builder */ ) {
  8603. return this.name;
  8604. }
  8605. }
  8606. /**
  8607. * TSL function for creating a builtin node.
  8608. *
  8609. * @tsl
  8610. * @function
  8611. * @param {string} name - The name of the built-in shader variable.
  8612. * @returns {BuiltinNode}
  8613. */
  8614. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  8615. let _screenSizeVec, _viewportVec;
  8616. /**
  8617. * This node provides a collection of screen related metrics.
  8618. * Depending on {@link ScreenNode#scope}, the nodes can represent
  8619. * resolution or viewport data as well as fragment or uv coordinates.
  8620. *
  8621. * @augments Node
  8622. */
  8623. class ScreenNode extends Node {
  8624. static get type() {
  8625. return 'ScreenNode';
  8626. }
  8627. /**
  8628. * Constructs a new screen node.
  8629. *
  8630. * @param {('coordinate'|'viewport'|'size'|'uv'|'dpr')} scope - The node's scope.
  8631. */
  8632. constructor( scope ) {
  8633. super();
  8634. /**
  8635. * The node represents different metric depending on which scope is selected.
  8636. *
  8637. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  8638. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  8639. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  8640. * - `ScreenNode.UV`: Normalized coordinates.
  8641. * - `ScreenNode.DPR`: Device pixel ratio.
  8642. *
  8643. * @type {('coordinate'|'viewport'|'size'|'uv'|'dpr')}
  8644. */
  8645. this.scope = scope;
  8646. /**
  8647. * This output node.
  8648. *
  8649. * @type {?Node}
  8650. * @default null
  8651. */
  8652. this._output = null;
  8653. /**
  8654. * This flag can be used for type testing.
  8655. *
  8656. * @type {boolean}
  8657. * @readonly
  8658. * @default true
  8659. */
  8660. this.isViewportNode = true;
  8661. }
  8662. /**
  8663. * This method is overwritten since the node type depends on the selected scope.
  8664. *
  8665. * @return {('float'|'vec2'|'vec4')} The node type.
  8666. */
  8667. getNodeType() {
  8668. if ( this.scope === ScreenNode.DPR ) return 'float';
  8669. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  8670. else return 'vec2';
  8671. }
  8672. /**
  8673. * This method is overwritten since the node's update type depends on the selected scope.
  8674. *
  8675. * @return {NodeUpdateType} The update type.
  8676. */
  8677. getUpdateType() {
  8678. let updateType = NodeUpdateType.NONE;
  8679. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT || this.scope === ScreenNode.DPR ) {
  8680. updateType = NodeUpdateType.RENDER;
  8681. }
  8682. this.updateType = updateType;
  8683. return updateType;
  8684. }
  8685. /**
  8686. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  8687. * from the current renderer.
  8688. *
  8689. * @param {NodeFrame} frame - A reference to the current node frame.
  8690. */
  8691. update( { renderer } ) {
  8692. const renderTarget = renderer.getRenderTarget();
  8693. if ( this.scope === ScreenNode.VIEWPORT ) {
  8694. if ( renderTarget !== null ) {
  8695. _viewportVec.copy( renderTarget.viewport );
  8696. } else {
  8697. renderer.getViewport( _viewportVec );
  8698. _viewportVec.multiplyScalar( renderer.getPixelRatio() );
  8699. }
  8700. } else if ( this.scope === ScreenNode.DPR ) {
  8701. this._output.value = renderer.getPixelRatio();
  8702. } else {
  8703. if ( renderTarget !== null ) {
  8704. _screenSizeVec.width = renderTarget.width;
  8705. _screenSizeVec.height = renderTarget.height;
  8706. } else {
  8707. renderer.getDrawingBufferSize( _screenSizeVec );
  8708. }
  8709. }
  8710. }
  8711. setup( /*builder*/ ) {
  8712. const scope = this.scope;
  8713. let output = null;
  8714. if ( scope === ScreenNode.SIZE ) {
  8715. output = uniform( _screenSizeVec || ( _screenSizeVec = new Vector2() ) );
  8716. } else if ( scope === ScreenNode.VIEWPORT ) {
  8717. output = uniform( _viewportVec || ( _viewportVec = new Vector4() ) );
  8718. } else if ( scope === ScreenNode.DPR ) {
  8719. output = uniform( 1 );
  8720. } else {
  8721. output = vec2( screenCoordinate.div( screenSize ) );
  8722. }
  8723. this._output = output;
  8724. return output;
  8725. }
  8726. generate( builder ) {
  8727. if ( this.scope === ScreenNode.COORDINATE ) {
  8728. let coord = builder.getFragCoord();
  8729. if ( builder.isFlipY() ) {
  8730. // follow webgpu standards
  8731. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  8732. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  8733. }
  8734. return coord;
  8735. }
  8736. return super.generate( builder );
  8737. }
  8738. }
  8739. ScreenNode.COORDINATE = 'coordinate';
  8740. ScreenNode.VIEWPORT = 'viewport';
  8741. ScreenNode.SIZE = 'size';
  8742. ScreenNode.UV = 'uv';
  8743. ScreenNode.DPR = 'dpr';
  8744. // Screen
  8745. /**
  8746. * TSL object that represents the current DPR.
  8747. *
  8748. * @tsl
  8749. * @type {ScreenNode<float>}
  8750. */
  8751. const screenDPR = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.DPR );
  8752. /**
  8753. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  8754. *
  8755. * @tsl
  8756. * @type {ScreenNode<vec2>}
  8757. */
  8758. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  8759. /**
  8760. * TSL object that represents the screen resolution in physical pixel units.
  8761. *
  8762. * @tsl
  8763. * @type {ScreenNode<vec2>}
  8764. */
  8765. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  8766. /**
  8767. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  8768. *
  8769. * @tsl
  8770. * @type {ScreenNode<vec2>}
  8771. */
  8772. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  8773. // Viewport
  8774. /**
  8775. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  8776. *
  8777. * @tsl
  8778. * @type {ScreenNode<vec4>}
  8779. */
  8780. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  8781. /**
  8782. * TSL object that represents the viewport resolution in physical pixel units.
  8783. *
  8784. * @tsl
  8785. * @type {ScreenNode<vec2>}
  8786. */
  8787. const viewportSize = viewport.zw;
  8788. /**
  8789. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  8790. *
  8791. * @tsl
  8792. * @type {ScreenNode<vec2>}
  8793. */
  8794. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  8795. /**
  8796. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  8797. *
  8798. * @tsl
  8799. * @type {ScreenNode<vec2>}
  8800. */
  8801. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  8802. // Deprecated
  8803. /**
  8804. * @deprecated since r169. Use {@link screenSize} instead.
  8805. */
  8806. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  8807. console.warn( 'THREE.TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  8808. return screenSize;
  8809. }, 'vec2' ).once() )();
  8810. /**
  8811. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  8812. *
  8813. * @tsl
  8814. * @type {UniformNode<uint>}
  8815. */
  8816. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).setName( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  8817. /**
  8818. * TSL object that represents the `near` value of the camera used for the current render.
  8819. *
  8820. * @tsl
  8821. * @type {UniformNode<float>}
  8822. */
  8823. const cameraNear = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  8824. /**
  8825. * TSL object that represents the `far` value of the camera used for the current render.
  8826. *
  8827. * @tsl
  8828. * @type {UniformNode<float>}
  8829. */
  8830. const cameraFar = /*@__PURE__*/ uniform( 'float' ).setName( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  8831. /**
  8832. * TSL object that represents the projection matrix of the camera used for the current render.
  8833. *
  8834. * @tsl
  8835. * @type {UniformNode<mat4>}
  8836. */
  8837. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8838. let cameraProjectionMatrix;
  8839. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8840. const matrices = [];
  8841. for ( const subCamera of camera.cameras ) {
  8842. matrices.push( subCamera.projectionMatrix );
  8843. }
  8844. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatrices' );
  8845. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrix' );
  8846. } else {
  8847. cameraProjectionMatrix = uniform( 'mat4' ).setName( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  8848. }
  8849. return cameraProjectionMatrix;
  8850. } ).once() )();
  8851. /**
  8852. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  8853. *
  8854. * @tsl
  8855. * @type {UniformNode<mat4>}
  8856. */
  8857. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8858. let cameraProjectionMatrixInverse;
  8859. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8860. const matrices = [];
  8861. for ( const subCamera of camera.cameras ) {
  8862. matrices.push( subCamera.projectionMatrixInverse );
  8863. }
  8864. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraProjectionMatricesInverse' );
  8865. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraProjectionMatrixInverse' );
  8866. } else {
  8867. cameraProjectionMatrixInverse = uniform( 'mat4' ).setName( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  8868. }
  8869. return cameraProjectionMatrixInverse;
  8870. } ).once() )();
  8871. /**
  8872. * TSL object that represents the view matrix of the camera used for the current render.
  8873. *
  8874. * @tsl
  8875. * @type {UniformNode<mat4>}
  8876. */
  8877. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8878. let cameraViewMatrix;
  8879. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8880. const matrices = [];
  8881. for ( const subCamera of camera.cameras ) {
  8882. matrices.push( subCamera.matrixWorldInverse );
  8883. }
  8884. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraViewMatrices' );
  8885. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraViewMatrix' );
  8886. } else {
  8887. cameraViewMatrix = uniform( 'mat4' ).setName( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  8888. }
  8889. return cameraViewMatrix;
  8890. } ).once() )();
  8891. /**
  8892. * TSL object that represents the world matrix of the camera used for the current render.
  8893. *
  8894. * @tsl
  8895. * @type {UniformNode<mat4>}
  8896. */
  8897. const cameraWorldMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8898. let cameraWorldMatrix;
  8899. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8900. const matrices = [];
  8901. for ( const subCamera of camera.cameras ) {
  8902. matrices.push( subCamera.matrixWorld );
  8903. }
  8904. const cameraWorldMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraWorldMatrices' );
  8905. cameraWorldMatrix = cameraWorldMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraWorldMatrix' );
  8906. } else {
  8907. cameraWorldMatrix = uniform( 'mat4' ).setName( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  8908. }
  8909. return cameraWorldMatrix;
  8910. } ).once() )();
  8911. /**
  8912. * TSL object that represents the normal matrix of the camera used for the current render.
  8913. *
  8914. * @tsl
  8915. * @type {UniformNode<mat3>}
  8916. */
  8917. const cameraNormalMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8918. let cameraNormalMatrix;
  8919. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8920. const matrices = [];
  8921. for ( const subCamera of camera.cameras ) {
  8922. matrices.push( subCamera.normalMatrix );
  8923. }
  8924. const cameraNormalMatrices = uniformArray( matrices ).setGroup( renderGroup ).setName( 'cameraNormalMatrices' );
  8925. cameraNormalMatrix = cameraNormalMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraNormalMatrix' );
  8926. } else {
  8927. cameraNormalMatrix = uniform( 'mat3' ).setName( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  8928. }
  8929. return cameraNormalMatrix;
  8930. } ).once() )();
  8931. /**
  8932. * TSL object that represents the position in world space of the camera used for the current render.
  8933. *
  8934. * @tsl
  8935. * @type {UniformNode<vec3>}
  8936. */
  8937. const cameraPosition = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8938. let cameraPosition;
  8939. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8940. const positions = [];
  8941. for ( let i = 0, l = camera.cameras.length; i < l; i ++ ) {
  8942. positions.push( new Vector3() );
  8943. }
  8944. const cameraPositions = uniformArray( positions ).setGroup( renderGroup ).setName( 'cameraPositions' ).onRenderUpdate( ( { camera }, self ) => {
  8945. const subCameras = camera.cameras;
  8946. const array = self.array;
  8947. for ( let i = 0, l = subCameras.length; i < l; i ++ ) {
  8948. array[ i ].setFromMatrixPosition( subCameras[ i ].matrixWorld );
  8949. }
  8950. } );
  8951. cameraPosition = cameraPositions.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toConst( 'cameraPosition' );
  8952. } else {
  8953. cameraPosition = uniform( new Vector3() ).setName( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  8954. }
  8955. return cameraPosition;
  8956. } ).once() )();
  8957. /**
  8958. * TSL object that represents the viewport of the camera used for the current render.
  8959. *
  8960. * @tsl
  8961. * @type {UniformNode<vec4>}
  8962. */
  8963. const cameraViewport = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8964. let cameraViewport;
  8965. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8966. const viewports = [];
  8967. for ( const subCamera of camera.cameras ) {
  8968. viewports.push( subCamera.viewport );
  8969. }
  8970. const cameraViewports = uniformArray( viewports, 'vec4' ).setGroup( renderGroup ).setName( 'cameraViewports' );
  8971. cameraViewport = cameraViewports.element( cameraIndex ).toConst( 'cameraViewport' );
  8972. } else {
  8973. // Fallback for single camera
  8974. cameraViewport = vec4( 0, 0, screenSize.x, screenSize.y ).toConst( 'cameraViewport' );
  8975. }
  8976. return cameraViewport;
  8977. } ).once() )();
  8978. const _sphere = /*@__PURE__*/ new Sphere();
  8979. /**
  8980. * This node can be used to access transformation related metrics of 3D objects.
  8981. * Depending on the selected scope, a different metric is represented as a uniform
  8982. * in the shader. The following scopes are supported:
  8983. *
  8984. * - `POSITION`: The object's position in world space.
  8985. * - `VIEW_POSITION`: The object's position in view/camera space.
  8986. * - `DIRECTION`: The object's direction in world space.
  8987. * - `SCALE`: The object's scale in world space.
  8988. * - `WORLD_MATRIX`: The object's matrix in world space.
  8989. *
  8990. * @augments Node
  8991. */
  8992. class Object3DNode extends Node {
  8993. static get type() {
  8994. return 'Object3DNode';
  8995. }
  8996. /**
  8997. * Constructs a new object 3D node.
  8998. *
  8999. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9000. * @param {?Object3D} [object3d=null] - The 3D object.
  9001. */
  9002. constructor( scope, object3d = null ) {
  9003. super();
  9004. /**
  9005. * The node reports a different type of transformation depending on the scope.
  9006. *
  9007. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  9008. */
  9009. this.scope = scope;
  9010. /**
  9011. * The 3D object.
  9012. *
  9013. * @type {?Object3D}
  9014. * @default null
  9015. */
  9016. this.object3d = object3d;
  9017. /**
  9018. * Overwritten since this type of node is updated per object.
  9019. *
  9020. * @type {string}
  9021. * @default 'object'
  9022. */
  9023. this.updateType = NodeUpdateType.OBJECT;
  9024. /**
  9025. * Holds the value of the node as a uniform.
  9026. *
  9027. * @type {UniformNode}
  9028. */
  9029. this.uniformNode = new UniformNode( null );
  9030. }
  9031. /**
  9032. * Overwritten since the node type is inferred from the scope.
  9033. *
  9034. * @return {('mat4'|'vec3'|'float')} The node type.
  9035. */
  9036. getNodeType() {
  9037. const scope = this.scope;
  9038. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9039. return 'mat4';
  9040. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9041. return 'vec3';
  9042. } else if ( scope === Object3DNode.RADIUS ) {
  9043. return 'float';
  9044. }
  9045. }
  9046. /**
  9047. * Updates the uniform value depending on the scope.
  9048. *
  9049. * @param {NodeFrame} frame - The current node frame.
  9050. */
  9051. update( frame ) {
  9052. const object = this.object3d;
  9053. const uniformNode = this.uniformNode;
  9054. const scope = this.scope;
  9055. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9056. uniformNode.value = object.matrixWorld;
  9057. } else if ( scope === Object3DNode.POSITION ) {
  9058. uniformNode.value = uniformNode.value || new Vector3();
  9059. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9060. } else if ( scope === Object3DNode.SCALE ) {
  9061. uniformNode.value = uniformNode.value || new Vector3();
  9062. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  9063. } else if ( scope === Object3DNode.DIRECTION ) {
  9064. uniformNode.value = uniformNode.value || new Vector3();
  9065. object.getWorldDirection( uniformNode.value );
  9066. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  9067. const camera = frame.camera;
  9068. uniformNode.value = uniformNode.value || new Vector3();
  9069. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  9070. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  9071. } else if ( scope === Object3DNode.RADIUS ) {
  9072. const geometry = frame.object.geometry;
  9073. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  9074. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  9075. uniformNode.value = _sphere.radius;
  9076. }
  9077. }
  9078. /**
  9079. * Generates the code snippet of the uniform node. The node type of the uniform
  9080. * node also depends on the selected scope.
  9081. *
  9082. * @param {NodeBuilder} builder - The current node builder.
  9083. * @return {string} The generated code snippet.
  9084. */
  9085. generate( builder ) {
  9086. const scope = this.scope;
  9087. if ( scope === Object3DNode.WORLD_MATRIX ) {
  9088. this.uniformNode.nodeType = 'mat4';
  9089. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  9090. this.uniformNode.nodeType = 'vec3';
  9091. } else if ( scope === Object3DNode.RADIUS ) {
  9092. this.uniformNode.nodeType = 'float';
  9093. }
  9094. return this.uniformNode.build( builder );
  9095. }
  9096. serialize( data ) {
  9097. super.serialize( data );
  9098. data.scope = this.scope;
  9099. }
  9100. deserialize( data ) {
  9101. super.deserialize( data );
  9102. this.scope = data.scope;
  9103. }
  9104. }
  9105. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  9106. Object3DNode.POSITION = 'position';
  9107. Object3DNode.SCALE = 'scale';
  9108. Object3DNode.VIEW_POSITION = 'viewPosition';
  9109. Object3DNode.DIRECTION = 'direction';
  9110. Object3DNode.RADIUS = 'radius';
  9111. /**
  9112. * TSL function for creating an object 3D node that represents the object's direction in world space.
  9113. *
  9114. * @tsl
  9115. * @function
  9116. * @param {?Object3D} [object3d] - The 3D object.
  9117. * @returns {Object3DNode<vec3>}
  9118. */
  9119. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  9120. /**
  9121. * TSL function for creating an object 3D node that represents the object's world matrix.
  9122. *
  9123. * @tsl
  9124. * @function
  9125. * @param {?Object3D} [object3d] - The 3D object.
  9126. * @returns {Object3DNode<mat4>}
  9127. */
  9128. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  9129. /**
  9130. * TSL function for creating an object 3D node that represents the object's position in world space.
  9131. *
  9132. * @tsl
  9133. * @function
  9134. * @param {?Object3D} [object3d] - The 3D object.
  9135. * @returns {Object3DNode<vec3>}
  9136. */
  9137. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  9138. /**
  9139. * TSL function for creating an object 3D node that represents the object's scale in world space.
  9140. *
  9141. * @tsl
  9142. * @function
  9143. * @param {?Object3D} [object3d] - The 3D object.
  9144. * @returns {Object3DNode<vec3>}
  9145. */
  9146. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  9147. /**
  9148. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  9149. *
  9150. * @tsl
  9151. * @function
  9152. * @param {?Object3D} [object3d] - The 3D object.
  9153. * @returns {Object3DNode<vec3>}
  9154. */
  9155. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  9156. /**
  9157. * TSL function for creating an object 3D node that represents the object's radius.
  9158. *
  9159. * @tsl
  9160. * @function
  9161. * @param {?Object3D} [object3d] - The 3D object.
  9162. * @returns {Object3DNode<float>}
  9163. */
  9164. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  9165. /**
  9166. * This type of node is a specialized version of `Object3DNode`
  9167. * with larger set of model related metrics. Unlike `Object3DNode`,
  9168. * `ModelNode` extracts the reference to the 3D object from the
  9169. * current node frame state.
  9170. *
  9171. * @augments Object3DNode
  9172. */
  9173. class ModelNode extends Object3DNode {
  9174. static get type() {
  9175. return 'ModelNode';
  9176. }
  9177. /**
  9178. * Constructs a new object model node.
  9179. *
  9180. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  9181. */
  9182. constructor( scope ) {
  9183. super( scope );
  9184. }
  9185. /**
  9186. * Extracts the model reference from the frame state and then
  9187. * updates the uniform value depending on the scope.
  9188. *
  9189. * @param {NodeFrame} frame - The current node frame.
  9190. */
  9191. update( frame ) {
  9192. this.object3d = frame.object;
  9193. super.update( frame );
  9194. }
  9195. }
  9196. /**
  9197. * TSL object that represents the object's direction in world space.
  9198. *
  9199. * @tsl
  9200. * @type {ModelNode<vec3>}
  9201. */
  9202. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  9203. /**
  9204. * TSL object that represents the object's world matrix.
  9205. *
  9206. * @tsl
  9207. * @type {ModelNode<mat4>}
  9208. */
  9209. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  9210. /**
  9211. * TSL object that represents the object's position in world space.
  9212. *
  9213. * @tsl
  9214. * @type {ModelNode<vec3>}
  9215. */
  9216. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  9217. /**
  9218. * TSL object that represents the object's scale in world space.
  9219. *
  9220. * @tsl
  9221. * @type {ModelNode<vec3>}
  9222. */
  9223. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  9224. /**
  9225. * TSL object that represents the object's position in view/camera space.
  9226. *
  9227. * @tsl
  9228. * @type {ModelNode<vec3>}
  9229. */
  9230. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  9231. /**
  9232. * TSL object that represents the object's radius.
  9233. *
  9234. * @tsl
  9235. * @type {ModelNode<float>}
  9236. */
  9237. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  9238. /**
  9239. * TSL object that represents the object's normal matrix.
  9240. *
  9241. * @tsl
  9242. * @type {UniformNode<mat3>}
  9243. */
  9244. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  9245. /**
  9246. * TSL object that represents the object's inverse world matrix.
  9247. *
  9248. * @tsl
  9249. * @type {UniformNode<mat4>}
  9250. */
  9251. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  9252. /**
  9253. * TSL object that represents the object's model view matrix.
  9254. *
  9255. * @tsl
  9256. * @type {Node<mat4>}
  9257. */
  9258. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9259. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  9260. } ).once() )().toVar( 'modelViewMatrix' );
  9261. // GPU Precision
  9262. /**
  9263. * TSL object that represents the object's model view in `mediump` precision.
  9264. *
  9265. * @tsl
  9266. * @type {Node<mat4>}
  9267. */
  9268. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  9269. // CPU Precision
  9270. /**
  9271. * TSL object that represents the object's model view in `highp` precision
  9272. * which is achieved by computing the matrix in JS and not in the shader.
  9273. *
  9274. * @tsl
  9275. * @type {Node<mat4>}
  9276. */
  9277. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9278. builder.context.isHighPrecisionModelViewMatrix = true;
  9279. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  9280. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9281. } );
  9282. } ).once() )().toVar( 'highpModelViewMatrix' );
  9283. /**
  9284. * TSL object that represents the object's model normal view in `highp` precision
  9285. * which is achieved by computing the matrix in JS and not in the shader.
  9286. *
  9287. * @tsl
  9288. * @type {Node<mat3>}
  9289. */
  9290. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  9291. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  9292. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  9293. if ( isHighPrecisionModelViewMatrix !== true ) {
  9294. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  9295. }
  9296. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  9297. } );
  9298. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  9299. /**
  9300. * TSL object that represents the position attribute of the current rendered object.
  9301. *
  9302. * @tsl
  9303. * @type {AttributeNode<vec3>}
  9304. */
  9305. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  9306. /**
  9307. * TSL object that represents the vertex position in local space of the current rendered object.
  9308. *
  9309. * @tsl
  9310. * @type {AttributeNode<vec3>}
  9311. */
  9312. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  9313. /**
  9314. * TSL object that represents the previous vertex position in local space of the current rendered object.
  9315. * Used in context of {@link VelocityNode} for rendering motion vectors.
  9316. *
  9317. * @tsl
  9318. * @type {AttributeNode<vec3>}
  9319. */
  9320. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  9321. /**
  9322. * TSL object that represents the vertex position in world space of the current rendered object.
  9323. *
  9324. * @tsl
  9325. * @type {VaryingNode<vec3>}
  9326. */
  9327. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  9328. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getSubBuildProperty( 'v_positionWorld' ) );
  9329. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9330. /**
  9331. * TSL object that represents the position world direction of the current rendered object.
  9332. *
  9333. * @tsl
  9334. * @type {Node<vec3>}
  9335. */
  9336. const positionWorldDirection = /*@__PURE__*/ ( Fn( () => {
  9337. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( 'v_positionWorldDirection' );
  9338. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  9339. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9340. /**
  9341. * TSL object that represents the vertex position in view space of the current rendered object.
  9342. *
  9343. * @tsl
  9344. * @type {VaryingNode<vec3>}
  9345. */
  9346. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  9347. return builder.context.setupPositionView().toVarying( 'v_positionView' );
  9348. }, 'vec3' ).once( [ 'POSITION' ] ) )();
  9349. /**
  9350. * TSL object that represents the position view direction of the current rendered object.
  9351. *
  9352. * @tsl
  9353. * @type {VaryingNode<vec3>}
  9354. */
  9355. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  9356. /**
  9357. * This node can be used to evaluate whether a primitive is front or back facing.
  9358. *
  9359. * @augments Node
  9360. */
  9361. class FrontFacingNode extends Node {
  9362. static get type() {
  9363. return 'FrontFacingNode';
  9364. }
  9365. /**
  9366. * Constructs a new front facing node.
  9367. */
  9368. constructor() {
  9369. super( 'bool' );
  9370. /**
  9371. * This flag can be used for type testing.
  9372. *
  9373. * @type {boolean}
  9374. * @readonly
  9375. * @default true
  9376. */
  9377. this.isFrontFacingNode = true;
  9378. }
  9379. generate( builder ) {
  9380. if ( builder.shaderStage !== 'fragment' ) return 'true';
  9381. //
  9382. const { material } = builder;
  9383. if ( material.side === BackSide ) {
  9384. return 'false';
  9385. }
  9386. return builder.getFrontFacing();
  9387. }
  9388. }
  9389. /**
  9390. * TSL object that represents whether a primitive is front or back facing
  9391. *
  9392. * @tsl
  9393. * @type {FrontFacingNode<bool>}
  9394. */
  9395. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  9396. /**
  9397. * TSL object that represents the front facing status as a number instead of a bool.
  9398. * `1` means front facing, `-1` means back facing.
  9399. *
  9400. * @tsl
  9401. * @type {Node<float>}
  9402. */
  9403. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  9404. /**
  9405. * Converts a direction vector to a face direction vector based on the material's side.
  9406. *
  9407. * If the material is set to `BackSide`, the direction is inverted.
  9408. * If the material is set to `DoubleSide`, the direction is multiplied by `faceDirection`.
  9409. *
  9410. * @tsl
  9411. * @param {Node<vec3>} direction - The direction vector to convert.
  9412. * @returns {Node<vec3>} The converted direction vector.
  9413. */
  9414. const directionToFaceDirection = /*@__PURE__*/ Fn( ( [ direction ], { material } ) => {
  9415. const side = material.side;
  9416. if ( side === BackSide ) {
  9417. direction = direction.mul( -1 );
  9418. } else if ( side === DoubleSide ) {
  9419. direction = direction.mul( faceDirection );
  9420. }
  9421. return direction;
  9422. } );
  9423. /**
  9424. * TSL object that represents the normal attribute of the current rendered object in local space.
  9425. *
  9426. * @tsl
  9427. * @type {Node<vec3>}
  9428. */
  9429. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  9430. /**
  9431. * TSL object that represents the vertex normal of the current rendered object in local space.
  9432. *
  9433. * @tsl
  9434. * @type {Node<vec3>}
  9435. */
  9436. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  9437. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  9438. console.warn( 'THREE.TSL: Vertex attribute "normal" not found on geometry.' );
  9439. return vec3( 0, 1, 0 );
  9440. }
  9441. return normalGeometry;
  9442. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  9443. /**
  9444. * TSL object that represents the flat vertex normal of the current rendered object in view space.
  9445. *
  9446. * @tsl
  9447. * @type {Node<vec3>}
  9448. */
  9449. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  9450. /**
  9451. * TSL object that represents the vertex normal of the current rendered object in view space.
  9452. *
  9453. * @tsl
  9454. * @type {Node<vec3>}
  9455. */
  9456. const normalViewGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9457. let node;
  9458. if ( builder.material.flatShading === true ) {
  9459. node = normalFlat;
  9460. } else {
  9461. node = transformNormalToView( normalLocal ).toVarying( 'v_normalViewGeometry' ).normalize();
  9462. }
  9463. return node;
  9464. }, 'vec3' ).once() )().toVar( 'normalViewGeometry' );
  9465. /**
  9466. * TSL object that represents the vertex normal of the current rendered object in world space.
  9467. *
  9468. * @tsl
  9469. * @type {Node<vec3>}
  9470. */
  9471. const normalWorldGeometry = /*@__PURE__*/ ( Fn( ( builder ) => {
  9472. let normal = normalViewGeometry.transformDirection( cameraViewMatrix );
  9473. if ( builder.material.flatShading !== true ) {
  9474. normal = normal.toVarying( 'v_normalWorldGeometry' );
  9475. }
  9476. return normal.normalize().toVar( 'normalWorldGeometry' );
  9477. }, 'vec3' ).once() )();
  9478. /**
  9479. * TSL object that represents the vertex normal of the current rendered object in view space.
  9480. *
  9481. * @tsl
  9482. * @type {Node<vec3>}
  9483. */
  9484. const normalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, material, context } ) => {
  9485. let node;
  9486. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9487. node = normalViewGeometry;
  9488. if ( material.flatShading !== true ) {
  9489. node = directionToFaceDirection( node );
  9490. }
  9491. } else {
  9492. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9493. node = context.setupNormal().context( { getUV: null } );
  9494. }
  9495. return node;
  9496. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'normalView' );
  9497. /**
  9498. * TSL object that represents the vertex normal of the current rendered object in world space.
  9499. *
  9500. * @tsl
  9501. * @type {Node<vec3>}
  9502. */
  9503. const normalWorld = /*@__PURE__*/ normalView.transformDirection( cameraViewMatrix ).toVar( 'normalWorld' );
  9504. /**
  9505. * TSL object that represents the clearcoat vertex normal of the current rendered object in view space.
  9506. *
  9507. * @tsl
  9508. * @type {Node<vec3>}
  9509. */
  9510. const clearcoatNormalView = /*@__PURE__*/ ( Fn( ( { subBuildFn, context } ) => {
  9511. let node;
  9512. if ( subBuildFn === 'NORMAL' || subBuildFn === 'VERTEX' ) {
  9513. node = normalView;
  9514. } else {
  9515. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  9516. node = context.setupClearcoatNormal().context( { getUV: null } );
  9517. }
  9518. return node;
  9519. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'clearcoatNormalView' );
  9520. /**
  9521. * Transforms the normal with the given matrix.
  9522. *
  9523. * @tsl
  9524. * @function
  9525. * @param {Node<vec3>} normal - The normal.
  9526. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  9527. * @return {Node<vec3>} The transformed normal.
  9528. */
  9529. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  9530. const m = mat3( matrix );
  9531. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  9532. return m.mul( transformedNormal ).xyz;
  9533. } );
  9534. /**
  9535. * Transforms the given normal from local to view space.
  9536. *
  9537. * @tsl
  9538. * @function
  9539. * @param {Node<vec3>} normal - The normal.
  9540. * @param {NodeBuilder} builder - The current node builder.
  9541. * @return {Node<vec3>} The transformed normal.
  9542. */
  9543. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  9544. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  9545. if ( modelNormalViewMatrix !== null ) {
  9546. return modelNormalViewMatrix.transformDirection( normal );
  9547. }
  9548. //
  9549. const transformedNormal = modelNormalMatrix.mul( normal );
  9550. return cameraViewMatrix.transformDirection( transformedNormal );
  9551. } );
  9552. // Deprecated
  9553. /**
  9554. * TSL object that represents the transformed vertex normal of the current rendered object in view space.
  9555. *
  9556. * @tsl
  9557. * @type {Node<vec3>}
  9558. * @deprecated since r178. Use `normalView` instead.
  9559. */
  9560. const transformedNormalView = ( Fn( () => { // @deprecated, r177
  9561. console.warn( 'THREE.TSL: "transformedNormalView" is deprecated. Use "normalView" instead.' );
  9562. return normalView;
  9563. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9564. /**
  9565. * TSL object that represents the transformed vertex normal of the current rendered object in world space.
  9566. *
  9567. * @tsl
  9568. * @type {Node<vec3>}
  9569. * @deprecated since r178. Use `normalWorld` instead.
  9570. */
  9571. const transformedNormalWorld = ( Fn( () => { // @deprecated, r177
  9572. console.warn( 'THREE.TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.' );
  9573. return normalWorld;
  9574. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9575. /**
  9576. * TSL object that represents the transformed clearcoat vertex normal of the current rendered object in view space.
  9577. *
  9578. * @tsl
  9579. * @type {Node<vec3>}
  9580. * @deprecated since r178. Use `clearcoatNormalView` instead.
  9581. */
  9582. const transformedClearcoatNormalView = ( Fn( () => { // @deprecated, r177
  9583. console.warn( 'THREE.TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.' );
  9584. return clearcoatNormalView;
  9585. } ).once( [ 'NORMAL', 'VERTEX' ] ) )();
  9586. const _e1$1 = /*@__PURE__*/ new Euler();
  9587. const _m1$1 = /*@__PURE__*/ new Matrix4();
  9588. /**
  9589. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  9590. *
  9591. * @tsl
  9592. * @type {UniformNode<float>}
  9593. */
  9594. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  9595. /**
  9596. * TSL object that represents the intensity of environment maps of PBR materials.
  9597. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  9598. *
  9599. * @tsl
  9600. * @type {Node<float>}
  9601. */
  9602. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  9603. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  9604. } );
  9605. /**
  9606. * TSL object that represents the rotation of environment maps.
  9607. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  9608. * rotation of `scene.environment` instead.
  9609. *
  9610. * @tsl
  9611. * @type {Node<mat4>}
  9612. */
  9613. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  9614. return frame.material;
  9615. } ).onObjectUpdate( function ( { material, scene } ) {
  9616. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  9617. if ( rotation ) {
  9618. _e1$1.copy( rotation );
  9619. _m1$1.makeRotationFromEuler( _e1$1 );
  9620. } else {
  9621. _m1$1.identity();
  9622. }
  9623. return _m1$1;
  9624. } );
  9625. /**
  9626. * The reflect vector in view space.
  9627. *
  9628. * @tsl
  9629. * @type {Node<vec3>}
  9630. */
  9631. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( normalView );
  9632. /**
  9633. * The refract vector in view space.
  9634. *
  9635. * @tsl
  9636. * @type {Node<vec3>}
  9637. */
  9638. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( normalView, materialRefractionRatio );
  9639. /**
  9640. * Used for sampling cube maps when using cube reflection mapping.
  9641. *
  9642. * @tsl
  9643. * @type {Node<vec3>}
  9644. */
  9645. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9646. /**
  9647. * Used for sampling cube maps when using cube refraction mapping.
  9648. *
  9649. * @tsl
  9650. * @type {Node<vec3>}
  9651. */
  9652. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  9653. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  9654. /**
  9655. * This type of uniform node represents a cube texture.
  9656. *
  9657. * @augments TextureNode
  9658. */
  9659. class CubeTextureNode extends TextureNode {
  9660. static get type() {
  9661. return 'CubeTextureNode';
  9662. }
  9663. /**
  9664. * Constructs a new cube texture node.
  9665. *
  9666. * @param {CubeTexture} value - The cube texture.
  9667. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9668. * @param {?Node<int>} [levelNode=null] - The level node.
  9669. * @param {?Node<float>} [biasNode=null] - The bias node.
  9670. */
  9671. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  9672. super( value, uvNode, levelNode, biasNode );
  9673. /**
  9674. * This flag can be used for type testing.
  9675. *
  9676. * @type {boolean}
  9677. * @readonly
  9678. * @default true
  9679. */
  9680. this.isCubeTextureNode = true;
  9681. }
  9682. /**
  9683. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  9684. *
  9685. * @param {NodeBuilder} builder - The current node builder.
  9686. * @return {string} The input type.
  9687. */
  9688. getInputType( /*builder*/ ) {
  9689. return 'cubeTexture';
  9690. }
  9691. /**
  9692. * Returns a default uvs based on the mapping type of the cube texture.
  9693. *
  9694. * @return {Node<vec3>} The default uv attribute.
  9695. */
  9696. getDefaultUV() {
  9697. const texture = this.value;
  9698. if ( texture.mapping === CubeReflectionMapping ) {
  9699. return reflectVector;
  9700. } else if ( texture.mapping === CubeRefractionMapping ) {
  9701. return refractVector;
  9702. } else {
  9703. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  9704. return vec3( 0, 0, 0 );
  9705. }
  9706. }
  9707. /**
  9708. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  9709. * for cube textures. The uv transformation matrix is not applied to cube textures.
  9710. *
  9711. * @param {boolean} value - The update toggle.
  9712. */
  9713. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  9714. /**
  9715. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  9716. * to modify the uv node for correct sampling.
  9717. *
  9718. * @param {NodeBuilder} builder - The current node builder.
  9719. * @param {Node} uvNode - The uv node to setup.
  9720. * @return {Node} The updated uv node.
  9721. */
  9722. setupUV( builder, uvNode ) {
  9723. const texture = this.value;
  9724. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  9725. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  9726. }
  9727. return materialEnvRotation.mul( uvNode );
  9728. }
  9729. /**
  9730. * Generates the uv code snippet.
  9731. *
  9732. * @param {NodeBuilder} builder - The current node builder.
  9733. * @param {Node} cubeUV - The uv node to generate code for.
  9734. * @return {string} The generated code snippet.
  9735. */
  9736. generateUV( builder, cubeUV ) {
  9737. return cubeUV.build( builder, 'vec3' );
  9738. }
  9739. }
  9740. /**
  9741. * TSL function for creating a cube texture node.
  9742. *
  9743. * @tsl
  9744. * @function
  9745. * @param {CubeTexture} value - The cube texture.
  9746. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9747. * @param {?Node<int>} [levelNode=null] - The level node.
  9748. * @param {?Node<float>} [biasNode=null] - The bias node.
  9749. * @returns {CubeTextureNode}
  9750. */
  9751. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  9752. /**
  9753. * TSL function for creating a cube texture uniform node.
  9754. *
  9755. * @tsl
  9756. * @function
  9757. * @param {?(CubeTexture|CubeTextureNode)} [value=EmptyTexture] - The cube texture.
  9758. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  9759. * @param {?Node<int>} [levelNode=null] - The level node.
  9760. * @param {?Node<float>} [biasNode=null] - The bias node.
  9761. * @returns {CubeTextureNode}
  9762. */
  9763. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  9764. let textureNode;
  9765. if ( value && value.isCubeTextureNode === true ) {
  9766. textureNode = nodeObject( value.clone() );
  9767. textureNode.referenceNode = value; // Ensure the reference is set to the original node
  9768. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  9769. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  9770. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  9771. } else {
  9772. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  9773. }
  9774. return textureNode;
  9775. };
  9776. /**
  9777. * TSL function for creating a uniform cube texture node.
  9778. *
  9779. * @tsl
  9780. * @function
  9781. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  9782. * @returns {CubeTextureNode}
  9783. */
  9784. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  9785. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  9786. /**
  9787. * This class is only relevant if the referenced property is array-like.
  9788. * In this case, `ReferenceElementNode` allows to refer to a specific
  9789. * element inside the data structure via an index.
  9790. *
  9791. * @augments ArrayElementNode
  9792. */
  9793. class ReferenceElementNode extends ArrayElementNode {
  9794. static get type() {
  9795. return 'ReferenceElementNode';
  9796. }
  9797. /**
  9798. * Constructs a new reference element node.
  9799. *
  9800. * @param {?ReferenceNode} referenceNode - The reference node.
  9801. * @param {Node} indexNode - The index node that defines the element access.
  9802. */
  9803. constructor( referenceNode, indexNode ) {
  9804. super( referenceNode, indexNode );
  9805. /**
  9806. * Similar to {@link ReferenceNode#reference}, an additional
  9807. * property references to the current node.
  9808. *
  9809. * @type {?ReferenceNode}
  9810. * @default null
  9811. */
  9812. this.referenceNode = referenceNode;
  9813. /**
  9814. * This flag can be used for type testing.
  9815. *
  9816. * @type {boolean}
  9817. * @readonly
  9818. * @default true
  9819. */
  9820. this.isReferenceElementNode = true;
  9821. }
  9822. /**
  9823. * This method is overwritten since the node type is inferred from
  9824. * the uniform type of the reference node.
  9825. *
  9826. * @return {string} The node type.
  9827. */
  9828. getNodeType() {
  9829. return this.referenceNode.uniformType;
  9830. }
  9831. generate( builder ) {
  9832. const snippet = super.generate( builder );
  9833. const arrayType = this.referenceNode.getNodeType();
  9834. const elementType = this.getNodeType();
  9835. return builder.format( snippet, arrayType, elementType );
  9836. }
  9837. }
  9838. /**
  9839. * This type of node establishes a reference to a property of another object.
  9840. * In this way, the value of the node is automatically linked to the value of
  9841. * referenced object. Reference nodes internally represent the linked value
  9842. * as a uniform.
  9843. *
  9844. * @augments Node
  9845. */
  9846. class ReferenceNode extends Node {
  9847. static get type() {
  9848. return 'ReferenceNode';
  9849. }
  9850. /**
  9851. * Constructs a new reference node.
  9852. *
  9853. * @param {string} property - The name of the property the node refers to.
  9854. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  9855. * @param {?Object} [object=null] - The object the property belongs to.
  9856. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  9857. */
  9858. constructor( property, uniformType, object = null, count = null ) {
  9859. super();
  9860. /**
  9861. * The name of the property the node refers to.
  9862. *
  9863. * @type {string}
  9864. */
  9865. this.property = property;
  9866. /**
  9867. * The uniform type that should be used to represent the property value.
  9868. *
  9869. * @type {string}
  9870. */
  9871. this.uniformType = uniformType;
  9872. /**
  9873. * The object the property belongs to.
  9874. *
  9875. * @type {?Object}
  9876. * @default null
  9877. */
  9878. this.object = object;
  9879. /**
  9880. * When the linked property is an array, this parameter defines its length.
  9881. *
  9882. * @type {?number}
  9883. * @default null
  9884. */
  9885. this.count = count;
  9886. /**
  9887. * The property name might have dots so nested properties can be referred.
  9888. * The hierarchy of the names is stored inside this array.
  9889. *
  9890. * @type {Array<string>}
  9891. */
  9892. this.properties = property.split( '.' );
  9893. /**
  9894. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  9895. * since the final reference might be updated from calling code.
  9896. *
  9897. * @type {?Object}
  9898. * @default null
  9899. */
  9900. this.reference = object;
  9901. /**
  9902. * The uniform node that holds the value of the reference node.
  9903. *
  9904. * @type {UniformNode}
  9905. * @default null
  9906. */
  9907. this.node = null;
  9908. /**
  9909. * The uniform group of the internal uniform.
  9910. *
  9911. * @type {UniformGroupNode}
  9912. * @default null
  9913. */
  9914. this.group = null;
  9915. /**
  9916. * An optional label of the internal uniform node.
  9917. *
  9918. * @type {?string}
  9919. * @default null
  9920. */
  9921. this.name = null;
  9922. /**
  9923. * Overwritten since reference nodes are updated per object.
  9924. *
  9925. * @type {string}
  9926. * @default 'object'
  9927. */
  9928. this.updateType = NodeUpdateType.OBJECT;
  9929. }
  9930. /**
  9931. * When the referred property is array-like, this method can be used
  9932. * to access elements via an index node.
  9933. *
  9934. * @param {IndexNode} indexNode - indexNode.
  9935. * @return {ReferenceElementNode} A reference to an element.
  9936. */
  9937. element( indexNode ) {
  9938. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  9939. }
  9940. /**
  9941. * Sets the uniform group for this reference node.
  9942. *
  9943. * @param {UniformGroupNode} group - The uniform group to set.
  9944. * @return {ReferenceNode} A reference to this node.
  9945. */
  9946. setGroup( group ) {
  9947. this.group = group;
  9948. return this;
  9949. }
  9950. /**
  9951. * Sets the name for the internal uniform.
  9952. *
  9953. * @param {string} name - The label to set.
  9954. * @return {ReferenceNode} A reference to this node.
  9955. */
  9956. setName( name ) {
  9957. this.name = name;
  9958. return this;
  9959. }
  9960. /**
  9961. * Sets the label for the internal uniform.
  9962. *
  9963. * @deprecated
  9964. * @param {string} name - The label to set.
  9965. * @return {ReferenceNode} A reference to this node.
  9966. */
  9967. label( name ) {
  9968. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  9969. return this.setName( name );
  9970. }
  9971. /**
  9972. * Sets the node type which automatically defines the internal
  9973. * uniform type.
  9974. *
  9975. * @param {string} uniformType - The type to set.
  9976. */
  9977. setNodeType( uniformType ) {
  9978. let node = null;
  9979. if ( this.count !== null ) {
  9980. node = buffer( null, uniformType, this.count );
  9981. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  9982. node = uniformArray( null, uniformType );
  9983. } else if ( uniformType === 'texture' ) {
  9984. node = texture( null );
  9985. } else if ( uniformType === 'cubeTexture' ) {
  9986. node = cubeTexture( null );
  9987. } else {
  9988. node = uniform( null, uniformType );
  9989. }
  9990. if ( this.group !== null ) {
  9991. node.setGroup( this.group );
  9992. }
  9993. if ( this.name !== null ) node.setName( this.name );
  9994. this.node = node;
  9995. }
  9996. /**
  9997. * This method is overwritten since the node type is inferred from
  9998. * the type of the reference node.
  9999. *
  10000. * @param {NodeBuilder} builder - The current node builder.
  10001. * @return {string} The node type.
  10002. */
  10003. getNodeType( builder ) {
  10004. if ( this.node === null ) {
  10005. this.updateReference( builder );
  10006. this.updateValue();
  10007. }
  10008. return this.node.getNodeType( builder );
  10009. }
  10010. /**
  10011. * Returns the property value from the given referred object.
  10012. *
  10013. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  10014. * @return {any} The value.
  10015. */
  10016. getValueFromReference( object = this.reference ) {
  10017. const { properties } = this;
  10018. let value = object[ properties[ 0 ] ];
  10019. for ( let i = 1; i < properties.length; i ++ ) {
  10020. value = value[ properties[ i ] ];
  10021. }
  10022. return value;
  10023. }
  10024. /**
  10025. * Allows to update the reference based on the given state. The state is only
  10026. * evaluated {@link ReferenceNode#object} is not set.
  10027. *
  10028. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10029. * @return {Object} The updated reference.
  10030. */
  10031. updateReference( state ) {
  10032. this.reference = this.object !== null ? this.object : state.object;
  10033. return this.reference;
  10034. }
  10035. /**
  10036. * The output of the reference node is the internal uniform node.
  10037. *
  10038. * @param {NodeBuilder} builder - The current node builder.
  10039. * @return {UniformNode} The output node.
  10040. */
  10041. setup( /* builder */ ) {
  10042. this.updateValue();
  10043. return this.node;
  10044. }
  10045. /**
  10046. * Overwritten to update the internal uniform value.
  10047. *
  10048. * @param {NodeFrame} frame - A reference to the current node frame.
  10049. */
  10050. update( /*frame*/ ) {
  10051. this.updateValue();
  10052. }
  10053. /**
  10054. * Retrieves the value from the referred object property and uses it
  10055. * to updated the internal uniform.
  10056. */
  10057. updateValue() {
  10058. if ( this.node === null ) this.setNodeType( this.uniformType );
  10059. const value = this.getValueFromReference();
  10060. if ( Array.isArray( value ) ) {
  10061. this.node.array = value;
  10062. } else {
  10063. this.node.value = value;
  10064. }
  10065. }
  10066. }
  10067. /**
  10068. * TSL function for creating a reference node.
  10069. *
  10070. * @tsl
  10071. * @function
  10072. * @param {string} name - The name of the property the node refers to.
  10073. * @param {string} type - The uniform type that should be used to represent the property value.
  10074. * @param {?Object} [object] - The object the property belongs to.
  10075. * @returns {ReferenceNode}
  10076. */
  10077. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  10078. /**
  10079. * TSL function for creating a reference node. Use this function if you want need a reference
  10080. * to an array-like property that should be represented as a uniform buffer.
  10081. *
  10082. * @tsl
  10083. * @function
  10084. * @param {string} name - The name of the property the node refers to.
  10085. * @param {string} type - The uniform type that should be used to represent the property value.
  10086. * @param {number} count - The number of value inside the array-like object.
  10087. * @param {Object} object - An array-like object the property belongs to.
  10088. * @returns {ReferenceNode}
  10089. */
  10090. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  10091. /**
  10092. * This node is a special type of reference node which is intended
  10093. * for linking material properties with node values.
  10094. * ```js
  10095. * const opacityNode = materialReference( 'opacity', 'float', material );
  10096. * ```
  10097. * When changing `material.opacity`, the node value of `opacityNode` will
  10098. * automatically be updated.
  10099. *
  10100. * @augments ReferenceNode
  10101. */
  10102. class MaterialReferenceNode extends ReferenceNode {
  10103. static get type() {
  10104. return 'MaterialReferenceNode';
  10105. }
  10106. /**
  10107. * Constructs a new material reference node.
  10108. *
  10109. * @param {string} property - The name of the property the node refers to.
  10110. * @param {string} inputType - The uniform type that should be used to represent the property value.
  10111. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  10112. * the node refers to the material of the current rendered object.
  10113. */
  10114. constructor( property, inputType, material = null ) {
  10115. super( property, inputType, material );
  10116. /**
  10117. * The material the property belongs to. When no material is set,
  10118. * the node refers to the material of the current rendered object.
  10119. *
  10120. * @type {?Material}
  10121. * @default null
  10122. */
  10123. this.material = material;
  10124. /**
  10125. * This flag can be used for type testing.
  10126. *
  10127. * @type {boolean}
  10128. * @readonly
  10129. * @default true
  10130. */
  10131. this.isMaterialReferenceNode = true;
  10132. }
  10133. /**
  10134. * Updates the reference based on the given state. The state is only evaluated
  10135. * {@link MaterialReferenceNode#material} is not set.
  10136. *
  10137. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  10138. * @return {Object} The updated reference.
  10139. */
  10140. updateReference( state ) {
  10141. this.reference = this.material !== null ? this.material : state.material;
  10142. return this.reference;
  10143. }
  10144. }
  10145. /**
  10146. * TSL function for creating a material reference node.
  10147. *
  10148. * @tsl
  10149. * @function
  10150. * @param {string} name - The name of the property the node refers to.
  10151. * @param {string} type - The uniform type that should be used to represent the property value.
  10152. * @param {?Material} [material=null] - The material the property belongs to.
  10153. * When no material is set, the node refers to the material of the current rendered object.
  10154. * @returns {MaterialReferenceNode}
  10155. */
  10156. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  10157. // Normal Mapping Without Precomputed Tangents
  10158. // http://www.thetenthplanet.de/archives/1180
  10159. const uv = uv$1();
  10160. const q0 = positionView.dFdx();
  10161. const q1 = positionView.dFdy();
  10162. const st0 = uv.dFdx();
  10163. const st1 = uv.dFdy();
  10164. const N = normalView;
  10165. const q1perp = q1.cross( N );
  10166. const q0perp = N.cross( q0 );
  10167. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  10168. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  10169. const det = T.dot( T ).max( B.dot( B ) );
  10170. const scale$1 = det.equal( 0.0 ).select( 0.0, det.inverseSqrt() );
  10171. /**
  10172. * Tangent vector in view space, computed dynamically from geometry and UV derivatives.
  10173. * Useful for normal mapping without precomputed tangents.
  10174. *
  10175. * Reference: http://www.thetenthplanet.de/archives/1180
  10176. *
  10177. * @tsl
  10178. * @type {Node<vec3>}
  10179. */
  10180. const tangentViewFrame = /*@__PURE__*/ T.mul( scale$1 ).toVar( 'tangentViewFrame' );
  10181. /**
  10182. * Bitangent vector in view space, computed dynamically from geometry and UV derivatives.
  10183. * Complements the tangentViewFrame for constructing the tangent space basis.
  10184. *
  10185. * Reference: http://www.thetenthplanet.de/archives/1180
  10186. *
  10187. * @tsl
  10188. * @type {Node<vec3>}
  10189. */
  10190. const bitangentViewFrame = /*@__PURE__*/ B.mul( scale$1 ).toVar( 'bitangentViewFrame' );
  10191. /**
  10192. * TSL object that represents the tangent attribute of the current rendered object.
  10193. *
  10194. * @tsl
  10195. * @type {Node<vec4>}
  10196. */
  10197. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  10198. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  10199. builder.geometry.computeTangents();
  10200. }
  10201. return attribute( 'tangent', 'vec4' );
  10202. } )();
  10203. /**
  10204. * TSL object that represents the vertex tangent in local space of the current rendered object.
  10205. *
  10206. * @tsl
  10207. * @type {Node<vec3>}
  10208. */
  10209. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  10210. /**
  10211. * TSL object that represents the vertex tangent in view space of the current rendered object.
  10212. *
  10213. * @tsl
  10214. * @type {Node<vec3>}
  10215. */
  10216. const tangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10217. let node;
  10218. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10219. node = modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize();
  10220. } else {
  10221. node = tangentViewFrame;
  10222. }
  10223. if ( material.flatShading !== true ) {
  10224. node = directionToFaceDirection( node );
  10225. }
  10226. return node;
  10227. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'tangentView' );
  10228. /**
  10229. * TSL object that represents the vertex tangent in world space of the current rendered object.
  10230. *
  10231. * @tsl
  10232. * @type {Node<vec3>}
  10233. */
  10234. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  10235. /**
  10236. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  10237. *
  10238. * @tsl
  10239. * @private
  10240. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  10241. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  10242. * @returns {Node<vec3>} The bitangent node.
  10243. */
  10244. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], { subBuildFn, material } ) => {
  10245. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  10246. if ( subBuildFn === 'NORMAL' && material.flatShading !== true ) {
  10247. bitangent = bitangent.toVarying( varyingName );
  10248. }
  10249. return bitangent;
  10250. } ).once( [ 'NORMAL' ] );
  10251. /**
  10252. * TSL object that represents the bitangent attribute of the current rendered object.
  10253. *
  10254. * @tsl
  10255. * @type {Node<vec3>}
  10256. */
  10257. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  10258. /**
  10259. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  10260. *
  10261. * @tsl
  10262. * @type {Node<vec3>}
  10263. */
  10264. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  10265. /**
  10266. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  10267. *
  10268. * @tsl
  10269. * @type {Node<vec3>}
  10270. */
  10271. const bitangentView = /*@__PURE__*/ ( Fn( ( { subBuildFn, geometry, material } ) => {
  10272. let node;
  10273. if ( subBuildFn === 'VERTEX' || geometry.hasAttribute( 'tangent' ) ) {
  10274. node = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize();
  10275. } else {
  10276. node = bitangentViewFrame;
  10277. }
  10278. if ( material.flatShading !== true ) {
  10279. node = directionToFaceDirection( node );
  10280. }
  10281. return node;
  10282. }, 'vec3' ).once( [ 'NORMAL', 'VERTEX' ] ) )().toVar( 'bitangentView' );
  10283. /**
  10284. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  10285. *
  10286. * @tsl
  10287. * @type {Node<vec3>}
  10288. */
  10289. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  10290. /**
  10291. * TSL object that represents the TBN matrix in view space.
  10292. *
  10293. * @tsl
  10294. * @type {Node<mat3>}
  10295. */
  10296. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView ).toVar( 'TBNViewMatrix' );
  10297. /**
  10298. * TSL object that represents the parallax direction.
  10299. *
  10300. * @tsl
  10301. * @type {Node<mat3>}
  10302. */
  10303. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  10304. /**
  10305. * TSL function for computing parallax uv coordinates.
  10306. *
  10307. * @tsl
  10308. * @function
  10309. * @param {Node<vec2>} uv - A uv node.
  10310. * @param {Node<vec2>} scale - A scale node.
  10311. * @returns {Node<vec2>} Parallax uv coordinates.
  10312. */
  10313. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  10314. /**
  10315. * TSL function for computing bent normals.
  10316. *
  10317. * @tsl
  10318. * @function
  10319. * @returns {Node<vec3>} Bent normals.
  10320. */
  10321. const bentNormalView = /*@__PURE__*/ ( Fn( () => {
  10322. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  10323. let bentNormal = anisotropyB.cross( positionViewDirection );
  10324. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  10325. bentNormal = mix( bentNormal, normalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  10326. return bentNormal;
  10327. } ).once() )();
  10328. /**
  10329. * This class can be used for applying normals maps to materials.
  10330. *
  10331. * ```js
  10332. * material.normalNode = normalMap( texture( normalTex ) );
  10333. * ```
  10334. *
  10335. * @augments TempNode
  10336. */
  10337. class NormalMapNode extends TempNode {
  10338. static get type() {
  10339. return 'NormalMapNode';
  10340. }
  10341. /**
  10342. * Constructs a new normal map node.
  10343. *
  10344. * @param {Node<vec3>} node - Represents the normal map data.
  10345. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10346. */
  10347. constructor( node, scaleNode = null ) {
  10348. super( 'vec3' );
  10349. /**
  10350. * Represents the normal map data.
  10351. *
  10352. * @type {Node<vec3>}
  10353. */
  10354. this.node = node;
  10355. /**
  10356. * Controls the intensity of the effect.
  10357. *
  10358. * @type {?Node<vec2>}
  10359. * @default null
  10360. */
  10361. this.scaleNode = scaleNode;
  10362. /**
  10363. * The normal map type.
  10364. *
  10365. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  10366. * @default TangentSpaceNormalMap
  10367. */
  10368. this.normalMapType = TangentSpaceNormalMap;
  10369. }
  10370. setup( { material } ) {
  10371. const { normalMapType, scaleNode } = this;
  10372. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  10373. if ( scaleNode !== null ) {
  10374. let scale = scaleNode;
  10375. if ( material.flatShading === true ) {
  10376. scale = directionToFaceDirection( scale );
  10377. }
  10378. normalMap = vec3( normalMap.xy.mul( scale ), normalMap.z );
  10379. }
  10380. let output = null;
  10381. if ( normalMapType === ObjectSpaceNormalMap ) {
  10382. output = transformNormalToView( normalMap );
  10383. } else if ( normalMapType === TangentSpaceNormalMap ) {
  10384. output = TBNViewMatrix.mul( normalMap ).normalize();
  10385. } else {
  10386. console.error( `THREE.NodeMaterial: Unsupported normal map type: ${ normalMapType }` );
  10387. output = normalView; // Fallback to default normal view
  10388. }
  10389. return output;
  10390. }
  10391. }
  10392. /**
  10393. * TSL function for creating a normal map node.
  10394. *
  10395. * @tsl
  10396. * @function
  10397. * @param {Node<vec3>} node - Represents the normal map data.
  10398. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  10399. * @returns {NormalMapNode}
  10400. */
  10401. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  10402. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  10403. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  10404. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  10405. // It's used to preserve the same TextureNode instance
  10406. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv$1() ), forceUVContext: true } );
  10407. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  10408. return vec2(
  10409. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  10410. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  10411. ).mul( bumpScale );
  10412. } );
  10413. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10414. const perturbNormalArb = Fn( ( inputs ) => {
  10415. const { surf_pos, surf_norm, dHdxy } = inputs;
  10416. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  10417. const vSigmaX = surf_pos.dFdx().normalize();
  10418. const vSigmaY = surf_pos.dFdy().normalize();
  10419. const vN = surf_norm; // normalized
  10420. const R1 = vSigmaY.cross( vN );
  10421. const R2 = vN.cross( vSigmaX );
  10422. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  10423. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  10424. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  10425. } );
  10426. /**
  10427. * This class can be used for applying bump maps to materials.
  10428. *
  10429. * ```js
  10430. * material.normalNode = bumpMap( texture( bumpTex ) );
  10431. * ```
  10432. *
  10433. * @augments TempNode
  10434. */
  10435. class BumpMapNode extends TempNode {
  10436. static get type() {
  10437. return 'BumpMapNode';
  10438. }
  10439. /**
  10440. * Constructs a new bump map node.
  10441. *
  10442. * @param {Node<float>} textureNode - Represents the bump map data.
  10443. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10444. */
  10445. constructor( textureNode, scaleNode = null ) {
  10446. super( 'vec3' );
  10447. /**
  10448. * Represents the bump map data.
  10449. *
  10450. * @type {Node<float>}
  10451. */
  10452. this.textureNode = textureNode;
  10453. /**
  10454. * Controls the intensity of the bump effect.
  10455. *
  10456. * @type {?Node<float>}
  10457. * @default null
  10458. */
  10459. this.scaleNode = scaleNode;
  10460. }
  10461. setup() {
  10462. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  10463. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  10464. return perturbNormalArb( {
  10465. surf_pos: positionView,
  10466. surf_norm: normalView,
  10467. dHdxy
  10468. } );
  10469. }
  10470. }
  10471. /**
  10472. * TSL function for creating a bump map node.
  10473. *
  10474. * @tsl
  10475. * @function
  10476. * @param {Node<float>} textureNode - Represents the bump map data.
  10477. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  10478. * @returns {BumpMapNode}
  10479. */
  10480. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  10481. const _propertyCache = new Map();
  10482. /**
  10483. * This class should simplify the node access to material properties.
  10484. * It internal uses reference nodes to make sure changes to material
  10485. * properties are automatically reflected to predefined TSL objects
  10486. * like e.g. `materialColor`.
  10487. *
  10488. * @augments Node
  10489. */
  10490. class MaterialNode extends Node {
  10491. static get type() {
  10492. return 'MaterialNode';
  10493. }
  10494. /**
  10495. * Constructs a new material node.
  10496. *
  10497. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  10498. */
  10499. constructor( scope ) {
  10500. super();
  10501. /**
  10502. * The scope defines what material property is referred by the node.
  10503. *
  10504. * @type {string}
  10505. */
  10506. this.scope = scope;
  10507. }
  10508. /**
  10509. * Returns a cached reference node for the given property and type.
  10510. *
  10511. * @param {string} property - The name of the material property.
  10512. * @param {string} type - The uniform type of the property.
  10513. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10514. */
  10515. getCache( property, type ) {
  10516. let node = _propertyCache.get( property );
  10517. if ( node === undefined ) {
  10518. node = materialReference( property, type );
  10519. _propertyCache.set( property, node );
  10520. }
  10521. return node;
  10522. }
  10523. /**
  10524. * Returns a float-typed material reference node for the given property name.
  10525. *
  10526. * @param {string} property - The name of the material property.
  10527. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  10528. */
  10529. getFloat( property ) {
  10530. return this.getCache( property, 'float' );
  10531. }
  10532. /**
  10533. * Returns a color-typed material reference node for the given property name.
  10534. *
  10535. * @param {string} property - The name of the material property.
  10536. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  10537. */
  10538. getColor( property ) {
  10539. return this.getCache( property, 'color' );
  10540. }
  10541. /**
  10542. * Returns a texture-typed material reference node for the given property name.
  10543. *
  10544. * @param {string} property - The name of the material property.
  10545. * @return {MaterialReferenceNode} A material reference node representing the property access.
  10546. */
  10547. getTexture( property ) {
  10548. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  10549. }
  10550. /**
  10551. * The node setup is done depending on the selected scope. Multiple material properties
  10552. * might be grouped into a single node composition if they logically belong together.
  10553. *
  10554. * @param {NodeBuilder} builder - The current node builder.
  10555. * @return {Node} The node representing the selected scope.
  10556. */
  10557. setup( builder ) {
  10558. const material = builder.context.material;
  10559. const scope = this.scope;
  10560. let node = null;
  10561. if ( scope === MaterialNode.COLOR ) {
  10562. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  10563. if ( material.map && material.map.isTexture === true ) {
  10564. node = colorNode.mul( this.getTexture( 'map' ) );
  10565. } else {
  10566. node = colorNode;
  10567. }
  10568. } else if ( scope === MaterialNode.OPACITY ) {
  10569. const opacityNode = this.getFloat( scope );
  10570. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  10571. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  10572. } else {
  10573. node = opacityNode;
  10574. }
  10575. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  10576. if ( material.specularMap && material.specularMap.isTexture === true ) {
  10577. node = this.getTexture( 'specular' ).r;
  10578. } else {
  10579. node = float( 1 );
  10580. }
  10581. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  10582. const specularIntensityNode = this.getFloat( scope );
  10583. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  10584. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  10585. } else {
  10586. node = specularIntensityNode;
  10587. }
  10588. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  10589. const specularColorNode = this.getColor( scope );
  10590. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  10591. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  10592. } else {
  10593. node = specularColorNode;
  10594. }
  10595. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  10596. const roughnessNode = this.getFloat( scope );
  10597. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  10598. node = roughnessNode.mul( this.getTexture( scope ).g );
  10599. } else {
  10600. node = roughnessNode;
  10601. }
  10602. } else if ( scope === MaterialNode.METALNESS ) {
  10603. const metalnessNode = this.getFloat( scope );
  10604. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  10605. node = metalnessNode.mul( this.getTexture( scope ).b );
  10606. } else {
  10607. node = metalnessNode;
  10608. }
  10609. } else if ( scope === MaterialNode.EMISSIVE ) {
  10610. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  10611. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  10612. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  10613. node = emissiveNode.mul( this.getTexture( scope ) );
  10614. } else {
  10615. node = emissiveNode;
  10616. }
  10617. } else if ( scope === MaterialNode.NORMAL ) {
  10618. if ( material.normalMap ) {
  10619. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  10620. node.normalMapType = material.normalMapType;
  10621. } else if ( material.bumpMap ) {
  10622. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  10623. } else {
  10624. node = normalView;
  10625. }
  10626. } else if ( scope === MaterialNode.CLEARCOAT ) {
  10627. const clearcoatNode = this.getFloat( scope );
  10628. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  10629. node = clearcoatNode.mul( this.getTexture( scope ).r );
  10630. } else {
  10631. node = clearcoatNode;
  10632. }
  10633. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  10634. const clearcoatRoughnessNode = this.getFloat( scope );
  10635. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  10636. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  10637. } else {
  10638. node = clearcoatRoughnessNode;
  10639. }
  10640. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  10641. if ( material.clearcoatNormalMap ) {
  10642. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  10643. } else {
  10644. node = normalView;
  10645. }
  10646. } else if ( scope === MaterialNode.SHEEN ) {
  10647. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  10648. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  10649. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  10650. } else {
  10651. node = sheenNode;
  10652. }
  10653. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  10654. const sheenRoughnessNode = this.getFloat( scope );
  10655. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  10656. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  10657. } else {
  10658. node = sheenRoughnessNode;
  10659. }
  10660. node = node.clamp( 0.07, 1.0 );
  10661. } else if ( scope === MaterialNode.ANISOTROPY ) {
  10662. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  10663. const anisotropyPolar = this.getTexture( scope );
  10664. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  10665. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  10666. } else {
  10667. node = materialAnisotropyVector;
  10668. }
  10669. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  10670. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  10671. if ( material.iridescenceThicknessMap ) {
  10672. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  10673. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  10674. } else {
  10675. node = iridescenceThicknessMaximum;
  10676. }
  10677. } else if ( scope === MaterialNode.TRANSMISSION ) {
  10678. const transmissionNode = this.getFloat( scope );
  10679. if ( material.transmissionMap ) {
  10680. node = transmissionNode.mul( this.getTexture( scope ).r );
  10681. } else {
  10682. node = transmissionNode;
  10683. }
  10684. } else if ( scope === MaterialNode.THICKNESS ) {
  10685. const thicknessNode = this.getFloat( scope );
  10686. if ( material.thicknessMap ) {
  10687. node = thicknessNode.mul( this.getTexture( scope ).g );
  10688. } else {
  10689. node = thicknessNode;
  10690. }
  10691. } else if ( scope === MaterialNode.IOR ) {
  10692. node = this.getFloat( scope );
  10693. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  10694. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  10695. } else if ( scope === MaterialNode.AO ) {
  10696. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  10697. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  10698. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  10699. } else {
  10700. const outputType = this.getNodeType( builder );
  10701. node = this.getCache( scope, outputType );
  10702. }
  10703. return node;
  10704. }
  10705. }
  10706. MaterialNode.ALPHA_TEST = 'alphaTest';
  10707. MaterialNode.COLOR = 'color';
  10708. MaterialNode.OPACITY = 'opacity';
  10709. MaterialNode.SHININESS = 'shininess';
  10710. MaterialNode.SPECULAR = 'specular';
  10711. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  10712. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  10713. MaterialNode.SPECULAR_COLOR = 'specularColor';
  10714. MaterialNode.REFLECTIVITY = 'reflectivity';
  10715. MaterialNode.ROUGHNESS = 'roughness';
  10716. MaterialNode.METALNESS = 'metalness';
  10717. MaterialNode.NORMAL = 'normal';
  10718. MaterialNode.CLEARCOAT = 'clearcoat';
  10719. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  10720. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  10721. MaterialNode.EMISSIVE = 'emissive';
  10722. MaterialNode.ROTATION = 'rotation';
  10723. MaterialNode.SHEEN = 'sheen';
  10724. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  10725. MaterialNode.ANISOTROPY = 'anisotropy';
  10726. MaterialNode.IRIDESCENCE = 'iridescence';
  10727. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  10728. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  10729. MaterialNode.IOR = 'ior';
  10730. MaterialNode.TRANSMISSION = 'transmission';
  10731. MaterialNode.THICKNESS = 'thickness';
  10732. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  10733. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  10734. MaterialNode.LINE_SCALE = 'scale';
  10735. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  10736. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  10737. MaterialNode.LINE_WIDTH = 'linewidth';
  10738. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  10739. MaterialNode.POINT_SIZE = 'size';
  10740. MaterialNode.DISPERSION = 'dispersion';
  10741. MaterialNode.LIGHT_MAP = 'light';
  10742. MaterialNode.AO = 'ao';
  10743. /**
  10744. * TSL object that represents alpha test of the current material.
  10745. *
  10746. * @tsl
  10747. * @type {Node<float>}
  10748. */
  10749. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  10750. /**
  10751. * TSL object that represents the diffuse color of the current material.
  10752. * The value is composed via `color` * `map`.
  10753. *
  10754. * @tsl
  10755. * @type {Node<vec3>}
  10756. */
  10757. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  10758. /**
  10759. * TSL object that represents the shininess of the current material.
  10760. *
  10761. * @tsl
  10762. * @type {Node<float>}
  10763. */
  10764. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  10765. /**
  10766. * TSL object that represents the emissive color of the current material.
  10767. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  10768. *
  10769. * @tsl
  10770. * @type {Node<vec3>}
  10771. */
  10772. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  10773. /**
  10774. * TSL object that represents the opacity of the current material.
  10775. * The value is composed via `opacity` * `alphaMap`.
  10776. *
  10777. * @tsl
  10778. * @type {Node<float>}
  10779. */
  10780. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  10781. /**
  10782. * TSL object that represents the specular of the current material.
  10783. *
  10784. * @tsl
  10785. * @type {Node<vec3>}
  10786. */
  10787. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  10788. /**
  10789. * TSL object that represents the specular intensity of the current material.
  10790. * The value is composed via `specularIntensity` * `specularMap.a`.
  10791. *
  10792. * @tsl
  10793. * @type {Node<float>}
  10794. */
  10795. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  10796. /**
  10797. * TSL object that represents the specular color of the current material.
  10798. * The value is composed via `specularColor` * `specularMap.rgb`.
  10799. *
  10800. * @tsl
  10801. * @type {Node<vec3>}
  10802. */
  10803. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  10804. /**
  10805. * TSL object that represents the specular strength of the current material.
  10806. * The value is composed via `specularMap.r`.
  10807. *
  10808. * @tsl
  10809. * @type {Node<float>}
  10810. */
  10811. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  10812. /**
  10813. * TSL object that represents the reflectivity of the current material.
  10814. *
  10815. * @tsl
  10816. * @type {Node<float>}
  10817. */
  10818. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  10819. /**
  10820. * TSL object that represents the roughness of the current material.
  10821. * The value is composed via `roughness` * `roughnessMap.g`.
  10822. *
  10823. * @tsl
  10824. * @type {Node<float>}
  10825. */
  10826. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  10827. /**
  10828. * TSL object that represents the metalness of the current material.
  10829. * The value is composed via `metalness` * `metalnessMap.b`.
  10830. *
  10831. * @tsl
  10832. * @type {Node<float>}
  10833. */
  10834. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  10835. /**
  10836. * TSL object that represents the normal of the current material.
  10837. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  10838. *
  10839. * @tsl
  10840. * @type {Node<vec3>}
  10841. */
  10842. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  10843. /**
  10844. * TSL object that represents the clearcoat of the current material.
  10845. * The value is composed via `clearcoat` * `clearcoatMap.r`
  10846. *
  10847. * @tsl
  10848. * @type {Node<float>}
  10849. */
  10850. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  10851. /**
  10852. * TSL object that represents the clearcoat roughness of the current material.
  10853. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  10854. *
  10855. * @tsl
  10856. * @type {Node<float>}
  10857. */
  10858. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  10859. /**
  10860. * TSL object that represents the clearcoat normal of the current material.
  10861. * The value will be either `clearcoatNormalMap` or `normalView`.
  10862. *
  10863. * @tsl
  10864. * @type {Node<vec3>}
  10865. */
  10866. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  10867. /**
  10868. * TSL object that represents the rotation of the current sprite material.
  10869. *
  10870. * @tsl
  10871. * @type {Node<float>}
  10872. */
  10873. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  10874. /**
  10875. * TSL object that represents the sheen color of the current material.
  10876. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  10877. *
  10878. * @tsl
  10879. * @type {Node<vec3>}
  10880. */
  10881. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  10882. /**
  10883. * TSL object that represents the sheen roughness of the current material.
  10884. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  10885. *
  10886. * @tsl
  10887. * @type {Node<float>}
  10888. */
  10889. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  10890. /**
  10891. * TSL object that represents the anisotropy of the current material.
  10892. *
  10893. * @tsl
  10894. * @type {Node<vec2>}
  10895. */
  10896. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  10897. /**
  10898. * TSL object that represents the iridescence of the current material.
  10899. *
  10900. * @tsl
  10901. * @type {Node<float>}
  10902. */
  10903. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  10904. /**
  10905. * TSL object that represents the iridescence IOR of the current material.
  10906. *
  10907. * @tsl
  10908. * @type {Node<float>}
  10909. */
  10910. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  10911. /**
  10912. * TSL object that represents the iridescence thickness of the current material.
  10913. *
  10914. * @tsl
  10915. * @type {Node<float>}
  10916. */
  10917. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  10918. /**
  10919. * TSL object that represents the transmission of the current material.
  10920. * The value is composed via `transmission` * `transmissionMap.r`.
  10921. *
  10922. * @tsl
  10923. * @type {Node<float>}
  10924. */
  10925. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  10926. /**
  10927. * TSL object that represents the thickness of the current material.
  10928. * The value is composed via `thickness` * `thicknessMap.g`.
  10929. *
  10930. * @tsl
  10931. * @type {Node<float>}
  10932. */
  10933. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  10934. /**
  10935. * TSL object that represents the IOR of the current material.
  10936. *
  10937. * @tsl
  10938. * @type {Node<float>}
  10939. */
  10940. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  10941. /**
  10942. * TSL object that represents the attenuation distance of the current material.
  10943. *
  10944. * @tsl
  10945. * @type {Node<float>}
  10946. */
  10947. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  10948. /**
  10949. * TSL object that represents the attenuation color of the current material.
  10950. *
  10951. * @tsl
  10952. * @type {Node<vec3>}
  10953. */
  10954. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  10955. /**
  10956. * TSL object that represents the scale of the current dashed line material.
  10957. *
  10958. * @tsl
  10959. * @type {Node<float>}
  10960. */
  10961. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  10962. /**
  10963. * TSL object that represents the dash size of the current dashed line material.
  10964. *
  10965. * @tsl
  10966. * @type {Node<float>}
  10967. */
  10968. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  10969. /**
  10970. * TSL object that represents the gap size of the current dashed line material.
  10971. *
  10972. * @tsl
  10973. * @type {Node<float>}
  10974. */
  10975. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  10976. /**
  10977. * TSL object that represents the line width of the current line material.
  10978. *
  10979. * @tsl
  10980. * @type {Node<float>}
  10981. */
  10982. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  10983. /**
  10984. * TSL object that represents the dash offset of the current line material.
  10985. *
  10986. * @tsl
  10987. * @type {Node<float>}
  10988. */
  10989. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  10990. /**
  10991. * TSL object that represents the point size of the current points material.
  10992. *
  10993. * @tsl
  10994. * @type {Node<float>}
  10995. */
  10996. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  10997. /**
  10998. * TSL object that represents the dispersion of the current material.
  10999. *
  11000. * @tsl
  11001. * @type {Node<float>}
  11002. */
  11003. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  11004. /**
  11005. * TSL object that represents the light map of the current material.
  11006. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  11007. *
  11008. * @tsl
  11009. * @type {Node<vec3>}
  11010. */
  11011. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  11012. /**
  11013. * TSL object that represents the ambient occlusion map of the current material.
  11014. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  11015. *
  11016. * @tsl
  11017. * @type {Node<float>}
  11018. */
  11019. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  11020. /**
  11021. * TSL object that represents the anisotropy vector of the current material.
  11022. *
  11023. * @tsl
  11024. * @type {Node<vec2>}
  11025. */
  11026. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  11027. return frame.material;
  11028. } ).onRenderUpdate( function ( { material } ) {
  11029. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  11030. } );
  11031. /**
  11032. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  11033. *
  11034. * @tsl
  11035. * @type {VaryingNode<vec4>}
  11036. */
  11037. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  11038. return builder.context.setupModelViewProjection();
  11039. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  11040. /**
  11041. * This class represents shader indices of different types. The following predefined node
  11042. * objects cover frequent use cases:
  11043. *
  11044. * - `vertexIndex`: The index of a vertex within a mesh.
  11045. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  11046. * - `drawIndex`: The index of a draw call.
  11047. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  11048. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  11049. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  11050. *
  11051. * @augments Node
  11052. */
  11053. class IndexNode extends Node {
  11054. static get type() {
  11055. return 'IndexNode';
  11056. }
  11057. /**
  11058. * Constructs a new index node.
  11059. *
  11060. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  11061. */
  11062. constructor( scope ) {
  11063. super( 'uint' );
  11064. /**
  11065. * The scope of the index node.
  11066. *
  11067. * @type {string}
  11068. */
  11069. this.scope = scope;
  11070. /**
  11071. * This flag can be used for type testing.
  11072. *
  11073. * @type {boolean}
  11074. * @readonly
  11075. * @default true
  11076. */
  11077. this.isIndexNode = true;
  11078. }
  11079. generate( builder ) {
  11080. const nodeType = this.getNodeType( builder );
  11081. const scope = this.scope;
  11082. let propertyName;
  11083. if ( scope === IndexNode.VERTEX ) {
  11084. propertyName = builder.getVertexIndex();
  11085. } else if ( scope === IndexNode.INSTANCE ) {
  11086. propertyName = builder.getInstanceIndex();
  11087. } else if ( scope === IndexNode.DRAW ) {
  11088. propertyName = builder.getDrawIndex();
  11089. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  11090. propertyName = builder.getInvocationLocalIndex();
  11091. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  11092. propertyName = builder.getInvocationSubgroupIndex();
  11093. } else if ( scope === IndexNode.SUBGROUP ) {
  11094. propertyName = builder.getSubgroupIndex();
  11095. } else {
  11096. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  11097. }
  11098. let output;
  11099. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  11100. output = propertyName;
  11101. } else {
  11102. const nodeVarying = varying( this );
  11103. output = nodeVarying.build( builder, nodeType );
  11104. }
  11105. return output;
  11106. }
  11107. }
  11108. IndexNode.VERTEX = 'vertex';
  11109. IndexNode.INSTANCE = 'instance';
  11110. IndexNode.SUBGROUP = 'subgroup';
  11111. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  11112. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  11113. IndexNode.DRAW = 'draw';
  11114. /**
  11115. * TSL object that represents the index of a vertex within a mesh.
  11116. *
  11117. * @tsl
  11118. * @type {IndexNode}
  11119. */
  11120. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  11121. /**
  11122. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  11123. *
  11124. * @tsl
  11125. * @type {IndexNode}
  11126. */
  11127. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  11128. /**
  11129. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  11130. *
  11131. * @tsl
  11132. * @type {IndexNode}
  11133. */
  11134. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  11135. /**
  11136. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  11137. *
  11138. * @tsl
  11139. * @type {IndexNode}
  11140. */
  11141. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  11142. /**
  11143. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  11144. *
  11145. * @tsl
  11146. * @type {IndexNode}
  11147. */
  11148. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  11149. /**
  11150. * TSL object that represents the index of a draw call.
  11151. *
  11152. * @tsl
  11153. * @type {IndexNode}
  11154. */
  11155. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  11156. /**
  11157. * This node implements the vertex shader logic which is required
  11158. * when rendering 3D objects via instancing. The code makes sure
  11159. * vertex positions, normals and colors can be modified via instanced
  11160. * data.
  11161. *
  11162. * @augments Node
  11163. */
  11164. class InstanceNode extends Node {
  11165. static get type() {
  11166. return 'InstanceNode';
  11167. }
  11168. /**
  11169. * Constructs a new instance node.
  11170. *
  11171. * @param {number} count - The number of instances.
  11172. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11173. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11174. */
  11175. constructor( count, instanceMatrix, instanceColor = null ) {
  11176. super( 'void' );
  11177. /**
  11178. * The number of instances.
  11179. *
  11180. * @type {number}
  11181. */
  11182. this.count = count;
  11183. /**
  11184. * Instanced buffer attribute representing the transformation of instances.
  11185. *
  11186. * @type {InstancedBufferAttribute}
  11187. */
  11188. this.instanceMatrix = instanceMatrix;
  11189. /**
  11190. * Instanced buffer attribute representing the color of instances.
  11191. *
  11192. * @type {InstancedBufferAttribute}
  11193. */
  11194. this.instanceColor = instanceColor;
  11195. /**
  11196. * The node that represents the instance matrix data.
  11197. *
  11198. * @type {?Node}
  11199. */
  11200. this.instanceMatrixNode = null;
  11201. /**
  11202. * The node that represents the instance color data.
  11203. *
  11204. * @type {?Node}
  11205. * @default null
  11206. */
  11207. this.instanceColorNode = null;
  11208. /**
  11209. * The update type is set to `frame` since an update
  11210. * of instanced buffer data must be checked per frame.
  11211. *
  11212. * @type {string}
  11213. * @default 'frame'
  11214. */
  11215. this.updateType = NodeUpdateType.FRAME;
  11216. /**
  11217. * A reference to a buffer that is used by `instanceMatrixNode`.
  11218. *
  11219. * @type {?InstancedInterleavedBuffer}
  11220. */
  11221. this.buffer = null;
  11222. /**
  11223. * A reference to a buffer that is used by `instanceColorNode`.
  11224. *
  11225. * @type {?InstancedBufferAttribute}
  11226. */
  11227. this.bufferColor = null;
  11228. }
  11229. /**
  11230. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11231. * to predefined node variables for accumulation. That follows the same patterns
  11232. * like with morph and skinning nodes.
  11233. *
  11234. * @param {NodeBuilder} builder - The current node builder.
  11235. */
  11236. setup( builder ) {
  11237. const { instanceMatrix, instanceColor } = this;
  11238. const { count } = instanceMatrix;
  11239. let { instanceMatrixNode, instanceColorNode } = this;
  11240. if ( instanceMatrixNode === null ) {
  11241. // 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.
  11242. if ( count <= 1000 ) {
  11243. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  11244. } else {
  11245. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  11246. this.buffer = buffer;
  11247. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11248. const instanceBuffers = [
  11249. // F.Signature -> bufferAttribute( array, type, stride, offset )
  11250. bufferFn( buffer, 'vec4', 16, 0 ),
  11251. bufferFn( buffer, 'vec4', 16, 4 ),
  11252. bufferFn( buffer, 'vec4', 16, 8 ),
  11253. bufferFn( buffer, 'vec4', 16, 12 )
  11254. ];
  11255. instanceMatrixNode = mat4( ...instanceBuffers );
  11256. }
  11257. this.instanceMatrixNode = instanceMatrixNode;
  11258. }
  11259. if ( instanceColor && instanceColorNode === null ) {
  11260. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  11261. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  11262. this.bufferColor = buffer;
  11263. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  11264. this.instanceColorNode = instanceColorNode;
  11265. }
  11266. // POSITION
  11267. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  11268. positionLocal.assign( instancePosition );
  11269. // NORMAL
  11270. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11271. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  11272. // ASSIGNS
  11273. normalLocal.assign( instanceNormal );
  11274. }
  11275. // COLOR
  11276. if ( this.instanceColorNode !== null ) {
  11277. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  11278. }
  11279. }
  11280. /**
  11281. * Checks if the internal buffers required an update.
  11282. *
  11283. * @param {NodeFrame} frame - The current node frame.
  11284. */
  11285. update( /*frame*/ ) {
  11286. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  11287. this.buffer.version = this.instanceMatrix.version;
  11288. }
  11289. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  11290. this.bufferColor.version = this.instanceColor.version;
  11291. }
  11292. }
  11293. }
  11294. /**
  11295. * TSL function for creating an instance node.
  11296. *
  11297. * @tsl
  11298. * @function
  11299. * @param {number} count - The number of instances.
  11300. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  11301. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  11302. * @returns {InstanceNode}
  11303. */
  11304. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  11305. /**
  11306. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  11307. * It allows an easier setup of the instance node.
  11308. *
  11309. * @augments InstanceNode
  11310. */
  11311. class InstancedMeshNode extends InstanceNode {
  11312. static get type() {
  11313. return 'InstancedMeshNode';
  11314. }
  11315. /**
  11316. * Constructs a new instanced mesh node.
  11317. *
  11318. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  11319. */
  11320. constructor( instancedMesh ) {
  11321. const { count, instanceMatrix, instanceColor } = instancedMesh;
  11322. super( count, instanceMatrix, instanceColor );
  11323. /**
  11324. * A reference to the instanced mesh.
  11325. *
  11326. * @type {InstancedMesh}
  11327. */
  11328. this.instancedMesh = instancedMesh;
  11329. }
  11330. }
  11331. /**
  11332. * TSL function for creating an instanced mesh node.
  11333. *
  11334. * @tsl
  11335. * @function
  11336. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  11337. * @returns {InstancedMeshNode}
  11338. */
  11339. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  11340. /**
  11341. * This node implements the vertex shader logic which is required
  11342. * when rendering 3D objects via batching. `BatchNode` must be used
  11343. * with instances of {@link BatchedMesh}.
  11344. *
  11345. * @augments Node
  11346. */
  11347. class BatchNode extends Node {
  11348. static get type() {
  11349. return 'BatchNode';
  11350. }
  11351. /**
  11352. * Constructs a new batch node.
  11353. *
  11354. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11355. */
  11356. constructor( batchMesh ) {
  11357. super( 'void' );
  11358. /**
  11359. * A reference to batched mesh.
  11360. *
  11361. * @type {BatchedMesh}
  11362. */
  11363. this.batchMesh = batchMesh;
  11364. /**
  11365. * The batching index node.
  11366. *
  11367. * @type {?IndexNode}
  11368. * @default null
  11369. */
  11370. this.batchingIdNode = null;
  11371. }
  11372. /**
  11373. * Setups the internal buffers and nodes and assigns the transformed vertex data
  11374. * to predefined node variables for accumulation. That follows the same patterns
  11375. * like with morph and skinning nodes.
  11376. *
  11377. * @param {NodeBuilder} builder - The current node builder.
  11378. */
  11379. setup( builder ) {
  11380. if ( this.batchingIdNode === null ) {
  11381. if ( builder.getDrawIndex() === null ) {
  11382. this.batchingIdNode = instanceIndex;
  11383. } else {
  11384. this.batchingIdNode = drawIndex;
  11385. }
  11386. }
  11387. const getIndirectIndex = Fn( ( [ id ] ) => {
  11388. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  11389. const x = int( id ).mod( size );
  11390. const y = int( id ).div( size );
  11391. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  11392. } ).setLayout( {
  11393. name: 'getIndirectIndex',
  11394. type: 'uint',
  11395. inputs: [
  11396. { name: 'id', type: 'int' }
  11397. ]
  11398. } );
  11399. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  11400. const matricesTexture = this.batchMesh._matricesTexture;
  11401. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  11402. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  11403. const x = j.mod( size );
  11404. const y = j.div( size );
  11405. const batchingMatrix = mat4(
  11406. textureLoad( matricesTexture, ivec2( x, y ) ),
  11407. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  11408. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  11409. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  11410. );
  11411. const colorsTexture = this.batchMesh._colorsTexture;
  11412. if ( colorsTexture !== null ) {
  11413. const getBatchingColor = Fn( ( [ id ] ) => {
  11414. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  11415. const j = id;
  11416. const x = j.mod( size );
  11417. const y = j.div( size );
  11418. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  11419. } ).setLayout( {
  11420. name: 'getBatchingColor',
  11421. type: 'vec3',
  11422. inputs: [
  11423. { name: 'id', type: 'int' }
  11424. ]
  11425. } );
  11426. const color = getBatchingColor( indirectId );
  11427. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  11428. }
  11429. const bm = mat3( batchingMatrix );
  11430. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  11431. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  11432. const batchingNormal = bm.mul( transformedNormal ).xyz;
  11433. normalLocal.assign( batchingNormal );
  11434. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11435. tangentLocal.mulAssign( bm );
  11436. }
  11437. }
  11438. }
  11439. /**
  11440. * TSL function for creating a batch node.
  11441. *
  11442. * @tsl
  11443. * @function
  11444. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  11445. * @returns {BatchNode}
  11446. */
  11447. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  11448. /**
  11449. * This class enables element access on instances of {@link StorageBufferNode}.
  11450. * In most cases, it is indirectly used when accessing elements with the
  11451. * {@link StorageBufferNode#element} method.
  11452. *
  11453. * ```js
  11454. * const position = positionStorage.element( instanceIndex );
  11455. * ```
  11456. *
  11457. * @augments ArrayElementNode
  11458. */
  11459. class StorageArrayElementNode extends ArrayElementNode {
  11460. static get type() {
  11461. return 'StorageArrayElementNode';
  11462. }
  11463. /**
  11464. * Constructs storage buffer element node.
  11465. *
  11466. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11467. * @param {Node} indexNode - The index node that defines the element access.
  11468. */
  11469. constructor( storageBufferNode, indexNode ) {
  11470. super( storageBufferNode, indexNode );
  11471. /**
  11472. * This flag can be used for type testing.
  11473. *
  11474. * @type {boolean}
  11475. * @readonly
  11476. * @default true
  11477. */
  11478. this.isStorageArrayElementNode = true;
  11479. }
  11480. /**
  11481. * The storage buffer node.
  11482. *
  11483. * @param {Node} value
  11484. * @type {StorageBufferNode}
  11485. */
  11486. set storageBufferNode( value ) {
  11487. this.node = value;
  11488. }
  11489. get storageBufferNode() {
  11490. return this.node;
  11491. }
  11492. getMemberType( builder, name ) {
  11493. const structTypeNode = this.storageBufferNode.structTypeNode;
  11494. if ( structTypeNode ) {
  11495. return structTypeNode.getMemberType( builder, name );
  11496. }
  11497. return 'void';
  11498. }
  11499. setup( builder ) {
  11500. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11501. if ( this.node.isPBO === true ) {
  11502. builder.setupPBO( this.node );
  11503. }
  11504. }
  11505. return super.setup( builder );
  11506. }
  11507. generate( builder, output ) {
  11508. let snippet;
  11509. const isAssignContext = builder.context.assign;
  11510. //
  11511. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  11512. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  11513. snippet = builder.generatePBO( this );
  11514. } else {
  11515. snippet = this.node.build( builder );
  11516. }
  11517. } else {
  11518. snippet = super.generate( builder );
  11519. }
  11520. if ( isAssignContext !== true ) {
  11521. const type = this.getNodeType( builder );
  11522. snippet = builder.format( snippet, type, output );
  11523. }
  11524. return snippet;
  11525. }
  11526. }
  11527. /**
  11528. * TSL function for creating a storage element node.
  11529. *
  11530. * @tsl
  11531. * @function
  11532. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  11533. * @param {Node} indexNode - The index node that defines the element access.
  11534. * @returns {StorageArrayElementNode}
  11535. */
  11536. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  11537. /**
  11538. * This node is used in context of compute shaders and allows to define a
  11539. * storage buffer for data. A typical workflow is to create instances of
  11540. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  11541. * setup up a compute shader that writes into the buffers and then convert
  11542. * the storage buffers to attribute nodes for rendering.
  11543. *
  11544. * ```js
  11545. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  11546. *
  11547. * const computeInit = Fn( () => { // the compute shader
  11548. *
  11549. * const position = positionBuffer.element( instanceIndex );
  11550. *
  11551. * // compute position data
  11552. *
  11553. * position.x = 1;
  11554. * position.y = 1;
  11555. * position.z = 1;
  11556. *
  11557. * } )().compute( particleCount );
  11558. *
  11559. * const particleMaterial = new THREE.SpriteNodeMaterial();
  11560. * particleMaterial.positionNode = positionBuffer.toAttribute();
  11561. *
  11562. * renderer.computeAsync( computeInit );
  11563. *
  11564. * ```
  11565. *
  11566. * @augments BufferNode
  11567. */
  11568. class StorageBufferNode extends BufferNode {
  11569. static get type() {
  11570. return 'StorageBufferNode';
  11571. }
  11572. /**
  11573. * Constructs a new storage buffer node.
  11574. *
  11575. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11576. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  11577. * @param {number} [bufferCount=0] - The buffer count.
  11578. */
  11579. constructor( value, bufferType = null, bufferCount = 0 ) {
  11580. let nodeType, structTypeNode = null;
  11581. if ( bufferType && bufferType.isStruct ) {
  11582. nodeType = 'struct';
  11583. structTypeNode = bufferType.layout;
  11584. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  11585. bufferCount = value.count;
  11586. }
  11587. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  11588. nodeType = getTypeFromLength( value.itemSize );
  11589. bufferCount = value.count;
  11590. } else {
  11591. nodeType = bufferType;
  11592. }
  11593. super( value, nodeType, bufferCount );
  11594. /**
  11595. * This flag can be used for type testing.
  11596. *
  11597. * @type {boolean}
  11598. * @readonly
  11599. * @default true
  11600. */
  11601. this.isStorageBufferNode = true;
  11602. /**
  11603. * The buffer struct type.
  11604. *
  11605. * @type {?StructTypeNode}
  11606. * @default null
  11607. */
  11608. this.structTypeNode = structTypeNode;
  11609. /**
  11610. * The access type of the texture node.
  11611. *
  11612. * @type {string}
  11613. * @default 'readWrite'
  11614. */
  11615. this.access = NodeAccess.READ_WRITE;
  11616. /**
  11617. * Whether the node is atomic or not.
  11618. *
  11619. * @type {boolean}
  11620. * @default false
  11621. */
  11622. this.isAtomic = false;
  11623. /**
  11624. * Whether the node represents a PBO or not.
  11625. * Only relevant for WebGL.
  11626. *
  11627. * @type {boolean}
  11628. * @default false
  11629. */
  11630. this.isPBO = false;
  11631. /**
  11632. * A reference to the internal buffer attribute node.
  11633. *
  11634. * @type {?BufferAttributeNode}
  11635. * @default null
  11636. */
  11637. this._attribute = null;
  11638. /**
  11639. * A reference to the internal varying node.
  11640. *
  11641. * @type {?VaryingNode}
  11642. * @default null
  11643. */
  11644. this._varying = null;
  11645. /**
  11646. * `StorageBufferNode` sets this property to `true` by default.
  11647. *
  11648. * @type {boolean}
  11649. * @default true
  11650. */
  11651. this.global = true;
  11652. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  11653. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  11654. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  11655. else value.isStorageBufferAttribute = true;
  11656. }
  11657. }
  11658. /**
  11659. * This method is overwritten since the buffer data might be shared
  11660. * and thus the hash should be shared as well.
  11661. *
  11662. * @param {NodeBuilder} builder - The current node builder.
  11663. * @return {string} The hash.
  11664. */
  11665. getHash( builder ) {
  11666. if ( this.bufferCount === 0 ) {
  11667. let bufferData = builder.globalCache.getData( this.value );
  11668. if ( bufferData === undefined ) {
  11669. bufferData = {
  11670. node: this
  11671. };
  11672. builder.globalCache.setData( this.value, bufferData );
  11673. }
  11674. return bufferData.node.uuid;
  11675. }
  11676. return this.uuid;
  11677. }
  11678. /**
  11679. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  11680. *
  11681. * @param {NodeBuilder} builder - The current node builder.
  11682. * @return {string} The input type.
  11683. */
  11684. getInputType( /*builder*/ ) {
  11685. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  11686. }
  11687. /**
  11688. * Enables element access with the given index node.
  11689. *
  11690. * @param {IndexNode} indexNode - The index node.
  11691. * @return {StorageArrayElementNode} A node representing the element access.
  11692. */
  11693. element( indexNode ) {
  11694. return storageElement( this, indexNode );
  11695. }
  11696. /**
  11697. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  11698. *
  11699. * @param {boolean} value - The value so set.
  11700. * @return {StorageBufferNode} A reference to this node.
  11701. */
  11702. setPBO( value ) {
  11703. this.isPBO = value;
  11704. return this;
  11705. }
  11706. /**
  11707. * Returns the `isPBO` value.
  11708. *
  11709. * @return {boolean} Whether the node represents a PBO or not.
  11710. */
  11711. getPBO() {
  11712. return this.isPBO;
  11713. }
  11714. /**
  11715. * Defines the node access.
  11716. *
  11717. * @param {string} value - The node access.
  11718. * @return {StorageBufferNode} A reference to this node.
  11719. */
  11720. setAccess( value ) {
  11721. this.access = value;
  11722. return this;
  11723. }
  11724. /**
  11725. * Convenience method for configuring a read-only node access.
  11726. *
  11727. * @return {StorageBufferNode} A reference to this node.
  11728. */
  11729. toReadOnly() {
  11730. return this.setAccess( NodeAccess.READ_ONLY );
  11731. }
  11732. /**
  11733. * Defines whether the node is atomic or not.
  11734. *
  11735. * @param {boolean} value - The atomic flag.
  11736. * @return {StorageBufferNode} A reference to this node.
  11737. */
  11738. setAtomic( value ) {
  11739. this.isAtomic = value;
  11740. return this;
  11741. }
  11742. /**
  11743. * Convenience method for making this node atomic.
  11744. *
  11745. * @return {StorageBufferNode} A reference to this node.
  11746. */
  11747. toAtomic() {
  11748. return this.setAtomic( true );
  11749. }
  11750. /**
  11751. * Returns attribute data for this storage buffer node.
  11752. *
  11753. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  11754. */
  11755. getAttributeData() {
  11756. if ( this._attribute === null ) {
  11757. this._attribute = bufferAttribute( this.value );
  11758. this._varying = varying( this._attribute );
  11759. }
  11760. return {
  11761. attribute: this._attribute,
  11762. varying: this._varying
  11763. };
  11764. }
  11765. /**
  11766. * This method is overwritten since the node type from the availability of storage buffers
  11767. * and the attribute data.
  11768. *
  11769. * @param {NodeBuilder} builder - The current node builder.
  11770. * @return {string} The node type.
  11771. */
  11772. getNodeType( builder ) {
  11773. if ( this.structTypeNode !== null ) {
  11774. return this.structTypeNode.getNodeType( builder );
  11775. }
  11776. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11777. return super.getNodeType( builder );
  11778. }
  11779. const { attribute } = this.getAttributeData();
  11780. return attribute.getNodeType( builder );
  11781. }
  11782. /**
  11783. * Returns the type of a member of the struct.
  11784. *
  11785. * @param {NodeBuilder} builder - The current node builder.
  11786. * @param {string} name - The name of the member.
  11787. * @return {string} The type of the member.
  11788. */
  11789. getMemberType( builder, name ) {
  11790. if ( this.structTypeNode !== null ) {
  11791. return this.structTypeNode.getMemberType( builder, name );
  11792. }
  11793. return 'void';
  11794. }
  11795. /**
  11796. * Generates the code snippet of the storage buffer node.
  11797. *
  11798. * @param {NodeBuilder} builder - The current node builder.
  11799. * @return {string} The generated code snippet.
  11800. */
  11801. generate( builder ) {
  11802. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  11803. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  11804. return super.generate( builder );
  11805. }
  11806. const { attribute, varying } = this.getAttributeData();
  11807. const output = varying.build( builder );
  11808. builder.registerTransform( output, attribute );
  11809. return output;
  11810. }
  11811. }
  11812. /**
  11813. * TSL function for creating a storage buffer node.
  11814. *
  11815. * @tsl
  11816. * @function
  11817. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11818. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  11819. * @param {number} [count=0] - The buffer count.
  11820. * @returns {StorageBufferNode}
  11821. */
  11822. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  11823. /**
  11824. * @tsl
  11825. * @function
  11826. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  11827. *
  11828. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  11829. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  11830. * @param {number} count - The buffer count.
  11831. * @returns {StorageBufferNode}
  11832. */
  11833. const storageObject = ( value, type, count ) => { // @deprecated, r171
  11834. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  11835. return storage( value, type, count ).setPBO( true );
  11836. };
  11837. const _frameId = new WeakMap();
  11838. /**
  11839. * This node implements the vertex transformation shader logic which is required
  11840. * for skinning/skeletal animation.
  11841. *
  11842. * @augments Node
  11843. */
  11844. class SkinningNode extends Node {
  11845. static get type() {
  11846. return 'SkinningNode';
  11847. }
  11848. /**
  11849. * Constructs a new skinning node.
  11850. *
  11851. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11852. */
  11853. constructor( skinnedMesh ) {
  11854. super( 'void' );
  11855. /**
  11856. * The skinned mesh.
  11857. *
  11858. * @type {SkinnedMesh}
  11859. */
  11860. this.skinnedMesh = skinnedMesh;
  11861. /**
  11862. * The update type overwritten since skinning nodes are updated per object.
  11863. *
  11864. * @type {string}
  11865. */
  11866. this.updateType = NodeUpdateType.OBJECT;
  11867. //
  11868. /**
  11869. * The skin index attribute.
  11870. *
  11871. * @type {AttributeNode}
  11872. */
  11873. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  11874. /**
  11875. * The skin weight attribute.
  11876. *
  11877. * @type {AttributeNode}
  11878. */
  11879. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  11880. /**
  11881. * The bind matrix node.
  11882. *
  11883. * @type {Node<mat4>}
  11884. */
  11885. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  11886. /**
  11887. * The bind matrix inverse node.
  11888. *
  11889. * @type {Node<mat4>}
  11890. */
  11891. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  11892. /**
  11893. * The bind matrices as a uniform buffer node.
  11894. *
  11895. * @type {Node}
  11896. */
  11897. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11898. /**
  11899. * The current vertex position in local space.
  11900. *
  11901. * @type {Node<vec3>}
  11902. */
  11903. this.positionNode = positionLocal;
  11904. /**
  11905. * The result of vertex position in local space.
  11906. *
  11907. * @type {Node<vec3>}
  11908. */
  11909. this.toPositionNode = positionLocal;
  11910. /**
  11911. * The previous bind matrices as a uniform buffer node.
  11912. * Required for computing motion vectors.
  11913. *
  11914. * @type {?Node}
  11915. * @default null
  11916. */
  11917. this.previousBoneMatricesNode = null;
  11918. }
  11919. /**
  11920. * Transforms the given vertex position via skinning.
  11921. *
  11922. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11923. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  11924. * @return {Node<vec3>} The transformed vertex position.
  11925. */
  11926. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  11927. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11928. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11929. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11930. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11931. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11932. // POSITION
  11933. const skinVertex = bindMatrixNode.mul( position );
  11934. const skinned = add(
  11935. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  11936. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  11937. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  11938. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  11939. );
  11940. return bindMatrixInverseNode.mul( skinned ).xyz;
  11941. }
  11942. /**
  11943. * Transforms the given vertex normal via skinning.
  11944. *
  11945. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11946. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  11947. * @return {Node<vec3>} The transformed vertex normal.
  11948. */
  11949. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  11950. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11951. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11952. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11953. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11954. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11955. // NORMAL
  11956. let skinMatrix = add(
  11957. skinWeightNode.x.mul( boneMatX ),
  11958. skinWeightNode.y.mul( boneMatY ),
  11959. skinWeightNode.z.mul( boneMatZ ),
  11960. skinWeightNode.w.mul( boneMatW )
  11961. );
  11962. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  11963. return skinMatrix.transformDirection( normal ).xyz;
  11964. }
  11965. /**
  11966. * Computes the transformed/skinned vertex position of the previous frame.
  11967. *
  11968. * @param {NodeBuilder} builder - The current node builder.
  11969. * @return {Node<vec3>} The skinned position from the previous frame.
  11970. */
  11971. getPreviousSkinnedPosition( builder ) {
  11972. const skinnedMesh = builder.object;
  11973. if ( this.previousBoneMatricesNode === null ) {
  11974. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  11975. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11976. }
  11977. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  11978. }
  11979. /**
  11980. * Returns `true` if bone matrices from the previous frame are required. Relevant
  11981. * when computing motion vectors with {@link VelocityNode}.
  11982. *
  11983. * @param {NodeBuilder} builder - The current node builder.
  11984. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  11985. */
  11986. needsPreviousBoneMatrices( builder ) {
  11987. const mrt = builder.renderer.getMRT();
  11988. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  11989. }
  11990. /**
  11991. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  11992. *
  11993. * @param {NodeBuilder} builder - The current node builder.
  11994. * @return {Node<vec3>} The transformed vertex position.
  11995. */
  11996. setup( builder ) {
  11997. if ( this.needsPreviousBoneMatrices( builder ) ) {
  11998. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  11999. }
  12000. const skinPosition = this.getSkinnedPosition();
  12001. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  12002. //
  12003. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  12004. const skinNormal = this.getSkinnedNormal();
  12005. normalLocal.assign( skinNormal );
  12006. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  12007. tangentLocal.assign( skinNormal );
  12008. }
  12009. }
  12010. return skinPosition;
  12011. }
  12012. /**
  12013. * Generates the code snippet of the skinning node.
  12014. *
  12015. * @param {NodeBuilder} builder - The current node builder.
  12016. * @param {string} output - The current output.
  12017. * @return {string} The generated code snippet.
  12018. */
  12019. generate( builder, output ) {
  12020. if ( output !== 'void' ) {
  12021. return super.generate( builder, output );
  12022. }
  12023. }
  12024. /**
  12025. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  12026. *
  12027. * @param {NodeFrame} frame - The current node frame.
  12028. */
  12029. update( frame ) {
  12030. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  12031. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  12032. _frameId.set( skeleton, frame.frameId );
  12033. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  12034. skeleton.update();
  12035. }
  12036. }
  12037. /**
  12038. * TSL function for creating a skinning node.
  12039. *
  12040. * @tsl
  12041. * @function
  12042. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12043. * @returns {SkinningNode}
  12044. */
  12045. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  12046. /**
  12047. * TSL function for computing skinning.
  12048. *
  12049. * @tsl
  12050. * @function
  12051. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  12052. * @param {Node<vec3>} [toPosition=null] - The target position.
  12053. * @returns {SkinningNode}
  12054. */
  12055. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  12056. const node = new SkinningNode( skinnedMesh );
  12057. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12058. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12059. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  12060. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  12061. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  12062. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  12063. node.toPositionNode = toPosition;
  12064. return nodeObject( node );
  12065. };
  12066. /**
  12067. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  12068. * ```js
  12069. * Loop( count, ( { i } ) => {
  12070. *
  12071. * } );
  12072. * ```
  12073. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  12074. * ```js
  12075. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  12076. *
  12077. * } );
  12078. *```
  12079. * Nested loops can be defined in a compacted form:
  12080. * ```js
  12081. * Loop( 10, 5, ( { i, j } ) => {
  12082. *
  12083. * } );
  12084. * ```
  12085. * Loops that should run backwards can be defined like so:
  12086. * ```js
  12087. * Loop( { start: 10 }, () => {} );
  12088. * ```
  12089. * It is possible to execute with boolean values, similar to the `while` syntax.
  12090. * ```js
  12091. * const value = float( 0 ).toVar();
  12092. *
  12093. * Loop( value.lessThan( 10 ), () => {
  12094. *
  12095. * value.addAssign( 1 );
  12096. *
  12097. * } );
  12098. * ```
  12099. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  12100. * @augments Node
  12101. */
  12102. class LoopNode extends Node {
  12103. static get type() {
  12104. return 'LoopNode';
  12105. }
  12106. /**
  12107. * Constructs a new loop node.
  12108. *
  12109. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  12110. */
  12111. constructor( params = [] ) {
  12112. super();
  12113. this.params = params;
  12114. }
  12115. /**
  12116. * Returns a loop variable name based on an index. The pattern is
  12117. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  12118. *
  12119. * @param {number} index - The index.
  12120. * @return {string} The loop variable name.
  12121. */
  12122. getVarName( index ) {
  12123. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  12124. }
  12125. /**
  12126. * Returns properties about this node.
  12127. *
  12128. * @param {NodeBuilder} builder - The current node builder.
  12129. * @return {Object} The node properties.
  12130. */
  12131. getProperties( builder ) {
  12132. const properties = builder.getNodeProperties( this );
  12133. if ( properties.stackNode !== undefined ) return properties;
  12134. //
  12135. const inputs = {};
  12136. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12137. const param = this.params[ i ];
  12138. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  12139. const type = ( param.isNode !== true && param.type ) || 'int';
  12140. inputs[ name ] = expression( name, type );
  12141. }
  12142. const stack = builder.addStack(); // TODO: cache() it
  12143. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder );
  12144. properties.stackNode = stack;
  12145. const baseParam = this.params[ 0 ];
  12146. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  12147. properties.updateNode = Fn( this.params[ 0 ].update )( inputs );
  12148. }
  12149. builder.removeStack();
  12150. return properties;
  12151. }
  12152. /**
  12153. * This method is overwritten since the node type is inferred based on the loop configuration.
  12154. *
  12155. * @param {NodeBuilder} builder - The current node builder.
  12156. * @return {string} The node type.
  12157. */
  12158. getNodeType( builder ) {
  12159. const { returnsNode } = this.getProperties( builder );
  12160. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  12161. }
  12162. setup( builder ) {
  12163. // setup properties
  12164. this.getProperties( builder );
  12165. }
  12166. generate( builder ) {
  12167. const properties = this.getProperties( builder );
  12168. const params = this.params;
  12169. const stackNode = properties.stackNode;
  12170. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  12171. const param = params[ i ];
  12172. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  12173. if ( param.isNode ) {
  12174. if ( param.getNodeType( builder ) === 'bool' ) {
  12175. isWhile = true;
  12176. type = 'bool';
  12177. end = param.build( builder, type );
  12178. } else {
  12179. type = 'int';
  12180. name = this.getVarName( i );
  12181. start = '0';
  12182. end = param.build( builder, type );
  12183. condition = '<';
  12184. }
  12185. } else {
  12186. type = param.type || 'int';
  12187. name = param.name || this.getVarName( i );
  12188. start = param.start;
  12189. end = param.end;
  12190. condition = param.condition;
  12191. update = param.update;
  12192. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  12193. else if ( start && start.isNode ) start = start.build( builder, type );
  12194. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  12195. else if ( end && end.isNode ) end = end.build( builder, type );
  12196. if ( start !== undefined && end === undefined ) {
  12197. start = start + ' - 1';
  12198. end = '0';
  12199. condition = '>=';
  12200. } else if ( end !== undefined && start === undefined ) {
  12201. start = '0';
  12202. condition = '<';
  12203. }
  12204. if ( condition === undefined ) {
  12205. if ( Number( start ) > Number( end ) ) {
  12206. condition = '>=';
  12207. } else {
  12208. condition = '<';
  12209. }
  12210. }
  12211. }
  12212. let loopSnippet;
  12213. if ( isWhile ) {
  12214. loopSnippet = `while ( ${ end } )`;
  12215. } else {
  12216. const internalParam = { start, end};
  12217. //
  12218. const startSnippet = internalParam.start;
  12219. const endSnippet = internalParam.end;
  12220. let updateSnippet;
  12221. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  12222. if ( update !== undefined && update !== null ) {
  12223. switch ( typeof update ) {
  12224. case 'function':
  12225. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  12226. const snippet = flow.code.replace( /\t|;/g, '' );
  12227. updateSnippet = snippet;
  12228. break;
  12229. case 'number':
  12230. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  12231. break;
  12232. case 'string':
  12233. updateSnippet = name + ' ' + update;
  12234. break;
  12235. default:
  12236. if ( update.isNode ) {
  12237. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  12238. } else {
  12239. console.error( 'THREE.TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  12240. updateSnippet = 'break /* invalid update */';
  12241. }
  12242. }
  12243. } else {
  12244. if ( type === 'int' || type === 'uint' ) {
  12245. update = condition.includes( '<' ) ? '++' : '--';
  12246. } else {
  12247. update = deltaOperator() + ' 1.';
  12248. }
  12249. updateSnippet = name + ' ' + update;
  12250. }
  12251. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  12252. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  12253. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  12254. }
  12255. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  12256. }
  12257. const stackSnippet = stackNode.build( builder, 'void' );
  12258. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  12259. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  12260. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  12261. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  12262. }
  12263. builder.addFlowTab();
  12264. return returnsSnippet;
  12265. }
  12266. }
  12267. /**
  12268. * TSL function for creating a loop node.
  12269. *
  12270. * @tsl
  12271. * @function
  12272. * @param {...any} params - A list of parameters.
  12273. * @returns {LoopNode}
  12274. */
  12275. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).toStack();
  12276. /**
  12277. * TSL function for creating a `Continue()` expression.
  12278. *
  12279. * @tsl
  12280. * @function
  12281. * @returns {ExpressionNode}
  12282. */
  12283. const Continue = () => expression( 'continue' ).toStack();
  12284. /**
  12285. * TSL function for creating a `Break()` expression.
  12286. *
  12287. * @tsl
  12288. * @function
  12289. * @returns {ExpressionNode}
  12290. */
  12291. const Break = () => expression( 'break' ).toStack();
  12292. const _morphTextures = /*@__PURE__*/ new WeakMap();
  12293. const _morphVec4 = /*@__PURE__*/ new Vector4();
  12294. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  12295. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  12296. const y = texelIndex.div( width );
  12297. const x = texelIndex.sub( y.mul( width ) );
  12298. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  12299. return bufferAttrib.mul( influence );
  12300. } );
  12301. function getEntry( geometry ) {
  12302. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12303. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  12304. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  12305. // instead of using attributes, the WebGL 2 code path encodes morph targets
  12306. // into an array of data textures. Each layer represents a single morph target.
  12307. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12308. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12309. let entry = _morphTextures.get( geometry );
  12310. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  12311. if ( entry !== undefined ) entry.texture.dispose();
  12312. const morphTargets = geometry.morphAttributes.position || [];
  12313. const morphNormals = geometry.morphAttributes.normal || [];
  12314. const morphColors = geometry.morphAttributes.color || [];
  12315. let vertexDataCount = 0;
  12316. if ( hasMorphPosition === true ) vertexDataCount = 1;
  12317. if ( hasMorphNormals === true ) vertexDataCount = 2;
  12318. if ( hasMorphColors === true ) vertexDataCount = 3;
  12319. let width = geometry.attributes.position.count * vertexDataCount;
  12320. let height = 1;
  12321. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  12322. if ( width > maxTextureSize ) {
  12323. height = Math.ceil( width / maxTextureSize );
  12324. width = maxTextureSize;
  12325. }
  12326. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  12327. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  12328. bufferTexture.type = FloatType;
  12329. bufferTexture.needsUpdate = true;
  12330. // fill buffer
  12331. const vertexDataStride = vertexDataCount * 4;
  12332. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  12333. const morphTarget = morphTargets[ i ];
  12334. const morphNormal = morphNormals[ i ];
  12335. const morphColor = morphColors[ i ];
  12336. const offset = width * height * 4 * i;
  12337. for ( let j = 0; j < morphTarget.count; j ++ ) {
  12338. const stride = j * vertexDataStride;
  12339. if ( hasMorphPosition === true ) {
  12340. _morphVec4.fromBufferAttribute( morphTarget, j );
  12341. buffer[ offset + stride + 0 ] = _morphVec4.x;
  12342. buffer[ offset + stride + 1 ] = _morphVec4.y;
  12343. buffer[ offset + stride + 2 ] = _morphVec4.z;
  12344. buffer[ offset + stride + 3 ] = 0;
  12345. }
  12346. if ( hasMorphNormals === true ) {
  12347. _morphVec4.fromBufferAttribute( morphNormal, j );
  12348. buffer[ offset + stride + 4 ] = _morphVec4.x;
  12349. buffer[ offset + stride + 5 ] = _morphVec4.y;
  12350. buffer[ offset + stride + 6 ] = _morphVec4.z;
  12351. buffer[ offset + stride + 7 ] = 0;
  12352. }
  12353. if ( hasMorphColors === true ) {
  12354. _morphVec4.fromBufferAttribute( morphColor, j );
  12355. buffer[ offset + stride + 8 ] = _morphVec4.x;
  12356. buffer[ offset + stride + 9 ] = _morphVec4.y;
  12357. buffer[ offset + stride + 10 ] = _morphVec4.z;
  12358. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  12359. }
  12360. }
  12361. }
  12362. entry = {
  12363. count: morphTargetsCount,
  12364. texture: bufferTexture,
  12365. stride: vertexDataCount,
  12366. size: new Vector2( width, height )
  12367. };
  12368. _morphTextures.set( geometry, entry );
  12369. function disposeTexture() {
  12370. bufferTexture.dispose();
  12371. _morphTextures.delete( geometry );
  12372. geometry.removeEventListener( 'dispose', disposeTexture );
  12373. }
  12374. geometry.addEventListener( 'dispose', disposeTexture );
  12375. }
  12376. return entry;
  12377. }
  12378. /**
  12379. * This node implements the vertex transformation shader logic which is required
  12380. * for morph target animation.
  12381. *
  12382. * @augments Node
  12383. */
  12384. class MorphNode extends Node {
  12385. static get type() {
  12386. return 'MorphNode';
  12387. }
  12388. /**
  12389. * Constructs a new morph node.
  12390. *
  12391. * @param {Mesh} mesh - The mesh holding the morph targets.
  12392. */
  12393. constructor( mesh ) {
  12394. super( 'void' );
  12395. /**
  12396. * The mesh holding the morph targets.
  12397. *
  12398. * @type {Mesh}
  12399. */
  12400. this.mesh = mesh;
  12401. /**
  12402. * A uniform node which represents the morph base influence value.
  12403. *
  12404. * @type {UniformNode<float>}
  12405. */
  12406. this.morphBaseInfluence = uniform( 1 );
  12407. /**
  12408. * The update type overwritten since morph nodes are updated per object.
  12409. *
  12410. * @type {string}
  12411. */
  12412. this.updateType = NodeUpdateType.OBJECT;
  12413. }
  12414. /**
  12415. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  12416. *
  12417. * @param {NodeBuilder} builder - The current node builder.
  12418. */
  12419. setup( builder ) {
  12420. const { geometry } = builder;
  12421. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  12422. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  12423. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  12424. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  12425. // nodes
  12426. const { texture: bufferMap, stride, size } = getEntry( geometry );
  12427. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  12428. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  12429. const width = int( size.width );
  12430. Loop( morphTargetsCount, ( { i } ) => {
  12431. const influence = float( 0 ).toVar();
  12432. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  12433. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  12434. } else {
  12435. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  12436. }
  12437. If( influence.notEqual( 0 ), () => {
  12438. if ( hasMorphPosition === true ) {
  12439. positionLocal.addAssign( getMorph( {
  12440. bufferMap,
  12441. influence,
  12442. stride,
  12443. width,
  12444. depth: i,
  12445. offset: int( 0 )
  12446. } ) );
  12447. }
  12448. if ( hasMorphNormals === true ) {
  12449. normalLocal.addAssign( getMorph( {
  12450. bufferMap,
  12451. influence,
  12452. stride,
  12453. width,
  12454. depth: i,
  12455. offset: int( 1 )
  12456. } ) );
  12457. }
  12458. } );
  12459. } );
  12460. }
  12461. /**
  12462. * Updates the state of the morphed mesh by updating the base influence.
  12463. *
  12464. * @param {NodeFrame} frame - The current node frame.
  12465. */
  12466. update( /*frame*/ ) {
  12467. const morphBaseInfluence = this.morphBaseInfluence;
  12468. if ( this.mesh.geometry.morphTargetsRelative ) {
  12469. morphBaseInfluence.value = 1;
  12470. } else {
  12471. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  12472. }
  12473. }
  12474. }
  12475. /**
  12476. * TSL function for creating a morph node.
  12477. *
  12478. * @tsl
  12479. * @function
  12480. * @param {Mesh} mesh - The mesh holding the morph targets.
  12481. * @returns {MorphNode}
  12482. */
  12483. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  12484. /**
  12485. * Base class for lighting nodes.
  12486. *
  12487. * @augments Node
  12488. */
  12489. class LightingNode extends Node {
  12490. static get type() {
  12491. return 'LightingNode';
  12492. }
  12493. /**
  12494. * Constructs a new lighting node.
  12495. */
  12496. constructor() {
  12497. super( 'vec3' );
  12498. /**
  12499. * This flag can be used for type testing.
  12500. *
  12501. * @type {boolean}
  12502. * @readonly
  12503. * @default true
  12504. */
  12505. this.isLightingNode = true;
  12506. }
  12507. }
  12508. /**
  12509. * A generic class that can be used by nodes which contribute
  12510. * ambient occlusion to the scene. E.g. an ambient occlusion map
  12511. * node can be used as input for this module. Used in {@link NodeMaterial}.
  12512. *
  12513. * @augments LightingNode
  12514. */
  12515. class AONode extends LightingNode {
  12516. static get type() {
  12517. return 'AONode';
  12518. }
  12519. /**
  12520. * Constructs a new AO node.
  12521. *
  12522. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  12523. */
  12524. constructor( aoNode = null ) {
  12525. super();
  12526. /**
  12527. * The ambient occlusion node.
  12528. *
  12529. * @type {?Node<float>}
  12530. * @default null
  12531. */
  12532. this.aoNode = aoNode;
  12533. }
  12534. setup( builder ) {
  12535. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  12536. }
  12537. }
  12538. /**
  12539. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  12540. * by adding lighting specific context data. It represents the runtime context of
  12541. * {@link LightsNode}.
  12542. *
  12543. * @augments ContextNode
  12544. */
  12545. class LightingContextNode extends ContextNode {
  12546. static get type() {
  12547. return 'LightingContextNode';
  12548. }
  12549. /**
  12550. * Constructs a new lighting context node.
  12551. *
  12552. * @param {LightsNode} lightsNode - The lights node.
  12553. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  12554. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  12555. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  12556. */
  12557. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  12558. super( lightsNode );
  12559. /**
  12560. * The current lighting model.
  12561. *
  12562. * @type {?LightingModel}
  12563. * @default null
  12564. */
  12565. this.lightingModel = lightingModel;
  12566. /**
  12567. * A backdrop node.
  12568. *
  12569. * @type {?Node<vec3>}
  12570. * @default null
  12571. */
  12572. this.backdropNode = backdropNode;
  12573. /**
  12574. * A backdrop alpha node.
  12575. *
  12576. * @type {?Node<float>}
  12577. * @default null
  12578. */
  12579. this.backdropAlphaNode = backdropAlphaNode;
  12580. this._value = null;
  12581. }
  12582. /**
  12583. * Returns a lighting context object.
  12584. *
  12585. * @return {{
  12586. * radiance: Node<vec3>,
  12587. * irradiance: Node<vec3>,
  12588. * iblIrradiance: Node<vec3>,
  12589. * ambientOcclusion: Node<float>,
  12590. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  12591. * backdrop: Node<vec3>,
  12592. * backdropAlpha: Node<float>
  12593. * }} The lighting context object.
  12594. */
  12595. getContext() {
  12596. const { backdropNode, backdropAlphaNode } = this;
  12597. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  12598. directSpecular = vec3().toVar( 'directSpecular' ),
  12599. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  12600. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  12601. const reflectedLight = {
  12602. directDiffuse,
  12603. directSpecular,
  12604. indirectDiffuse,
  12605. indirectSpecular
  12606. };
  12607. const context = {
  12608. radiance: vec3().toVar( 'radiance' ),
  12609. irradiance: vec3().toVar( 'irradiance' ),
  12610. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  12611. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  12612. reflectedLight,
  12613. backdrop: backdropNode,
  12614. backdropAlpha: backdropAlphaNode
  12615. };
  12616. return context;
  12617. }
  12618. setup( builder ) {
  12619. this.value = this._value || ( this._value = this.getContext() );
  12620. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  12621. return super.setup( builder );
  12622. }
  12623. }
  12624. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  12625. /**
  12626. * A generic class that can be used by nodes which contribute
  12627. * irradiance to the scene. E.g. a light map node can be used
  12628. * as input for this module. Used in {@link NodeMaterial}.
  12629. *
  12630. * @augments LightingNode
  12631. */
  12632. class IrradianceNode extends LightingNode {
  12633. static get type() {
  12634. return 'IrradianceNode';
  12635. }
  12636. /**
  12637. * Constructs a new irradiance node.
  12638. *
  12639. * @param {Node<vec3>} node - A node contributing irradiance.
  12640. */
  12641. constructor( node ) {
  12642. super();
  12643. /**
  12644. * A node contributing irradiance.
  12645. *
  12646. * @type {Node<vec3>}
  12647. */
  12648. this.node = node;
  12649. }
  12650. setup( builder ) {
  12651. builder.context.irradiance.addAssign( this.node );
  12652. }
  12653. }
  12654. const _size$5 = /*@__PURE__*/ new Vector2();
  12655. /**
  12656. * A special type of texture node which represents the data of the current viewport
  12657. * as a texture. The module extracts data from the current bound framebuffer with
  12658. * a copy operation so no extra render pass is required to produce the texture data
  12659. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  12660. * variety of effects like refractive or transmissive materials.
  12661. *
  12662. * @augments TextureNode
  12663. */
  12664. class ViewportTextureNode extends TextureNode {
  12665. static get type() {
  12666. return 'ViewportTextureNode';
  12667. }
  12668. /**
  12669. * Constructs a new viewport texture node.
  12670. *
  12671. * @param {Node} [uvNode=screenUV] - The uv node.
  12672. * @param {?Node} [levelNode=null] - The level node.
  12673. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12674. */
  12675. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  12676. let defaultFramebuffer = null;
  12677. if ( framebufferTexture === null ) {
  12678. defaultFramebuffer = new FramebufferTexture();
  12679. defaultFramebuffer.minFilter = LinearMipmapLinearFilter;
  12680. framebufferTexture = defaultFramebuffer;
  12681. } else {
  12682. defaultFramebuffer = framebufferTexture;
  12683. }
  12684. super( framebufferTexture, uvNode, levelNode );
  12685. /**
  12686. * Whether to generate mipmaps or not.
  12687. *
  12688. * @type {boolean}
  12689. * @default false
  12690. */
  12691. this.generateMipmaps = false;
  12692. /**
  12693. * The reference framebuffer texture. This is used to store the framebuffer texture
  12694. * for the current render target. If the render target changes, a new framebuffer texture
  12695. * is created automatically.
  12696. *
  12697. * @type {FramebufferTexture}
  12698. * @default null
  12699. */
  12700. this.defaultFramebuffer = defaultFramebuffer;
  12701. /**
  12702. * This flag can be used for type testing.
  12703. *
  12704. * @type {boolean}
  12705. * @readonly
  12706. * @default true
  12707. */
  12708. this.isOutputTextureNode = true;
  12709. /**
  12710. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  12711. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  12712. *
  12713. * @type {string}
  12714. * @default 'frame'
  12715. */
  12716. this.updateBeforeType = NodeUpdateType.FRAME;
  12717. /**
  12718. * The framebuffer texture for the current renderer context.
  12719. *
  12720. * @type {WeakMap<RenderTarget, FramebufferTexture>}
  12721. * @private
  12722. */
  12723. this._cacheTextures = new WeakMap();
  12724. }
  12725. /**
  12726. * This methods returns a texture for the given render target reference.
  12727. *
  12728. * To avoid rendering errors, `ViewportTextureNode` must use unique framebuffer textures
  12729. * for different render contexts.
  12730. *
  12731. * @param {?RenderTarget} [reference=null] - The render target reference.
  12732. * @return {Texture} The framebuffer texture.
  12733. */
  12734. getTextureForReference( reference = null ) {
  12735. let defaultFramebuffer;
  12736. let cacheTextures;
  12737. if ( this.referenceNode ) {
  12738. defaultFramebuffer = this.referenceNode.defaultFramebuffer;
  12739. cacheTextures = this.referenceNode._cacheTextures;
  12740. } else {
  12741. defaultFramebuffer = this.defaultFramebuffer;
  12742. cacheTextures = this._cacheTextures;
  12743. }
  12744. if ( reference === null ) {
  12745. return defaultFramebuffer;
  12746. }
  12747. if ( cacheTextures.has( reference ) === false ) {
  12748. const framebufferTexture = defaultFramebuffer.clone();
  12749. cacheTextures.set( reference, framebufferTexture );
  12750. }
  12751. return cacheTextures.get( reference );
  12752. }
  12753. updateReference( frame ) {
  12754. const renderTarget = frame.renderer.getRenderTarget();
  12755. this.value = this.getTextureForReference( renderTarget );
  12756. return this.value;
  12757. }
  12758. updateBefore( frame ) {
  12759. const renderer = frame.renderer;
  12760. const renderTarget = renderer.getRenderTarget();
  12761. if ( renderTarget === null ) {
  12762. renderer.getDrawingBufferSize( _size$5 );
  12763. } else {
  12764. _size$5.set( renderTarget.width, renderTarget.height );
  12765. }
  12766. //
  12767. const framebufferTexture = this.getTextureForReference( renderTarget );
  12768. if ( framebufferTexture.image.width !== _size$5.width || framebufferTexture.image.height !== _size$5.height ) {
  12769. framebufferTexture.image.width = _size$5.width;
  12770. framebufferTexture.image.height = _size$5.height;
  12771. framebufferTexture.needsUpdate = true;
  12772. }
  12773. //
  12774. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  12775. framebufferTexture.generateMipmaps = this.generateMipmaps;
  12776. renderer.copyFramebufferToTexture( framebufferTexture );
  12777. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  12778. }
  12779. clone() {
  12780. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  12781. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  12782. return viewportTextureNode;
  12783. }
  12784. }
  12785. /**
  12786. * TSL function for creating a viewport texture node.
  12787. *
  12788. * @tsl
  12789. * @function
  12790. * @param {?Node} [uvNode=screenUV] - The uv node.
  12791. * @param {?Node} [levelNode=null] - The level node.
  12792. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12793. * @returns {ViewportTextureNode}
  12794. */
  12795. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  12796. /**
  12797. * TSL function for creating a viewport texture node with enabled mipmap generation.
  12798. *
  12799. * @tsl
  12800. * @function
  12801. * @param {?Node} [uvNode=screenUV] - The uv node.
  12802. * @param {?Node} [levelNode=null] - The level node.
  12803. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12804. * @returns {ViewportTextureNode}
  12805. */
  12806. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  12807. let _sharedDepthbuffer = null;
  12808. /**
  12809. * Represents the depth of the current viewport as a texture. This module
  12810. * can be used in combination with viewport texture to achieve effects
  12811. * that require depth evaluation.
  12812. *
  12813. * @augments ViewportTextureNode
  12814. */
  12815. class ViewportDepthTextureNode extends ViewportTextureNode {
  12816. static get type() {
  12817. return 'ViewportDepthTextureNode';
  12818. }
  12819. /**
  12820. * Constructs a new viewport depth texture node.
  12821. *
  12822. * @param {Node} [uvNode=screenUV] - The uv node.
  12823. * @param {?Node} [levelNode=null] - The level node.
  12824. */
  12825. constructor( uvNode = screenUV, levelNode = null ) {
  12826. if ( _sharedDepthbuffer === null ) {
  12827. _sharedDepthbuffer = new DepthTexture();
  12828. }
  12829. super( uvNode, levelNode, _sharedDepthbuffer );
  12830. }
  12831. /**
  12832. * Overwritten so the method always returns the unique shared
  12833. * depth texture.
  12834. *
  12835. * @return {DepthTexture} The shared depth texture.
  12836. */
  12837. getTextureForReference() {
  12838. return _sharedDepthbuffer;
  12839. }
  12840. }
  12841. /**
  12842. * TSL function for a viewport depth texture node.
  12843. *
  12844. * @tsl
  12845. * @function
  12846. * @param {?Node} [uvNode=screenUV] - The uv node.
  12847. * @param {?Node} [levelNode=null] - The level node.
  12848. * @returns {ViewportDepthTextureNode}
  12849. */
  12850. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  12851. /**
  12852. * This node offers a collection of features in context of the depth logic in the fragment shader.
  12853. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  12854. * fragment or for depth evaluation purposes.
  12855. *
  12856. * @augments Node
  12857. */
  12858. class ViewportDepthNode extends Node {
  12859. static get type() {
  12860. return 'ViewportDepthNode';
  12861. }
  12862. /**
  12863. * Constructs a new viewport depth node.
  12864. *
  12865. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  12866. * @param {?Node} [valueNode=null] - The value node.
  12867. */
  12868. constructor( scope, valueNode = null ) {
  12869. super( 'float' );
  12870. /**
  12871. * The node behaves differently depending on which scope is selected.
  12872. *
  12873. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  12874. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  12875. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  12876. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  12877. *
  12878. * @type {('depth'|'depthBase'|'linearDepth')}
  12879. */
  12880. this.scope = scope;
  12881. /**
  12882. * Can be used to define a custom depth value.
  12883. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  12884. *
  12885. * @type {?Node}
  12886. * @default null
  12887. */
  12888. this.valueNode = valueNode;
  12889. /**
  12890. * This flag can be used for type testing.
  12891. *
  12892. * @type {boolean}
  12893. * @readonly
  12894. * @default true
  12895. */
  12896. this.isViewportDepthNode = true;
  12897. }
  12898. generate( builder ) {
  12899. const { scope } = this;
  12900. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12901. return builder.getFragDepth();
  12902. }
  12903. return super.generate( builder );
  12904. }
  12905. setup( { camera } ) {
  12906. const { scope } = this;
  12907. const value = this.valueNode;
  12908. let node = null;
  12909. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12910. if ( value !== null ) {
  12911. node = depthBase().assign( value );
  12912. }
  12913. } else if ( scope === ViewportDepthNode.DEPTH ) {
  12914. if ( camera.isPerspectiveCamera ) {
  12915. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  12916. } else {
  12917. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12918. }
  12919. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  12920. if ( value !== null ) {
  12921. if ( camera.isPerspectiveCamera ) {
  12922. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  12923. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  12924. } else {
  12925. node = value;
  12926. }
  12927. } else {
  12928. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12929. }
  12930. }
  12931. return node;
  12932. }
  12933. }
  12934. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  12935. ViewportDepthNode.DEPTH = 'depth';
  12936. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  12937. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  12938. /**
  12939. * TSL function for converting a viewZ value to an orthographic depth value.
  12940. *
  12941. * @tsl
  12942. * @function
  12943. * @param {Node<float>} viewZ - The viewZ node.
  12944. * @param {Node<float>} near - The camera's near value.
  12945. * @param {Node<float>} far - The camera's far value.
  12946. * @returns {Node<float>}
  12947. */
  12948. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  12949. /**
  12950. * TSL function for converting an orthographic depth value to a viewZ value.
  12951. *
  12952. * @tsl
  12953. * @function
  12954. * @param {Node<float>} depth - The orthographic depth.
  12955. * @param {Node<float>} near - The camera's near value.
  12956. * @param {Node<float>} far - The camera's far value.
  12957. * @returns {Node<float>}
  12958. */
  12959. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  12960. /**
  12961. * TSL function for converting a viewZ value to a perspective depth value.
  12962. *
  12963. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  12964. *
  12965. * @tsl
  12966. * @function
  12967. * @param {Node<float>} viewZ - The viewZ node.
  12968. * @param {Node<float>} near - The camera's near value.
  12969. * @param {Node<float>} far - The camera's far value.
  12970. * @returns {Node<float>}
  12971. */
  12972. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  12973. /**
  12974. * TSL function for converting a perspective depth value to a viewZ value.
  12975. *
  12976. * @tsl
  12977. * @function
  12978. * @param {Node<float>} depth - The perspective depth.
  12979. * @param {Node<float>} near - The camera's near value.
  12980. * @param {Node<float>} far - The camera's far value.
  12981. * @returns {Node<float>}
  12982. */
  12983. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  12984. /**
  12985. * TSL function for converting a viewZ value to a logarithmic depth value.
  12986. *
  12987. * @tsl
  12988. * @function
  12989. * @param {Node<float>} viewZ - The viewZ node.
  12990. * @param {Node<float>} near - The camera's near value.
  12991. * @param {Node<float>} far - The camera's far value.
  12992. * @returns {Node<float>}
  12993. */
  12994. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  12995. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  12996. // The final logarithmic depth formula used here is adapted from one described in an
  12997. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  12998. // which was an improvement upon an earlier formula one described in an
  12999. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  13000. // Ulrich's formula is the following:
  13001. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  13002. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  13003. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  13004. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  13005. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  13006. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  13007. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  13008. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  13009. // be used, and ultimately Ulrich's "near plane" version was chosen.
  13010. // Outerra eventually made another improvement to their original "C-constant" variant,
  13011. // but it still does not incorporate the camera near plane (for this version,
  13012. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  13013. // Here we make 4 changes to Ulrich's formula:
  13014. // 1. Clamp the camera near plane so we don't divide by 0.
  13015. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  13016. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  13017. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  13018. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  13019. // so we do the same here, hence the 'viewZ.negate()' call.
  13020. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  13021. near = near.max( 1e-6 ).toVar();
  13022. const numerator = log2( viewZ.negate().div( near ) );
  13023. const denominator = log2( far.div( near ) );
  13024. return numerator.div( denominator );
  13025. };
  13026. /**
  13027. * TSL function for converting a logarithmic depth value to a viewZ value.
  13028. *
  13029. * @tsl
  13030. * @function
  13031. * @param {Node<float>} depth - The logarithmic depth.
  13032. * @param {Node<float>} near - The camera's near value.
  13033. * @param {Node<float>} far - The camera's far value.
  13034. * @returns {Node<float>}
  13035. */
  13036. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  13037. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  13038. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  13039. // a negative viewZ).
  13040. const exponent = depth.mul( log( far.div( near ) ) );
  13041. return float( Math.E ).pow( exponent ).mul( near ).negate();
  13042. };
  13043. /**
  13044. * TSL function for defining a value for the current fragment's depth.
  13045. *
  13046. * @tsl
  13047. * @function
  13048. * @param {Node<float>} value - The depth value to set.
  13049. * @returns {ViewportDepthNode<float>}
  13050. */
  13051. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  13052. /**
  13053. * TSL object that represents the depth value for the current fragment.
  13054. *
  13055. * @tsl
  13056. * @type {ViewportDepthNode}
  13057. */
  13058. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  13059. /**
  13060. * TSL function for converting a perspective depth value to linear depth.
  13061. *
  13062. * @tsl
  13063. * @function
  13064. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  13065. * @returns {ViewportDepthNode<float>}
  13066. */
  13067. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  13068. /**
  13069. * TSL object that represents the linear (orthographic) depth value of the current fragment
  13070. *
  13071. * @tsl
  13072. * @type {ViewportDepthNode}
  13073. */
  13074. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  13075. depth.assign = ( value ) => depthBase( value );
  13076. /**
  13077. * This node is used in {@link NodeMaterial} to setup the clipping
  13078. * which can happen hardware-accelerated (if supported) and optionally
  13079. * use alpha-to-coverage for anti-aliasing clipped edges.
  13080. *
  13081. * @augments Node
  13082. */
  13083. class ClippingNode extends Node {
  13084. static get type() {
  13085. return 'ClippingNode';
  13086. }
  13087. /**
  13088. * Constructs a new clipping node.
  13089. *
  13090. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  13091. * the selected scope influences the behavior of the node and what type of code is generated.
  13092. */
  13093. constructor( scope = ClippingNode.DEFAULT ) {
  13094. super();
  13095. /**
  13096. * The node's scope. Similar to other nodes, the selected scope influences
  13097. * the behavior of the node and what type of code is generated.
  13098. *
  13099. * @type {('default'|'hardware'|'alphaToCoverage')}
  13100. */
  13101. this.scope = scope;
  13102. }
  13103. /**
  13104. * Setups the node depending on the selected scope.
  13105. *
  13106. * @param {NodeBuilder} builder - The current node builder.
  13107. * @return {Node} The result node.
  13108. */
  13109. setup( builder ) {
  13110. super.setup( builder );
  13111. const clippingContext = builder.clippingContext;
  13112. const { intersectionPlanes, unionPlanes } = clippingContext;
  13113. this.hardwareClipping = builder.material.hardwareClipping;
  13114. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  13115. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  13116. } else if ( this.scope === ClippingNode.HARDWARE ) {
  13117. return this.setupHardwareClipping( unionPlanes, builder );
  13118. } else {
  13119. return this.setupDefault( intersectionPlanes, unionPlanes );
  13120. }
  13121. }
  13122. /**
  13123. * Setups alpha to coverage.
  13124. *
  13125. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13126. * @param {Array<Vector4>} unionPlanes - The union planes.
  13127. * @return {Node} The result node.
  13128. */
  13129. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  13130. return Fn( () => {
  13131. const distanceToPlane = float().toVar( 'distanceToPlane' );
  13132. const distanceGradient = float().toVar( 'distanceToGradient' );
  13133. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  13134. const numUnionPlanes = unionPlanes.length;
  13135. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13136. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13137. Loop( numUnionPlanes, ( { i } ) => {
  13138. const plane = clippingPlanes.element( i );
  13139. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13140. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13141. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  13142. } );
  13143. }
  13144. const numIntersectionPlanes = intersectionPlanes.length;
  13145. if ( numIntersectionPlanes > 0 ) {
  13146. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13147. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  13148. Loop( numIntersectionPlanes, ( { i } ) => {
  13149. const plane = clippingPlanes.element( i );
  13150. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  13151. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  13152. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  13153. } );
  13154. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  13155. }
  13156. diffuseColor.a.mulAssign( clipOpacity );
  13157. diffuseColor.a.equal( 0.0 ).discard();
  13158. } )();
  13159. }
  13160. /**
  13161. * Setups the default clipping.
  13162. *
  13163. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  13164. * @param {Array<Vector4>} unionPlanes - The union planes.
  13165. * @return {Node} The result node.
  13166. */
  13167. setupDefault( intersectionPlanes, unionPlanes ) {
  13168. return Fn( () => {
  13169. const numUnionPlanes = unionPlanes.length;
  13170. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  13171. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13172. Loop( numUnionPlanes, ( { i } ) => {
  13173. const plane = clippingPlanes.element( i );
  13174. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  13175. } );
  13176. }
  13177. const numIntersectionPlanes = intersectionPlanes.length;
  13178. if ( numIntersectionPlanes > 0 ) {
  13179. const clippingPlanes = uniformArray( intersectionPlanes ).setGroup( renderGroup );
  13180. const clipped = bool( true ).toVar( 'clipped' );
  13181. Loop( numIntersectionPlanes, ( { i } ) => {
  13182. const plane = clippingPlanes.element( i );
  13183. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  13184. } );
  13185. clipped.discard();
  13186. }
  13187. } )();
  13188. }
  13189. /**
  13190. * Setups hardware clipping.
  13191. *
  13192. * @param {Array<Vector4>} unionPlanes - The union planes.
  13193. * @param {NodeBuilder} builder - The current node builder.
  13194. * @return {Node} The result node.
  13195. */
  13196. setupHardwareClipping( unionPlanes, builder ) {
  13197. const numUnionPlanes = unionPlanes.length;
  13198. builder.enableHardwareClipping( numUnionPlanes );
  13199. return Fn( () => {
  13200. const clippingPlanes = uniformArray( unionPlanes ).setGroup( renderGroup );
  13201. const hw_clip_distances = builtin( builder.getClipDistance() );
  13202. Loop( numUnionPlanes, ( { i } ) => {
  13203. const plane = clippingPlanes.element( i );
  13204. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  13205. hw_clip_distances.element( i ).assign( distance );
  13206. } );
  13207. } )();
  13208. }
  13209. }
  13210. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  13211. ClippingNode.DEFAULT = 'default';
  13212. ClippingNode.HARDWARE = 'hardware';
  13213. /**
  13214. * TSL function for setting up the default clipping logic.
  13215. *
  13216. * @tsl
  13217. * @function
  13218. * @returns {ClippingNode}
  13219. */
  13220. const clipping = () => nodeObject( new ClippingNode() );
  13221. /**
  13222. * TSL function for setting up alpha to coverage.
  13223. *
  13224. * @tsl
  13225. * @function
  13226. * @returns {ClippingNode}
  13227. */
  13228. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  13229. /**
  13230. * TSL function for setting up hardware-based clipping.
  13231. *
  13232. * @tsl
  13233. * @function
  13234. * @returns {ClippingNode}
  13235. */
  13236. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  13237. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  13238. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  13239. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13240. 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 ) ) ) ) ) );
  13241. } );
  13242. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  13243. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  13244. } );
  13245. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  13246. // Find the discretized derivatives of our coordinates
  13247. const maxDeriv = max$1(
  13248. length( dFdx( position.xyz ) ),
  13249. length( dFdy( position.xyz ) )
  13250. );
  13251. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  13252. // Find two nearest log-discretized noise scales
  13253. const pixScales = vec2(
  13254. exp2( floor( log2( pixScale ) ) ),
  13255. exp2( ceil( log2( pixScale ) ) )
  13256. );
  13257. // Compute alpha thresholds at our two noise scales
  13258. const alpha = vec2(
  13259. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  13260. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  13261. );
  13262. // Factor to interpolate lerp with
  13263. const lerpFactor = fract( log2( pixScale ) );
  13264. // Interpolate alpha threshold from noise at two scales
  13265. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  13266. // Pass into CDF to compute uniformly distrib threshold
  13267. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  13268. const cases = vec3(
  13269. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  13270. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  13271. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  13272. // Find our final, uniformly distributed alpha threshold (ατ)
  13273. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  13274. // Avoids ατ == 0. Could also do ατ =1-ατ
  13275. return clamp( threshold, 1.0e-6, 1.0 );
  13276. } ).setLayout( {
  13277. name: 'getAlphaHashThreshold',
  13278. type: 'float',
  13279. inputs: [
  13280. { name: 'position', type: 'vec3' }
  13281. ]
  13282. } );
  13283. /**
  13284. * An attribute node for representing vertex colors.
  13285. *
  13286. * @augments AttributeNode
  13287. */
  13288. class VertexColorNode extends AttributeNode {
  13289. static get type() {
  13290. return 'VertexColorNode';
  13291. }
  13292. /**
  13293. * Constructs a new vertex color node.
  13294. *
  13295. * @param {number} index - The attribute index.
  13296. */
  13297. constructor( index ) {
  13298. super( null, 'vec4' );
  13299. /**
  13300. * This flag can be used for type testing.
  13301. *
  13302. * @type {boolean}
  13303. * @readonly
  13304. * @default true
  13305. */
  13306. this.isVertexColorNode = true;
  13307. /**
  13308. * The attribute index to enable more than one sets of vertex colors.
  13309. *
  13310. * @type {number}
  13311. * @default 0
  13312. */
  13313. this.index = index;
  13314. }
  13315. /**
  13316. * Overwrites the default implementation by honoring the attribute index.
  13317. *
  13318. * @param {NodeBuilder} builder - The current node builder.
  13319. * @return {string} The attribute name.
  13320. */
  13321. getAttributeName( /*builder*/ ) {
  13322. const index = this.index;
  13323. return 'color' + ( index > 0 ? index : '' );
  13324. }
  13325. generate( builder ) {
  13326. const attributeName = this.getAttributeName( builder );
  13327. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  13328. let result;
  13329. if ( geometryAttribute === true ) {
  13330. result = super.generate( builder );
  13331. } else {
  13332. // Vertex color fallback should be white
  13333. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  13334. }
  13335. return result;
  13336. }
  13337. serialize( data ) {
  13338. super.serialize( data );
  13339. data.index = this.index;
  13340. }
  13341. deserialize( data ) {
  13342. super.deserialize( data );
  13343. this.index = data.index;
  13344. }
  13345. }
  13346. /**
  13347. * TSL function for creating a reference node.
  13348. *
  13349. * @tsl
  13350. * @function
  13351. * @param {number} [index=0] - The attribute index.
  13352. * @returns {VertexColorNode}
  13353. */
  13354. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  13355. /**
  13356. * Represents a "Color Burn" blend mode.
  13357. *
  13358. * It's designed to darken the base layer's colors based on the color of the blend layer.
  13359. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  13360. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  13361. *
  13362. * @tsl
  13363. * @function
  13364. * @param {Node<vec3>} base - The base color.
  13365. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  13366. * @return {Node<vec3>} The result.
  13367. */
  13368. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13369. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  13370. } ).setLayout( {
  13371. name: 'blendBurn',
  13372. type: 'vec3',
  13373. inputs: [
  13374. { name: 'base', type: 'vec3' },
  13375. { name: 'blend', type: 'vec3' }
  13376. ]
  13377. } );
  13378. /**
  13379. * Represents a "Color Dodge" blend mode.
  13380. *
  13381. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  13382. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  13383. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  13384. *
  13385. * @tsl
  13386. * @function
  13387. * @param {Node<vec3>} base - The base color.
  13388. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13389. * @return {Node<vec3>} The result.
  13390. */
  13391. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13392. return min$1( base.div( blend.oneMinus() ), 1.0 );
  13393. } ).setLayout( {
  13394. name: 'blendDodge',
  13395. type: 'vec3',
  13396. inputs: [
  13397. { name: 'base', type: 'vec3' },
  13398. { name: 'blend', type: 'vec3' }
  13399. ]
  13400. } );
  13401. /**
  13402. * Represents a "Screen" blend mode.
  13403. *
  13404. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  13405. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  13406. * effects.
  13407. *
  13408. * @tsl
  13409. * @function
  13410. * @param {Node<vec3>} base - The base color.
  13411. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  13412. * @return {Node<vec3>} The result.
  13413. */
  13414. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13415. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  13416. } ).setLayout( {
  13417. name: 'blendScreen',
  13418. type: 'vec3',
  13419. inputs: [
  13420. { name: 'base', type: 'vec3' },
  13421. { name: 'blend', type: 'vec3' }
  13422. ]
  13423. } );
  13424. /**
  13425. * Represents a "Overlay" blend mode.
  13426. *
  13427. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  13428. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  13429. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  13430. *
  13431. * @tsl
  13432. * @function
  13433. * @param {Node<vec3>} base - The base color.
  13434. * @param {Node<vec3>} blend - The blend color
  13435. * @return {Node<vec3>} The result.
  13436. */
  13437. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13438. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  13439. } ).setLayout( {
  13440. name: 'blendOverlay',
  13441. type: 'vec3',
  13442. inputs: [
  13443. { name: 'base', type: 'vec3' },
  13444. { name: 'blend', type: 'vec3' }
  13445. ]
  13446. } );
  13447. /**
  13448. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  13449. * It assumes both input colors have non-premultiplied alpha.
  13450. *
  13451. * @tsl
  13452. * @function
  13453. * @param {Node<vec4>} base - The base color.
  13454. * @param {Node<vec4>} blend - The blend color
  13455. * @return {Node<vec4>} The result.
  13456. */
  13457. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  13458. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  13459. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  13460. } ).setLayout( {
  13461. name: 'blendColor',
  13462. type: 'vec4',
  13463. inputs: [
  13464. { name: 'base', type: 'vec4' },
  13465. { name: 'blend', type: 'vec4' }
  13466. ]
  13467. } );
  13468. /**
  13469. * Premultiplies the RGB channels of a color by its alpha channel.
  13470. *
  13471. * This function is useful for converting a non-premultiplied alpha color
  13472. * into a premultiplied alpha format, where the RGB values are scaled
  13473. * by the alpha value. Premultiplied alpha is often used in graphics
  13474. * rendering for certain operations, such as compositing and image processing.
  13475. *
  13476. * @tsl
  13477. * @function
  13478. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  13479. * @return {Node<vec4>} The color with premultiplied alpha.
  13480. */
  13481. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13482. return vec4( color.rgb.mul( color.a ), color.a );
  13483. }, { color: 'vec4', return: 'vec4' } );
  13484. /**
  13485. * Unpremultiplies the RGB channels of a color by its alpha channel.
  13486. *
  13487. * This function is useful for converting a premultiplied alpha color
  13488. * back into a non-premultiplied alpha format, where the RGB values are
  13489. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  13490. * rendering for certain operations, such as compositing and image processing.
  13491. *
  13492. * @tsl
  13493. * @function
  13494. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  13495. * @return {Node<vec4>} The color with non-premultiplied alpha.
  13496. */
  13497. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  13498. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  13499. return vec4( color.rgb.div( color.a ), color.a );
  13500. }, { color: 'vec4', return: 'vec4' } );
  13501. // Deprecated
  13502. /**
  13503. * @tsl
  13504. * @function
  13505. * @deprecated since r171. Use {@link blendBurn} instead.
  13506. *
  13507. * @param {...any} params
  13508. * @returns {Function}
  13509. */
  13510. const burn = ( ...params ) => { // @deprecated, r171
  13511. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  13512. return blendBurn( params );
  13513. };
  13514. /**
  13515. * @tsl
  13516. * @function
  13517. * @deprecated since r171. Use {@link blendDodge} instead.
  13518. *
  13519. * @param {...any} params
  13520. * @returns {Function}
  13521. */
  13522. const dodge = ( ...params ) => { // @deprecated, r171
  13523. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  13524. return blendDodge( params );
  13525. };
  13526. /**
  13527. * @tsl
  13528. * @function
  13529. * @deprecated since r171. Use {@link blendScreen} instead.
  13530. *
  13531. * @param {...any} params
  13532. * @returns {Function}
  13533. */
  13534. const screen = ( ...params ) => { // @deprecated, r171
  13535. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  13536. return blendScreen( params );
  13537. };
  13538. /**
  13539. * @tsl
  13540. * @function
  13541. * @deprecated since r171. Use {@link blendOverlay} instead.
  13542. *
  13543. * @param {...any} params
  13544. * @returns {Function}
  13545. */
  13546. const overlay = ( ...params ) => { // @deprecated, r171
  13547. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  13548. return blendOverlay( params );
  13549. };
  13550. /**
  13551. * Base class for all node materials.
  13552. *
  13553. * @augments Material
  13554. */
  13555. class NodeMaterial extends Material {
  13556. static get type() {
  13557. return 'NodeMaterial';
  13558. }
  13559. /**
  13560. * Represents the type of the node material.
  13561. *
  13562. * @type {string}
  13563. */
  13564. get type() {
  13565. return this.constructor.type;
  13566. }
  13567. set type( _value ) { /* */ }
  13568. /**
  13569. * Constructs a new node material.
  13570. */
  13571. constructor() {
  13572. super();
  13573. /**
  13574. * This flag can be used for type testing.
  13575. *
  13576. * @type {boolean}
  13577. * @readonly
  13578. * @default true
  13579. */
  13580. this.isNodeMaterial = true;
  13581. /**
  13582. * Whether this material is affected by fog or not.
  13583. *
  13584. * @type {boolean}
  13585. * @default true
  13586. */
  13587. this.fog = true;
  13588. /**
  13589. * Whether this material is affected by lights or not.
  13590. *
  13591. * @type {boolean}
  13592. * @default false
  13593. */
  13594. this.lights = false;
  13595. /**
  13596. * Whether this material uses hardware clipping or not.
  13597. * This property is managed by the engine and should not be
  13598. * modified by apps.
  13599. *
  13600. * @type {boolean}
  13601. * @default false
  13602. */
  13603. this.hardwareClipping = false;
  13604. /**
  13605. * Node materials which set their `lights` property to `true`
  13606. * are affected by all lights of the scene. Sometimes selective
  13607. * lighting is wanted which means only _some_ lights in the scene
  13608. * affect a material. This can be achieved by creating an instance
  13609. * of {@link LightsNode} with a list of selective
  13610. * lights and assign the node to this property.
  13611. *
  13612. * ```js
  13613. * const customLightsNode = lights( [ light1, light2 ] );
  13614. * material.lightsNode = customLightsNode;
  13615. * ```
  13616. *
  13617. * @type {?LightsNode}
  13618. * @default null
  13619. */
  13620. this.lightsNode = null;
  13621. /**
  13622. * The environment of node materials can be defined by an environment
  13623. * map assigned to the `envMap` property or by `Scene.environment`
  13624. * if the node material is a PBR material. This node property allows to overwrite
  13625. * the default behavior and define the environment with a custom node.
  13626. *
  13627. * ```js
  13628. * material.envNode = pmremTexture( renderTarget.texture );
  13629. * ```
  13630. *
  13631. * @type {?Node<vec3>}
  13632. * @default null
  13633. */
  13634. this.envNode = null;
  13635. /**
  13636. * The lighting of node materials might be influenced by ambient occlusion.
  13637. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  13638. * and the respective `aoMapIntensity`. This node property allows to overwrite
  13639. * the default and define the ambient occlusion with a custom node instead.
  13640. *
  13641. * If you don't want to overwrite the diffuse color but modify the existing
  13642. * values instead, use {@link materialAO}.
  13643. *
  13644. * @type {?Node<float>}
  13645. * @default null
  13646. */
  13647. this.aoNode = null;
  13648. /**
  13649. * The diffuse color of node materials is by default inferred from the
  13650. * `color` and `map` properties. This node property allows to overwrite the default
  13651. * and define the diffuse color with a node instead.
  13652. *
  13653. * ```js
  13654. * material.colorNode = color( 0xff0000 ); // define red color
  13655. * ```
  13656. *
  13657. * If you don't want to overwrite the diffuse color but modify the existing
  13658. * values instead, use {@link materialColor}.
  13659. *
  13660. * ```js
  13661. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  13662. * ```
  13663. *
  13664. * @type {?Node<vec3>}
  13665. * @default null
  13666. */
  13667. this.colorNode = null;
  13668. /**
  13669. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  13670. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  13671. * and define the normals with a node instead.
  13672. *
  13673. * If you don't want to overwrite the normals but modify the existing values instead,
  13674. * use {@link materialNormal}.
  13675. *
  13676. * @type {?Node<vec3>}
  13677. * @default null
  13678. */
  13679. this.normalNode = null;
  13680. /**
  13681. * The opacity of node materials is by default inferred from the `opacity`
  13682. * and `alphaMap` properties. This node property allows to overwrite the default
  13683. * and define the opacity with a node instead.
  13684. *
  13685. * If you don't want to overwrite the normals but modify the existing
  13686. * value instead, use {@link materialOpacity}.
  13687. *
  13688. * @type {?Node<float>}
  13689. * @default null
  13690. */
  13691. this.opacityNode = null;
  13692. /**
  13693. * This node can be used to implement a variety of filter-like effects. The idea is
  13694. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  13695. * to create an arbitrary effect and then assign the node composition to this property.
  13696. * Everything behind the object using this material will now be affected by a filter.
  13697. *
  13698. * ```js
  13699. * const material = new NodeMaterial()
  13700. * material.transparent = true;
  13701. *
  13702. * // everything behind the object will be monochromatic
  13703. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  13704. * ```
  13705. *
  13706. * Backdrop computations are part of the lighting so only lit materials can use this property.
  13707. *
  13708. * @type {?Node<vec3>}
  13709. * @default null
  13710. */
  13711. this.backdropNode = null;
  13712. /**
  13713. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  13714. *
  13715. * @type {?Node<float>}
  13716. * @default null
  13717. */
  13718. this.backdropAlphaNode = null;
  13719. /**
  13720. * The alpha test of node materials is by default inferred from the `alphaTest`
  13721. * property. This node property allows to overwrite the default and define the
  13722. * alpha test with a node instead.
  13723. *
  13724. * If you don't want to overwrite the alpha test but modify the existing
  13725. * value instead, use {@link materialAlphaTest}.
  13726. *
  13727. * @type {?Node<float>}
  13728. * @default null
  13729. */
  13730. this.alphaTestNode = null;
  13731. /**
  13732. * Discards the fragment if the mask value is `false`.
  13733. *
  13734. * @type {?Node<bool>}
  13735. * @default null
  13736. */
  13737. this.maskNode = null;
  13738. /**
  13739. * The local vertex positions are computed based on multiple factors like the
  13740. * attribute data, morphing or skinning. This node property allows to overwrite
  13741. * the default and define local vertex positions with nodes instead.
  13742. *
  13743. * If you don't want to overwrite the vertex positions but modify the existing
  13744. * values instead, use {@link positionLocal}.
  13745. *
  13746. *```js
  13747. * material.positionNode = positionLocal.add( displace );
  13748. * ```
  13749. *
  13750. * @type {?Node<vec3>}
  13751. * @default null
  13752. */
  13753. this.positionNode = null;
  13754. /**
  13755. * This node property is intended for logic which modifies geometry data once or per animation step.
  13756. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  13757. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  13758. * can be implemented.
  13759. *
  13760. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  13761. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  13762. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  13763. * eventually assigned to `geometryNode`.
  13764. *
  13765. * @type {?Function}
  13766. * @default null
  13767. */
  13768. this.geometryNode = null;
  13769. /**
  13770. * Allows to overwrite depth values in the fragment shader.
  13771. *
  13772. * @type {?Node<float>}
  13773. * @default null
  13774. */
  13775. this.depthNode = null;
  13776. /**
  13777. * Allows to overwrite the position used for shadow map rendering which
  13778. * is by default {@link positionWorld}, the vertex position
  13779. * in world space.
  13780. *
  13781. * @type {?Node<float>}
  13782. * @default null
  13783. */
  13784. this.receivedShadowPositionNode = null;
  13785. /**
  13786. * Allows to overwrite the geometry position used for shadow map projection which
  13787. * is by default {@link positionLocal}, the vertex position in local space.
  13788. *
  13789. * @type {?Node<float>}
  13790. * @default null
  13791. */
  13792. this.castShadowPositionNode = null;
  13793. /**
  13794. * This node can be used to influence how an object using this node material
  13795. * receive shadows.
  13796. *
  13797. * ```js
  13798. * const totalShadows = float( 1 ).toVar();
  13799. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  13800. * totalShadows.mulAssign( shadow );
  13801. * //return float( 1 ); // bypass received shadows
  13802. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  13803. * } );
  13804. *
  13805. * @type {?(Function|FunctionNode<vec4>)}
  13806. * @default null
  13807. */
  13808. this.receivedShadowNode = null;
  13809. /**
  13810. * This node can be used to influence how an object using this node material
  13811. * casts shadows. To apply a color to shadows, you can simply do:
  13812. *
  13813. * ```js
  13814. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  13815. * ```
  13816. *
  13817. * Which can be nice to fake colored shadows of semi-transparent objects. It
  13818. * is also common to use the property with `Fn` function so checks are performed
  13819. * per fragment.
  13820. *
  13821. * ```js
  13822. * materialCustomShadow.castShadowNode = Fn( () => {
  13823. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  13824. * return materialColor;
  13825. * } )();
  13826. * ```
  13827. *
  13828. * @type {?Node<vec4>}
  13829. * @default null
  13830. */
  13831. this.castShadowNode = null;
  13832. /**
  13833. * This node can be used to define the final output of the material.
  13834. *
  13835. * TODO: Explain the differences to `fragmentNode`.
  13836. *
  13837. * @type {?Node<vec4>}
  13838. * @default null
  13839. */
  13840. this.outputNode = null;
  13841. /**
  13842. * MRT configuration is done on renderer or pass level. This node allows to
  13843. * overwrite what values are written into MRT targets on material level. This
  13844. * can be useful for implementing selective FX features that should only affect
  13845. * specific objects.
  13846. *
  13847. * @type {?MRTNode}
  13848. * @default null
  13849. */
  13850. this.mrtNode = null;
  13851. /**
  13852. * This node property can be used if you need complete freedom in implementing
  13853. * the fragment shader. Assigning a node will replace the built-in material
  13854. * logic used in the fragment stage.
  13855. *
  13856. * @type {?Node<vec4>}
  13857. * @default null
  13858. */
  13859. this.fragmentNode = null;
  13860. /**
  13861. * This node property can be used if you need complete freedom in implementing
  13862. * the vertex shader. Assigning a node will replace the built-in material logic
  13863. * used in the vertex stage.
  13864. *
  13865. * @type {?Node<vec4>}
  13866. * @default null
  13867. */
  13868. this.vertexNode = null;
  13869. // Deprecated properties
  13870. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  13871. get: () => {
  13872. return this.receivedShadowPositionNode;
  13873. },
  13874. set: ( value ) => {
  13875. console.warn( 'THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  13876. this.receivedShadowPositionNode = value;
  13877. }
  13878. } );
  13879. }
  13880. /**
  13881. * Allows to define a custom cache key that influence the material key computation
  13882. * for render objects.
  13883. *
  13884. * @return {string} The custom cache key.
  13885. */
  13886. customProgramCacheKey() {
  13887. return this.type + getCacheKey$1( this );
  13888. }
  13889. /**
  13890. * Builds this material with the given node builder.
  13891. *
  13892. * @param {NodeBuilder} builder - The current node builder.
  13893. */
  13894. build( builder ) {
  13895. this.setup( builder );
  13896. }
  13897. /**
  13898. * Setups a node material observer with the given builder.
  13899. *
  13900. * @param {NodeBuilder} builder - The current node builder.
  13901. * @return {NodeMaterialObserver} The node material observer.
  13902. */
  13903. setupObserver( builder ) {
  13904. return new NodeMaterialObserver( builder );
  13905. }
  13906. /**
  13907. * Setups the vertex and fragment stage of this node material.
  13908. *
  13909. * @param {NodeBuilder} builder - The current node builder.
  13910. */
  13911. setup( builder ) {
  13912. builder.context.setupNormal = () => subBuild( this.setupNormal( builder ), 'NORMAL', 'vec3' );
  13913. builder.context.setupPositionView = () => this.setupPositionView( builder );
  13914. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  13915. const renderer = builder.renderer;
  13916. const renderTarget = renderer.getRenderTarget();
  13917. // < VERTEX STAGE >
  13918. builder.addStack();
  13919. const mvp = subBuild( this.setupVertex( builder ), 'VERTEX' );
  13920. const vertexNode = this.vertexNode || mvp;
  13921. builder.stack.outputNode = vertexNode;
  13922. this.setupHardwareClipping( builder );
  13923. if ( this.geometryNode !== null ) {
  13924. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  13925. }
  13926. builder.addFlow( 'vertex', builder.removeStack() );
  13927. // < FRAGMENT STAGE >
  13928. builder.addStack();
  13929. let resultNode;
  13930. const clippingNode = this.setupClipping( builder );
  13931. if ( this.depthWrite === true || this.depthTest === true ) {
  13932. // only write depth if depth buffer is configured
  13933. if ( renderTarget !== null ) {
  13934. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  13935. } else {
  13936. if ( renderer.depth === true ) this.setupDepth( builder );
  13937. }
  13938. }
  13939. if ( this.fragmentNode === null ) {
  13940. this.setupDiffuseColor( builder );
  13941. this.setupVariants( builder );
  13942. const outgoingLightNode = this.setupLighting( builder );
  13943. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  13944. // force unsigned floats - useful for RenderTargets
  13945. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  13946. resultNode = this.setupOutput( builder, basicOutput );
  13947. // OUTPUT NODE
  13948. output.assign( resultNode );
  13949. //
  13950. const isCustomOutput = this.outputNode !== null;
  13951. if ( isCustomOutput ) resultNode = this.outputNode;
  13952. // MRT
  13953. if ( renderTarget !== null ) {
  13954. const mrt = renderer.getMRT();
  13955. const materialMRT = this.mrtNode;
  13956. if ( mrt !== null ) {
  13957. if ( isCustomOutput ) output.assign( resultNode );
  13958. resultNode = mrt;
  13959. if ( materialMRT !== null ) {
  13960. resultNode = mrt.merge( materialMRT );
  13961. }
  13962. } else if ( materialMRT !== null ) {
  13963. resultNode = materialMRT;
  13964. }
  13965. }
  13966. } else {
  13967. let fragmentNode = this.fragmentNode;
  13968. if ( fragmentNode.isOutputStructNode !== true ) {
  13969. fragmentNode = vec4( fragmentNode );
  13970. }
  13971. resultNode = this.setupOutput( builder, fragmentNode );
  13972. }
  13973. builder.stack.outputNode = resultNode;
  13974. builder.addFlow( 'fragment', builder.removeStack() );
  13975. // < OBSERVER >
  13976. builder.observer = this.setupObserver( builder );
  13977. }
  13978. /**
  13979. * Setups the clipping node.
  13980. *
  13981. * @param {NodeBuilder} builder - The current node builder.
  13982. * @return {ClippingNode} The clipping node.
  13983. */
  13984. setupClipping( builder ) {
  13985. if ( builder.clippingContext === null ) return null;
  13986. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  13987. let result = null;
  13988. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  13989. const samples = builder.renderer.samples;
  13990. if ( this.alphaToCoverage && samples > 1 ) {
  13991. // to be added to flow when the color/alpha value has been determined
  13992. result = clippingAlpha();
  13993. } else {
  13994. builder.stack.add( clipping() );
  13995. }
  13996. }
  13997. return result;
  13998. }
  13999. /**
  14000. * Setups the hardware clipping if available on the current device.
  14001. *
  14002. * @param {NodeBuilder} builder - The current node builder.
  14003. */
  14004. setupHardwareClipping( builder ) {
  14005. this.hardwareClipping = false;
  14006. if ( builder.clippingContext === null ) return;
  14007. const candidateCount = builder.clippingContext.unionPlanes.length;
  14008. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  14009. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  14010. builder.stack.add( hardwareClipping() );
  14011. this.hardwareClipping = true;
  14012. }
  14013. return;
  14014. }
  14015. /**
  14016. * Setups the depth of this material.
  14017. *
  14018. * @param {NodeBuilder} builder - The current node builder.
  14019. */
  14020. setupDepth( builder ) {
  14021. const { renderer, camera } = builder;
  14022. // Depth
  14023. let depthNode = this.depthNode;
  14024. if ( depthNode === null ) {
  14025. const mrt = renderer.getMRT();
  14026. if ( mrt && mrt.has( 'depth' ) ) {
  14027. depthNode = mrt.get( 'depth' );
  14028. } else if ( renderer.logarithmicDepthBuffer === true ) {
  14029. if ( camera.isPerspectiveCamera ) {
  14030. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  14031. } else {
  14032. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  14033. }
  14034. }
  14035. }
  14036. if ( depthNode !== null ) {
  14037. depth.assign( depthNode ).toStack();
  14038. }
  14039. }
  14040. /**
  14041. * Setups the position node in view space. This method exists
  14042. * so derived node materials can modify the implementation e.g. sprite materials.
  14043. *
  14044. * @param {NodeBuilder} builder - The current node builder.
  14045. * @return {Node<vec3>} The position in view space.
  14046. */
  14047. setupPositionView( /*builder*/ ) {
  14048. return modelViewMatrix.mul( positionLocal ).xyz;
  14049. }
  14050. /**
  14051. * Setups the position in clip space.
  14052. *
  14053. * @param {NodeBuilder} builder - The current node builder.
  14054. * @return {Node<vec4>} The position in view space.
  14055. */
  14056. setupModelViewProjection( /*builder*/ ) {
  14057. return cameraProjectionMatrix.mul( positionView );
  14058. }
  14059. /**
  14060. * Setups the logic for the vertex stage.
  14061. *
  14062. * @param {NodeBuilder} builder - The current node builder.
  14063. * @return {Node<vec4>} The position in clip space.
  14064. */
  14065. setupVertex( builder ) {
  14066. builder.addStack();
  14067. this.setupPosition( builder );
  14068. builder.context.vertex = builder.removeStack();
  14069. return modelViewProjection;
  14070. }
  14071. /**
  14072. * Setups the computation of the position in local space.
  14073. *
  14074. * @param {NodeBuilder} builder - The current node builder.
  14075. * @return {Node<vec3>} The position in local space.
  14076. */
  14077. setupPosition( builder ) {
  14078. const { object, geometry } = builder;
  14079. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  14080. morphReference( object ).toStack();
  14081. }
  14082. if ( object.isSkinnedMesh === true ) {
  14083. skinning( object ).toStack();
  14084. }
  14085. if ( this.displacementMap ) {
  14086. const displacementMap = materialReference( 'displacementMap', 'texture' );
  14087. const displacementScale = materialReference( 'displacementScale', 'float' );
  14088. const displacementBias = materialReference( 'displacementBias', 'float' );
  14089. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  14090. }
  14091. if ( object.isBatchedMesh ) {
  14092. batch( object ).toStack();
  14093. }
  14094. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  14095. instancedMesh( object ).toStack();
  14096. }
  14097. if ( this.positionNode !== null ) {
  14098. positionLocal.assign( subBuild( this.positionNode, 'POSITION', 'vec3' ) );
  14099. }
  14100. return positionLocal;
  14101. }
  14102. /**
  14103. * Setups the computation of the material's diffuse color.
  14104. *
  14105. * @param {NodeBuilder} builder - The current node builder.
  14106. * @param {BufferGeometry} geometry - The geometry.
  14107. */
  14108. setupDiffuseColor( { object, geometry } ) {
  14109. // MASK
  14110. if ( this.maskNode !== null ) {
  14111. // Discard if the mask is `false`
  14112. bool( this.maskNode ).not().discard();
  14113. }
  14114. // COLOR
  14115. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  14116. // VERTEX COLORS
  14117. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  14118. colorNode = colorNode.mul( vertexColor() );
  14119. }
  14120. // INSTANCED COLORS
  14121. if ( object.instanceColor ) {
  14122. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  14123. colorNode = instanceColor.mul( colorNode );
  14124. }
  14125. if ( object.isBatchedMesh && object._colorsTexture ) {
  14126. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  14127. colorNode = batchColor.mul( colorNode );
  14128. }
  14129. // DIFFUSE COLOR
  14130. diffuseColor.assign( colorNode );
  14131. // OPACITY
  14132. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14133. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  14134. // ALPHA TEST
  14135. let alphaTestNode = null;
  14136. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  14137. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  14138. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  14139. }
  14140. // ALPHA HASH
  14141. if ( this.alphaHash === true ) {
  14142. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  14143. }
  14144. // OPAQUE
  14145. const isOpaque = this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false;
  14146. if ( isOpaque ) {
  14147. diffuseColor.a.assign( 1.0 );
  14148. } else if ( alphaTestNode === null ) {
  14149. diffuseColor.a.lessThanEqual( 0 ).discard();
  14150. }
  14151. }
  14152. /**
  14153. * Abstract interface method that can be implemented by derived materials
  14154. * to setup material-specific node variables.
  14155. *
  14156. * @abstract
  14157. * @param {NodeBuilder} builder - The current node builder.
  14158. */
  14159. setupVariants( /*builder*/ ) {
  14160. // Interface function.
  14161. }
  14162. /**
  14163. * Setups the outgoing light node variable
  14164. *
  14165. * @return {Node<vec3>} The outgoing light node.
  14166. */
  14167. setupOutgoingLight() {
  14168. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  14169. }
  14170. /**
  14171. * Setups the normal node from the material.
  14172. *
  14173. * @return {Node<vec3>} The normal node.
  14174. */
  14175. setupNormal() {
  14176. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  14177. }
  14178. /**
  14179. * Setups the environment node from the material.
  14180. *
  14181. * @param {NodeBuilder} builder - The current node builder.
  14182. * @return {Node<vec4>} The environment node.
  14183. */
  14184. setupEnvironment( /*builder*/ ) {
  14185. let node = null;
  14186. if ( this.envNode ) {
  14187. node = this.envNode;
  14188. } else if ( this.envMap ) {
  14189. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  14190. }
  14191. return node;
  14192. }
  14193. /**
  14194. * Setups the light map node from the material.
  14195. *
  14196. * @param {NodeBuilder} builder - The current node builder.
  14197. * @return {Node<vec3>} The light map node.
  14198. */
  14199. setupLightMap( builder ) {
  14200. let node = null;
  14201. if ( builder.material.lightMap ) {
  14202. node = new IrradianceNode( materialLightMap );
  14203. }
  14204. return node;
  14205. }
  14206. /**
  14207. * Setups the lights node based on the scene, environment and material.
  14208. *
  14209. * @param {NodeBuilder} builder - The current node builder.
  14210. * @return {LightsNode} The lights node.
  14211. */
  14212. setupLights( builder ) {
  14213. const materialLightsNode = [];
  14214. //
  14215. const envNode = this.setupEnvironment( builder );
  14216. if ( envNode && envNode.isLightingNode ) {
  14217. materialLightsNode.push( envNode );
  14218. }
  14219. const lightMapNode = this.setupLightMap( builder );
  14220. if ( lightMapNode && lightMapNode.isLightingNode ) {
  14221. materialLightsNode.push( lightMapNode );
  14222. }
  14223. if ( this.aoNode !== null || builder.material.aoMap ) {
  14224. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  14225. materialLightsNode.push( new AONode( aoNode ) );
  14226. }
  14227. let lightsN = this.lightsNode || builder.lightsNode;
  14228. if ( materialLightsNode.length > 0 ) {
  14229. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  14230. }
  14231. return lightsN;
  14232. }
  14233. /**
  14234. * This method should be implemented by most derived materials
  14235. * since it defines the material's lighting model.
  14236. *
  14237. * @abstract
  14238. * @param {NodeBuilder} builder - The current node builder.
  14239. * @return {LightingModel} The lighting model.
  14240. */
  14241. setupLightingModel( /*builder*/ ) {
  14242. // Interface function.
  14243. }
  14244. /**
  14245. * Setups the outgoing light node.
  14246. *
  14247. * @param {NodeBuilder} builder - The current node builder.
  14248. * @return {Node<vec3>} The outgoing light node.
  14249. */
  14250. setupLighting( builder ) {
  14251. const { material } = builder;
  14252. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  14253. // OUTGOING LIGHT
  14254. const lights = this.lights === true || this.lightsNode !== null;
  14255. const lightsNode = lights ? this.setupLights( builder ) : null;
  14256. let outgoingLightNode = this.setupOutgoingLight( builder );
  14257. if ( lightsNode && lightsNode.getScope().hasLights ) {
  14258. const lightingModel = this.setupLightingModel( builder ) || null;
  14259. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  14260. } else if ( backdropNode !== null ) {
  14261. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  14262. }
  14263. // EMISSIVE
  14264. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  14265. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  14266. outgoingLightNode = outgoingLightNode.add( emissive );
  14267. }
  14268. return outgoingLightNode;
  14269. }
  14270. /**
  14271. * Setup the fog.
  14272. *
  14273. * @param {NodeBuilder} builder - The current node builder.
  14274. * @param {Node<vec4>} outputNode - The existing output node.
  14275. * @return {Node<vec4>} The output node.
  14276. */
  14277. setupFog( builder, outputNode ) {
  14278. const fogNode = builder.fogNode;
  14279. if ( fogNode ) {
  14280. output.assign( outputNode );
  14281. outputNode = vec4( fogNode.toVar() );
  14282. }
  14283. return outputNode;
  14284. }
  14285. /**
  14286. * Setups premultiplied alpha.
  14287. *
  14288. * @param {NodeBuilder} builder - The current node builder.
  14289. * @param {Node<vec4>} outputNode - The existing output node.
  14290. * @return {Node<vec4>} The output node.
  14291. */
  14292. setupPremultipliedAlpha( builder, outputNode ) {
  14293. return premultiplyAlpha( outputNode );
  14294. }
  14295. /**
  14296. * Setups the output node.
  14297. *
  14298. * @param {NodeBuilder} builder - The current node builder.
  14299. * @param {Node<vec4>} outputNode - The existing output node.
  14300. * @return {Node<vec4>} The output node.
  14301. */
  14302. setupOutput( builder, outputNode ) {
  14303. // FOG
  14304. if ( this.fog === true ) {
  14305. outputNode = this.setupFog( builder, outputNode );
  14306. }
  14307. // PREMULTIPLIED ALPHA
  14308. if ( this.premultipliedAlpha === true ) {
  14309. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  14310. }
  14311. return outputNode;
  14312. }
  14313. /**
  14314. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  14315. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  14316. * defining all material properties of the classic type in the node type.
  14317. *
  14318. * @param {Material} material - The material to copy properties with their values to this node material.
  14319. */
  14320. setDefaultValues( material ) {
  14321. // This approach is to reuse the native refreshUniforms*
  14322. // and turn available the use of features like transmission and environment in core
  14323. for ( const property in material ) {
  14324. const value = material[ property ];
  14325. if ( this[ property ] === undefined ) {
  14326. this[ property ] = value;
  14327. if ( value && value.clone ) this[ property ] = value.clone();
  14328. }
  14329. }
  14330. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  14331. for ( const key in descriptors ) {
  14332. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  14333. descriptors[ key ].get !== undefined ) {
  14334. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  14335. }
  14336. }
  14337. }
  14338. /**
  14339. * Serializes this material to JSON.
  14340. *
  14341. * @param {?(Object|string)} meta - The meta information for serialization.
  14342. * @return {Object} The serialized node.
  14343. */
  14344. toJSON( meta ) {
  14345. const isRoot = ( meta === undefined || typeof meta === 'string' );
  14346. if ( isRoot ) {
  14347. meta = {
  14348. textures: {},
  14349. images: {},
  14350. nodes: {}
  14351. };
  14352. }
  14353. const data = Material.prototype.toJSON.call( this, meta );
  14354. const nodeChildren = getNodeChildren( this );
  14355. data.inputNodes = {};
  14356. for ( const { property, childNode } of nodeChildren ) {
  14357. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  14358. }
  14359. // TODO: Copied from Object3D.toJSON
  14360. function extractFromCache( cache ) {
  14361. const values = [];
  14362. for ( const key in cache ) {
  14363. const data = cache[ key ];
  14364. delete data.metadata;
  14365. values.push( data );
  14366. }
  14367. return values;
  14368. }
  14369. if ( isRoot ) {
  14370. const textures = extractFromCache( meta.textures );
  14371. const images = extractFromCache( meta.images );
  14372. const nodes = extractFromCache( meta.nodes );
  14373. if ( textures.length > 0 ) data.textures = textures;
  14374. if ( images.length > 0 ) data.images = images;
  14375. if ( nodes.length > 0 ) data.nodes = nodes;
  14376. }
  14377. return data;
  14378. }
  14379. /**
  14380. * Copies the properties of the given node material to this instance.
  14381. *
  14382. * @param {NodeMaterial} source - The material to copy.
  14383. * @return {NodeMaterial} A reference to this node material.
  14384. */
  14385. copy( source ) {
  14386. this.lightsNode = source.lightsNode;
  14387. this.envNode = source.envNode;
  14388. this.colorNode = source.colorNode;
  14389. this.normalNode = source.normalNode;
  14390. this.opacityNode = source.opacityNode;
  14391. this.backdropNode = source.backdropNode;
  14392. this.backdropAlphaNode = source.backdropAlphaNode;
  14393. this.alphaTestNode = source.alphaTestNode;
  14394. this.maskNode = source.maskNode;
  14395. this.positionNode = source.positionNode;
  14396. this.geometryNode = source.geometryNode;
  14397. this.depthNode = source.depthNode;
  14398. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  14399. this.castShadowPositionNode = source.castShadowPositionNode;
  14400. this.receivedShadowNode = source.receivedShadowNode;
  14401. this.castShadowNode = source.castShadowNode;
  14402. this.outputNode = source.outputNode;
  14403. this.mrtNode = source.mrtNode;
  14404. this.fragmentNode = source.fragmentNode;
  14405. this.vertexNode = source.vertexNode;
  14406. return super.copy( source );
  14407. }
  14408. }
  14409. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  14410. /**
  14411. * Node material version of {@link LineBasicMaterial}.
  14412. *
  14413. * @augments NodeMaterial
  14414. */
  14415. class LineBasicNodeMaterial extends NodeMaterial {
  14416. static get type() {
  14417. return 'LineBasicNodeMaterial';
  14418. }
  14419. /**
  14420. * Constructs a new line basic node material.
  14421. *
  14422. * @param {Object} [parameters] - The configuration parameter.
  14423. */
  14424. constructor( parameters ) {
  14425. super();
  14426. /**
  14427. * This flag can be used for type testing.
  14428. *
  14429. * @type {boolean}
  14430. * @readonly
  14431. * @default true
  14432. */
  14433. this.isLineBasicNodeMaterial = true;
  14434. this.setDefaultValues( _defaultValues$d );
  14435. this.setValues( parameters );
  14436. }
  14437. }
  14438. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  14439. /**
  14440. * Node material version of {@link LineDashedMaterial}.
  14441. *
  14442. * @augments NodeMaterial
  14443. */
  14444. class LineDashedNodeMaterial extends NodeMaterial {
  14445. static get type() {
  14446. return 'LineDashedNodeMaterial';
  14447. }
  14448. /**
  14449. * Constructs a new line dashed node material.
  14450. *
  14451. * @param {Object} [parameters] - The configuration parameter.
  14452. */
  14453. constructor( parameters ) {
  14454. super();
  14455. /**
  14456. * This flag can be used for type testing.
  14457. *
  14458. * @type {boolean}
  14459. * @readonly
  14460. * @default true
  14461. */
  14462. this.isLineDashedNodeMaterial = true;
  14463. this.setDefaultValues( _defaultValues$c );
  14464. /**
  14465. * The dash offset.
  14466. *
  14467. * @type {number}
  14468. * @default 0
  14469. */
  14470. this.dashOffset = 0;
  14471. /**
  14472. * The offset of dash materials is by default inferred from the `dashOffset`
  14473. * property. This node property allows to overwrite the default
  14474. * and define the offset with a node instead.
  14475. *
  14476. * If you don't want to overwrite the offset but modify the existing
  14477. * value instead, use {@link materialLineDashOffset}.
  14478. *
  14479. * @type {?Node<float>}
  14480. * @default null
  14481. */
  14482. this.offsetNode = null;
  14483. /**
  14484. * The scale of dash materials is by default inferred from the `scale`
  14485. * property. This node property allows to overwrite the default
  14486. * and define the scale with a node instead.
  14487. *
  14488. * If you don't want to overwrite the scale but modify the existing
  14489. * value instead, use {@link materialLineScale}.
  14490. *
  14491. * @type {?Node<float>}
  14492. * @default null
  14493. */
  14494. this.dashScaleNode = null;
  14495. /**
  14496. * The dash size of dash materials is by default inferred from the `dashSize`
  14497. * property. This node property allows to overwrite the default
  14498. * and define the dash size with a node instead.
  14499. *
  14500. * If you don't want to overwrite the dash size but modify the existing
  14501. * value instead, use {@link materialLineDashSize}.
  14502. *
  14503. * @type {?Node<float>}
  14504. * @default null
  14505. */
  14506. this.dashSizeNode = null;
  14507. /**
  14508. * The gap size of dash materials is by default inferred from the `gapSize`
  14509. * property. This node property allows to overwrite the default
  14510. * and define the gap size with a node instead.
  14511. *
  14512. * If you don't want to overwrite the gap size but modify the existing
  14513. * value instead, use {@link materialLineGapSize}.
  14514. *
  14515. * @type {?Node<float>}
  14516. * @default null
  14517. */
  14518. this.gapSizeNode = null;
  14519. this.setValues( parameters );
  14520. }
  14521. /**
  14522. * Setups the dash specific node variables.
  14523. *
  14524. * @param {NodeBuilder} builder - The current node builder.
  14525. */
  14526. setupVariants( /* builder */ ) {
  14527. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14528. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14529. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14530. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14531. dashSize.assign( dashSizeNode );
  14532. gapSize.assign( gapSizeNode );
  14533. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  14534. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  14535. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  14536. }
  14537. }
  14538. let _sharedFramebuffer = null;
  14539. /**
  14540. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  14541. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  14542. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  14543. *
  14544. * @augments ViewportTextureNode
  14545. */
  14546. class ViewportSharedTextureNode extends ViewportTextureNode {
  14547. static get type() {
  14548. return 'ViewportSharedTextureNode';
  14549. }
  14550. /**
  14551. * Constructs a new viewport shared texture node.
  14552. *
  14553. * @param {Node} [uvNode=screenUV] - The uv node.
  14554. * @param {?Node} [levelNode=null] - The level node.
  14555. */
  14556. constructor( uvNode = screenUV, levelNode = null ) {
  14557. if ( _sharedFramebuffer === null ) {
  14558. _sharedFramebuffer = new FramebufferTexture();
  14559. }
  14560. super( uvNode, levelNode, _sharedFramebuffer );
  14561. }
  14562. /**
  14563. * Overwritten so the method always returns the unique shared
  14564. * framebuffer texture.
  14565. *
  14566. * @return {FramebufferTexture} The shared framebuffer texture.
  14567. */
  14568. getTextureForReference() {
  14569. return _sharedFramebuffer;
  14570. }
  14571. updateReference() {
  14572. return this;
  14573. }
  14574. }
  14575. /**
  14576. * TSL function for creating a shared viewport texture node.
  14577. *
  14578. * @tsl
  14579. * @function
  14580. * @param {?Node} [uvNode=screenUV] - The uv node.
  14581. * @param {?Node} [levelNode=null] - The level node.
  14582. * @returns {ViewportSharedTextureNode}
  14583. */
  14584. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  14585. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  14586. /**
  14587. * This node material can be used to render lines with a size larger than one
  14588. * by representing them as instanced meshes.
  14589. *
  14590. * @augments NodeMaterial
  14591. */
  14592. class Line2NodeMaterial extends NodeMaterial {
  14593. static get type() {
  14594. return 'Line2NodeMaterial';
  14595. }
  14596. /**
  14597. * Constructs a new node material for wide line rendering.
  14598. *
  14599. * @param {Object} [parameters={}] - The configuration parameter.
  14600. */
  14601. constructor( parameters = {} ) {
  14602. super();
  14603. /**
  14604. * This flag can be used for type testing.
  14605. *
  14606. * @type {boolean}
  14607. * @readonly
  14608. * @default true
  14609. */
  14610. this.isLine2NodeMaterial = true;
  14611. this.setDefaultValues( _defaultValues$b );
  14612. /**
  14613. * Whether vertex colors should be used or not.
  14614. *
  14615. * @type {boolean}
  14616. * @default false
  14617. */
  14618. this.useColor = parameters.vertexColors;
  14619. /**
  14620. * The dash offset.
  14621. *
  14622. * @type {number}
  14623. * @default 0
  14624. */
  14625. this.dashOffset = 0;
  14626. /**
  14627. * Defines the lines color.
  14628. *
  14629. * @type {?Node<vec3>}
  14630. * @default null
  14631. */
  14632. this.lineColorNode = null;
  14633. /**
  14634. * Defines the offset.
  14635. *
  14636. * @type {?Node<float>}
  14637. * @default null
  14638. */
  14639. this.offsetNode = null;
  14640. /**
  14641. * Defines the dash scale.
  14642. *
  14643. * @type {?Node<float>}
  14644. * @default null
  14645. */
  14646. this.dashScaleNode = null;
  14647. /**
  14648. * Defines the dash size.
  14649. *
  14650. * @type {?Node<float>}
  14651. * @default null
  14652. */
  14653. this.dashSizeNode = null;
  14654. /**
  14655. * Defines the gap size.
  14656. *
  14657. * @type {?Node<float>}
  14658. * @default null
  14659. */
  14660. this.gapSizeNode = null;
  14661. /**
  14662. * Blending is set to `NoBlending` since transparency
  14663. * is not supported, yet.
  14664. *
  14665. * @type {number}
  14666. * @default 0
  14667. */
  14668. this.blending = NoBlending;
  14669. this._useDash = parameters.dashed;
  14670. this._useAlphaToCoverage = true;
  14671. this._useWorldUnits = false;
  14672. this.setValues( parameters );
  14673. }
  14674. /**
  14675. * Setups the vertex and fragment stage of this node material.
  14676. *
  14677. * @param {NodeBuilder} builder - The current node builder.
  14678. */
  14679. setup( builder ) {
  14680. const { renderer } = builder;
  14681. const useAlphaToCoverage = this._useAlphaToCoverage;
  14682. const useColor = this.useColor;
  14683. const useDash = this._useDash;
  14684. const useWorldUnits = this._useWorldUnits;
  14685. const trimSegment = Fn( ( { start, end } ) => {
  14686. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  14687. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  14688. const nearEstimate = b.mul( -0.5 ).div( a );
  14689. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  14690. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  14691. } ).setLayout( {
  14692. name: 'trimSegment',
  14693. type: 'vec4',
  14694. inputs: [
  14695. { name: 'start', type: 'vec4' },
  14696. { name: 'end', type: 'vec4' }
  14697. ]
  14698. } );
  14699. this.vertexNode = Fn( () => {
  14700. const instanceStart = attribute( 'instanceStart' );
  14701. const instanceEnd = attribute( 'instanceEnd' );
  14702. // camera space
  14703. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  14704. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  14705. if ( useDash ) {
  14706. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  14707. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  14708. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  14709. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  14710. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  14711. lineDistance = lineDistance.add( offsetNode );
  14712. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  14713. }
  14714. if ( useWorldUnits ) {
  14715. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  14716. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  14717. }
  14718. const aspect = viewport.z.div( viewport.w );
  14719. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  14720. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  14721. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  14722. // perhaps there is a more elegant solution -- WestLangley
  14723. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  14724. If( perspective, () => {
  14725. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  14726. end.assign( trimSegment( { start: start, end: end } ) );
  14727. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  14728. start.assign( trimSegment( { start: end, end: start } ) );
  14729. } );
  14730. } );
  14731. // clip space
  14732. const clipStart = cameraProjectionMatrix.mul( start );
  14733. const clipEnd = cameraProjectionMatrix.mul( end );
  14734. // ndc space
  14735. const ndcStart = clipStart.xyz.div( clipStart.w );
  14736. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  14737. // direction
  14738. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  14739. // account for clip-space aspect ratio
  14740. dir.x.assign( dir.x.mul( aspect ) );
  14741. dir.assign( dir.normalize() );
  14742. const clip = vec4().toVar();
  14743. if ( useWorldUnits ) {
  14744. // get the offset direction as perpendicular to the view vector
  14745. const worldDir = end.xyz.sub( start.xyz ).normalize();
  14746. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  14747. const worldUp = worldDir.cross( tmpFwd ).normalize();
  14748. const worldFwd = worldDir.cross( worldUp );
  14749. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  14750. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  14751. // height offset
  14752. const hw = materialLineWidth.mul( 0.5 );
  14753. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  14754. // don't extend the line if we're rendering dashes because we
  14755. // won't be rendering the endcaps
  14756. if ( ! useDash ) {
  14757. // cap extension
  14758. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  14759. // add width to the box
  14760. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  14761. // endcaps
  14762. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  14763. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  14764. } );
  14765. }
  14766. // project the worldpos
  14767. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  14768. // shift the depth of the projected points so the line
  14769. // segments overlap neatly
  14770. const clipPose = vec3().toVar();
  14771. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  14772. clip.z.assign( clipPose.z.mul( clip.w ) );
  14773. } else {
  14774. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  14775. // undo aspect ratio adjustment
  14776. dir.x.assign( dir.x.div( aspect ) );
  14777. offset.x.assign( offset.x.div( aspect ) );
  14778. // sign flip
  14779. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  14780. // endcaps
  14781. If( positionGeometry.y.lessThan( 0.0 ), () => {
  14782. offset.assign( offset.sub( dir ) );
  14783. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  14784. offset.assign( offset.add( dir ) );
  14785. } );
  14786. // adjust for linewidth
  14787. offset.assign( offset.mul( materialLineWidth ) );
  14788. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  14789. offset.assign( offset.div( viewport.w ) );
  14790. // select end
  14791. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  14792. // back to clip space
  14793. offset.assign( offset.mul( clip.w ) );
  14794. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  14795. }
  14796. return clip;
  14797. } )();
  14798. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  14799. const p13 = p1.sub( p3 );
  14800. const p43 = p4.sub( p3 );
  14801. const p21 = p2.sub( p1 );
  14802. const d1343 = p13.dot( p43 );
  14803. const d4321 = p43.dot( p21 );
  14804. const d1321 = p13.dot( p21 );
  14805. const d4343 = p43.dot( p43 );
  14806. const d2121 = p21.dot( p21 );
  14807. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  14808. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  14809. const mua = numer.div( denom ).clamp();
  14810. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  14811. return vec2( mua, mub );
  14812. } );
  14813. this.colorNode = Fn( () => {
  14814. const vUv = uv$1();
  14815. if ( useDash ) {
  14816. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14817. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14818. dashSize.assign( dashSizeNode );
  14819. gapSize.assign( gapSizeNode );
  14820. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  14821. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  14822. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  14823. }
  14824. const alpha = float( 1 ).toVar( 'alpha' );
  14825. if ( useWorldUnits ) {
  14826. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  14827. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  14828. // Find the closest points on the view ray and the line segment
  14829. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  14830. const lineDir = worldEnd.sub( worldStart );
  14831. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  14832. const p1 = worldStart.add( lineDir.mul( params.x ) );
  14833. const p2 = rayEnd.mul( params.y );
  14834. const delta = p1.sub( p2 );
  14835. const len = delta.length();
  14836. const norm = len.div( materialLineWidth );
  14837. if ( ! useDash ) {
  14838. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  14839. const dnorm = norm.fwidth();
  14840. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  14841. } else {
  14842. norm.greaterThan( 0.5 ).discard();
  14843. }
  14844. }
  14845. } else {
  14846. // round endcaps
  14847. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  14848. const a = vUv.x;
  14849. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  14850. const len2 = a.mul( a ).add( b.mul( b ) );
  14851. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  14852. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  14853. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  14854. } );
  14855. } else {
  14856. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  14857. const a = vUv.x;
  14858. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  14859. const len2 = a.mul( a ).add( b.mul( b ) );
  14860. len2.greaterThan( 1.0 ).discard();
  14861. } );
  14862. }
  14863. }
  14864. let lineColorNode;
  14865. if ( this.lineColorNode ) {
  14866. lineColorNode = this.lineColorNode;
  14867. } else {
  14868. if ( useColor ) {
  14869. const instanceColorStart = attribute( 'instanceColorStart' );
  14870. const instanceColorEnd = attribute( 'instanceColorEnd' );
  14871. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  14872. lineColorNode = instanceColor.mul( materialColor );
  14873. } else {
  14874. lineColorNode = materialColor;
  14875. }
  14876. }
  14877. return vec4( lineColorNode, alpha );
  14878. } )();
  14879. if ( this.transparent ) {
  14880. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14881. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  14882. }
  14883. super.setup( builder );
  14884. }
  14885. /**
  14886. * Whether the lines should sized in world units or not.
  14887. * When set to `false` the unit is pixel.
  14888. *
  14889. * @type {boolean}
  14890. * @default false
  14891. */
  14892. get worldUnits() {
  14893. return this._useWorldUnits;
  14894. }
  14895. set worldUnits( value ) {
  14896. if ( this._useWorldUnits !== value ) {
  14897. this._useWorldUnits = value;
  14898. this.needsUpdate = true;
  14899. }
  14900. }
  14901. /**
  14902. * Whether the lines should be dashed or not.
  14903. *
  14904. * @type {boolean}
  14905. * @default false
  14906. */
  14907. get dashed() {
  14908. return this._useDash;
  14909. }
  14910. set dashed( value ) {
  14911. if ( this._useDash !== value ) {
  14912. this._useDash = value;
  14913. this.needsUpdate = true;
  14914. }
  14915. }
  14916. /**
  14917. * Whether alpha to coverage should be used or not.
  14918. *
  14919. * @type {boolean}
  14920. * @default true
  14921. */
  14922. get alphaToCoverage() {
  14923. return this._useAlphaToCoverage;
  14924. }
  14925. set alphaToCoverage( value ) {
  14926. if ( this._useAlphaToCoverage !== value ) {
  14927. this._useAlphaToCoverage = value;
  14928. this.needsUpdate = true;
  14929. }
  14930. }
  14931. }
  14932. /**
  14933. * Packs a direction vector into a color value.
  14934. *
  14935. * @tsl
  14936. * @function
  14937. * @param {Node<vec3>} node - The direction to pack.
  14938. * @return {Node<vec3>} The color.
  14939. */
  14940. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  14941. /**
  14942. * Unpacks a color value into a direction vector.
  14943. *
  14944. * @tsl
  14945. * @function
  14946. * @param {Node<vec3>} node - The color to unpack.
  14947. * @return {Node<vec3>} The direction.
  14948. */
  14949. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  14950. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  14951. /**
  14952. * Node material version of {@link MeshNormalMaterial}.
  14953. *
  14954. * @augments NodeMaterial
  14955. */
  14956. class MeshNormalNodeMaterial extends NodeMaterial {
  14957. static get type() {
  14958. return 'MeshNormalNodeMaterial';
  14959. }
  14960. /**
  14961. * Constructs a new mesh normal node material.
  14962. *
  14963. * @param {Object} [parameters] - The configuration parameter.
  14964. */
  14965. constructor( parameters ) {
  14966. super();
  14967. /**
  14968. * This flag can be used for type testing.
  14969. *
  14970. * @type {boolean}
  14971. * @readonly
  14972. * @default true
  14973. */
  14974. this.isMeshNormalNodeMaterial = true;
  14975. this.setDefaultValues( _defaultValues$a );
  14976. this.setValues( parameters );
  14977. }
  14978. /**
  14979. * Overwrites the default implementation by computing the diffuse color
  14980. * based on the normal data.
  14981. */
  14982. setupDiffuseColor() {
  14983. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14984. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  14985. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( normalView ), opacityNode ), SRGBColorSpace ) );
  14986. }
  14987. }
  14988. /**
  14989. * TSL function for creating an equirect uv node.
  14990. *
  14991. * Can be used to compute texture coordinates for projecting an
  14992. * equirectangular texture onto a mesh for using it as the scene's
  14993. * background.
  14994. *
  14995. * ```js
  14996. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  14997. * ```
  14998. *
  14999. * @tsl
  15000. * @function
  15001. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  15002. * @returns {Node<vec2>}
  15003. */
  15004. const equirectUV = /*@__PURE__*/ Fn( ( [ dir = positionWorldDirection ] ) => {
  15005. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  15006. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  15007. return vec2( u, v );
  15008. } );
  15009. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  15010. /**
  15011. * This class represents a cube render target. It is a special version
  15012. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  15013. *
  15014. * @augments WebGLCubeRenderTarget
  15015. */
  15016. class CubeRenderTarget extends WebGLCubeRenderTarget {
  15017. /**
  15018. * Constructs a new cube render target.
  15019. *
  15020. * @param {number} [size=1] - The size of the render target.
  15021. * @param {RenderTarget~Options} [options] - The configuration object.
  15022. */
  15023. constructor( size = 1, options = {} ) {
  15024. super( size, options );
  15025. /**
  15026. * This flag can be used for type testing.
  15027. *
  15028. * @type {boolean}
  15029. * @readonly
  15030. * @default true
  15031. */
  15032. this.isCubeRenderTarget = true;
  15033. }
  15034. /**
  15035. * Converts the given equirectangular texture to a cube map.
  15036. *
  15037. * @param {Renderer} renderer - The renderer.
  15038. * @param {Texture} texture - The equirectangular texture.
  15039. * @return {CubeRenderTarget} A reference to this cube render target.
  15040. */
  15041. fromEquirectangularTexture( renderer, texture$1 ) {
  15042. const currentMinFilter = texture$1.minFilter;
  15043. const currentGenerateMipmaps = texture$1.generateMipmaps;
  15044. texture$1.generateMipmaps = true;
  15045. this.texture.type = texture$1.type;
  15046. this.texture.colorSpace = texture$1.colorSpace;
  15047. this.texture.generateMipmaps = texture$1.generateMipmaps;
  15048. this.texture.minFilter = texture$1.minFilter;
  15049. this.texture.magFilter = texture$1.magFilter;
  15050. const geometry = new BoxGeometry( 5, 5, 5 );
  15051. const uvNode = equirectUV( positionWorldDirection );
  15052. const material = new NodeMaterial();
  15053. material.colorNode = texture( texture$1, uvNode, 0 );
  15054. material.side = BackSide;
  15055. material.blending = NoBlending;
  15056. const mesh = new Mesh( geometry, material );
  15057. const scene = new Scene();
  15058. scene.add( mesh );
  15059. // Avoid blurred poles
  15060. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  15061. const camera = new CubeCamera( 1, 10, this );
  15062. const currentMRT = renderer.getMRT();
  15063. renderer.setMRT( null );
  15064. camera.update( renderer, scene );
  15065. renderer.setMRT( currentMRT );
  15066. texture$1.minFilter = currentMinFilter;
  15067. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  15068. mesh.geometry.dispose();
  15069. mesh.material.dispose();
  15070. return this;
  15071. }
  15072. }
  15073. const _cache$1 = new WeakMap();
  15074. /**
  15075. * This node can be used to automatically convert environment maps in the
  15076. * equirectangular format into the cube map format.
  15077. *
  15078. * @augments TempNode
  15079. */
  15080. class CubeMapNode extends TempNode {
  15081. static get type() {
  15082. return 'CubeMapNode';
  15083. }
  15084. /**
  15085. * Constructs a new cube map node.
  15086. *
  15087. * @param {Node} envNode - The node representing the environment map.
  15088. */
  15089. constructor( envNode ) {
  15090. super( 'vec3' );
  15091. /**
  15092. * The node representing the environment map.
  15093. *
  15094. * @type {Node}
  15095. */
  15096. this.envNode = envNode;
  15097. /**
  15098. * A reference to the internal cube texture.
  15099. *
  15100. * @private
  15101. * @type {?CubeTexture}
  15102. * @default null
  15103. */
  15104. this._cubeTexture = null;
  15105. /**
  15106. * A reference to the internal cube texture node.
  15107. *
  15108. * @private
  15109. * @type {CubeTextureNode}
  15110. */
  15111. this._cubeTextureNode = cubeTexture( null );
  15112. const defaultTexture = new CubeTexture();
  15113. defaultTexture.isRenderTargetTexture = true;
  15114. /**
  15115. * A default cube texture that acts as a placeholder.
  15116. * It is used when the conversion from equirectangular to cube
  15117. * map has not finished yet for a given texture.
  15118. *
  15119. * @private
  15120. * @type {CubeTexture}
  15121. */
  15122. this._defaultTexture = defaultTexture;
  15123. /**
  15124. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  15125. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  15126. *
  15127. * @type {string}
  15128. * @default 'render'
  15129. */
  15130. this.updateBeforeType = NodeUpdateType.RENDER;
  15131. }
  15132. updateBefore( frame ) {
  15133. const { renderer, material } = frame;
  15134. const envNode = this.envNode;
  15135. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  15136. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  15137. if ( texture && texture.isTexture ) {
  15138. const mapping = texture.mapping;
  15139. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  15140. // check for converted cubemap map
  15141. if ( _cache$1.has( texture ) ) {
  15142. const cubeMap = _cache$1.get( texture );
  15143. mapTextureMapping( cubeMap, texture.mapping );
  15144. this._cubeTexture = cubeMap;
  15145. } else {
  15146. // create cube map from equirectangular map
  15147. const image = texture.image;
  15148. if ( isEquirectangularMapReady$1( image ) ) {
  15149. const renderTarget = new CubeRenderTarget( image.height );
  15150. renderTarget.fromEquirectangularTexture( renderer, texture );
  15151. mapTextureMapping( renderTarget.texture, texture.mapping );
  15152. this._cubeTexture = renderTarget.texture;
  15153. _cache$1.set( texture, renderTarget.texture );
  15154. texture.addEventListener( 'dispose', onTextureDispose );
  15155. } else {
  15156. // default cube texture as fallback when equirectangular texture is not yet loaded
  15157. this._cubeTexture = this._defaultTexture;
  15158. }
  15159. }
  15160. //
  15161. this._cubeTextureNode.value = this._cubeTexture;
  15162. } else {
  15163. // envNode already refers to a cube map
  15164. this._cubeTextureNode = this.envNode;
  15165. }
  15166. }
  15167. }
  15168. }
  15169. setup( builder ) {
  15170. this.updateBefore( builder );
  15171. return this._cubeTextureNode;
  15172. }
  15173. }
  15174. /**
  15175. * Returns true if the given equirectangular image has been fully loaded
  15176. * and is ready for further processing.
  15177. *
  15178. * @private
  15179. * @param {Image} image - The equirectangular image to check.
  15180. * @return {boolean} Whether the image is ready or not.
  15181. */
  15182. function isEquirectangularMapReady$1( image ) {
  15183. if ( image === null || image === undefined ) return false;
  15184. return image.height > 0;
  15185. }
  15186. /**
  15187. * This function is executed when `dispose()` is called on the equirectangular
  15188. * texture. In this case, the generated cube map with its render target
  15189. * is deleted as well.
  15190. *
  15191. * @private
  15192. * @param {Object} event - The event object.
  15193. */
  15194. function onTextureDispose( event ) {
  15195. const texture = event.target;
  15196. texture.removeEventListener( 'dispose', onTextureDispose );
  15197. const renderTarget = _cache$1.get( texture );
  15198. if ( renderTarget !== undefined ) {
  15199. _cache$1.delete( texture );
  15200. renderTarget.dispose();
  15201. }
  15202. }
  15203. /**
  15204. * This function makes sure the generated cube map uses the correct
  15205. * texture mapping that corresponds to the equirectangular original.
  15206. *
  15207. * @private
  15208. * @param {Texture} texture - The cube texture.
  15209. * @param {number} mapping - The original texture mapping.
  15210. */
  15211. function mapTextureMapping( texture, mapping ) {
  15212. if ( mapping === EquirectangularReflectionMapping ) {
  15213. texture.mapping = CubeReflectionMapping;
  15214. } else if ( mapping === EquirectangularRefractionMapping ) {
  15215. texture.mapping = CubeRefractionMapping;
  15216. }
  15217. }
  15218. /**
  15219. * TSL function for creating a cube map node.
  15220. *
  15221. * @tsl
  15222. * @function
  15223. * @param {Node} envNode - The node representing the environment map.
  15224. * @returns {CubeMapNode}
  15225. */
  15226. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  15227. /**
  15228. * Represents a basic model for Image-based lighting (IBL). The environment
  15229. * is defined via environment maps in the equirectangular or cube map format.
  15230. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  15231. * or {@link MeshPhongNodeMaterial}.
  15232. *
  15233. * @augments LightingNode
  15234. */
  15235. class BasicEnvironmentNode extends LightingNode {
  15236. static get type() {
  15237. return 'BasicEnvironmentNode';
  15238. }
  15239. /**
  15240. * Constructs a new basic environment node.
  15241. *
  15242. * @param {Node} [envNode=null] - A node representing the environment.
  15243. */
  15244. constructor( envNode = null ) {
  15245. super();
  15246. /**
  15247. * A node representing the environment.
  15248. *
  15249. * @type {Node}
  15250. * @default null
  15251. */
  15252. this.envNode = envNode;
  15253. }
  15254. setup( builder ) {
  15255. // environment property is used in the finish() method of BasicLightingModel
  15256. builder.context.environment = cubeMapNode( this.envNode );
  15257. }
  15258. }
  15259. /**
  15260. * A specific version of {@link IrradianceNode} that is only relevant
  15261. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  15262. * requires a special scaling factor for the light map.
  15263. *
  15264. * @augments LightingNode
  15265. */
  15266. class BasicLightMapNode extends LightingNode {
  15267. static get type() {
  15268. return 'BasicLightMapNode';
  15269. }
  15270. /**
  15271. * Constructs a new basic light map node.
  15272. *
  15273. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  15274. */
  15275. constructor( lightMapNode = null ) {
  15276. super();
  15277. /**
  15278. * The light map node.
  15279. *
  15280. * @type {?Node<vec3>}
  15281. */
  15282. this.lightMapNode = lightMapNode;
  15283. }
  15284. setup( builder ) {
  15285. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  15286. const RECIPROCAL_PI = float( 1 / Math.PI );
  15287. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  15288. }
  15289. }
  15290. /**
  15291. * Abstract class for implementing lighting models. The module defines
  15292. * multiple methods that concrete lighting models can implement. These
  15293. * methods are executed at different points during the light evaluation
  15294. * process.
  15295. */
  15296. class LightingModel {
  15297. /**
  15298. * This method is intended for setting up lighting model and context data
  15299. * which are later used in the evaluation process.
  15300. *
  15301. * @abstract
  15302. * @param {NodeBuilder} builder - The current node builder.
  15303. */
  15304. start( builder ) {
  15305. // lights ( direct )
  15306. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  15307. // indirect
  15308. this.indirect( builder );
  15309. }
  15310. /**
  15311. * This method is intended for executing final tasks like final updates
  15312. * to the outgoing light.
  15313. *
  15314. * @abstract
  15315. * @param {NodeBuilder} builder - The current node builder.
  15316. */
  15317. finish( /*builder*/ ) { }
  15318. /**
  15319. * This method is intended for implementing the direct light term and
  15320. * executed during the build process of directional, point and spot light nodes.
  15321. *
  15322. * @abstract
  15323. * @param {Object} lightData - The light data.
  15324. * @param {NodeBuilder} builder - The current node builder.
  15325. */
  15326. direct( /*lightData, builder*/ ) { }
  15327. /**
  15328. * This method is intended for implementing the direct light term for
  15329. * rect area light nodes.
  15330. *
  15331. * @abstract
  15332. * @param {Object} lightData - The light data.
  15333. * @param {NodeBuilder} builder - The current node builder.
  15334. */
  15335. directRectArea( /*lightData, builder*/ ) {}
  15336. /**
  15337. * This method is intended for implementing the indirect light term.
  15338. *
  15339. * @abstract
  15340. * @param {NodeBuilder} builder - The current node builder.
  15341. */
  15342. indirect( /*builder*/ ) { }
  15343. /**
  15344. * This method is intended for implementing the ambient occlusion term.
  15345. * Unlike other methods, this method must be called manually by the lighting
  15346. * model in its indirect term.
  15347. *
  15348. * @abstract
  15349. * @param {NodeBuilder} builder - The current node builder.
  15350. */
  15351. ambientOcclusion( /*input, stack, builder*/ ) { }
  15352. }
  15353. /**
  15354. * Represents the lighting model for unlit materials. The only light contribution
  15355. * is baked indirect lighting modulated with ambient occlusion and the material's
  15356. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  15357. *
  15358. * @augments LightingModel
  15359. */
  15360. class BasicLightingModel extends LightingModel {
  15361. /**
  15362. * Constructs a new basic lighting model.
  15363. */
  15364. constructor() {
  15365. super();
  15366. }
  15367. /**
  15368. * Implements the baked indirect lighting with its modulation.
  15369. *
  15370. * @param {NodeBuilder} builder - The current node builder.
  15371. */
  15372. indirect( { context } ) {
  15373. const ambientOcclusion = context.ambientOcclusion;
  15374. const reflectedLight = context.reflectedLight;
  15375. const irradianceLightMap = context.irradianceLightMap;
  15376. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  15377. // accumulation (baked indirect lighting only)
  15378. if ( irradianceLightMap ) {
  15379. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  15380. } else {
  15381. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  15382. }
  15383. // modulation
  15384. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15385. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  15386. }
  15387. /**
  15388. * Implements the environment mapping.
  15389. *
  15390. * @param {NodeBuilder} builder - The current node builder.
  15391. */
  15392. finish( builder ) {
  15393. const { material, context } = builder;
  15394. const outgoingLight = context.outgoingLight;
  15395. const envNode = builder.context.environment;
  15396. if ( envNode ) {
  15397. switch ( material.combine ) {
  15398. case MultiplyOperation:
  15399. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  15400. break;
  15401. case MixOperation:
  15402. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  15403. break;
  15404. case AddOperation:
  15405. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  15406. break;
  15407. default:
  15408. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  15409. break;
  15410. }
  15411. }
  15412. }
  15413. }
  15414. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  15415. /**
  15416. * Node material version of {@link MeshBasicMaterial}.
  15417. *
  15418. * @augments NodeMaterial
  15419. */
  15420. class MeshBasicNodeMaterial extends NodeMaterial {
  15421. static get type() {
  15422. return 'MeshBasicNodeMaterial';
  15423. }
  15424. /**
  15425. * Constructs a new mesh basic node material.
  15426. *
  15427. * @param {Object} [parameters] - The configuration parameter.
  15428. */
  15429. constructor( parameters ) {
  15430. super();
  15431. /**
  15432. * This flag can be used for type testing.
  15433. *
  15434. * @type {boolean}
  15435. * @readonly
  15436. * @default true
  15437. */
  15438. this.isMeshBasicNodeMaterial = true;
  15439. /**
  15440. * Although the basic material is by definition unlit, we set
  15441. * this property to `true` since we use a lighting model to compute
  15442. * the outgoing light of the fragment shader.
  15443. *
  15444. * @type {boolean}
  15445. * @default true
  15446. */
  15447. this.lights = true;
  15448. this.setDefaultValues( _defaultValues$9 );
  15449. this.setValues( parameters );
  15450. }
  15451. /**
  15452. * Basic materials are not affected by normal and bump maps so we
  15453. * return by default {@link normalViewGeometry}.
  15454. *
  15455. * @return {Node<vec3>} The normal node.
  15456. */
  15457. setupNormal() {
  15458. return directionToFaceDirection( normalViewGeometry ); // see #28839
  15459. }
  15460. /**
  15461. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15462. * to implement the default environment mapping.
  15463. *
  15464. * @param {NodeBuilder} builder - The current node builder.
  15465. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15466. */
  15467. setupEnvironment( builder ) {
  15468. const envNode = super.setupEnvironment( builder );
  15469. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15470. }
  15471. /**
  15472. * This method must be overwritten since light maps are evaluated
  15473. * with a special scaling factor for basic materials.
  15474. *
  15475. * @param {NodeBuilder} builder - The current node builder.
  15476. * @return {?BasicLightMapNode<vec3>} The light map node.
  15477. */
  15478. setupLightMap( builder ) {
  15479. let node = null;
  15480. if ( builder.material.lightMap ) {
  15481. node = new BasicLightMapNode( materialLightMap );
  15482. }
  15483. return node;
  15484. }
  15485. /**
  15486. * The material overwrites this method because `lights` is set to `true` but
  15487. * we still want to return the diffuse color as the outgoing light.
  15488. *
  15489. * @return {Node<vec3>} The outgoing light node.
  15490. */
  15491. setupOutgoingLight() {
  15492. return diffuseColor.rgb;
  15493. }
  15494. /**
  15495. * Setups the lighting model.
  15496. *
  15497. * @return {BasicLightingModel} The lighting model.
  15498. */
  15499. setupLightingModel() {
  15500. return new BasicLightingModel();
  15501. }
  15502. }
  15503. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  15504. // Original approximation by Christophe Schlick '94
  15505. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  15506. // Optimized variant (presented by Epic at SIGGRAPH '13)
  15507. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  15508. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  15509. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  15510. } ); // validated
  15511. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  15512. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  15513. } ); // validated
  15514. const G_BlinnPhong_Implicit = () => float( 0.25 );
  15515. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  15516. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  15517. } );
  15518. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15519. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15520. const dotNH = normalView.dot( halfDir ).clamp();
  15521. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15522. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  15523. const G = G_BlinnPhong_Implicit();
  15524. const D = D_BlinnPhong( { dotNH } );
  15525. return F.mul( G ).mul( D );
  15526. } );
  15527. /**
  15528. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  15529. *
  15530. * @augments BasicLightingModel
  15531. */
  15532. class PhongLightingModel extends BasicLightingModel {
  15533. /**
  15534. * Constructs a new phong lighting model.
  15535. *
  15536. * @param {boolean} [specular=true] - Whether specular is supported or not.
  15537. */
  15538. constructor( specular = true ) {
  15539. super();
  15540. /**
  15541. * Whether specular is supported or not. Set this to `false` if you are
  15542. * looking for a Lambert-like material meaning a material for non-shiny
  15543. * surfaces, without specular highlights.
  15544. *
  15545. * @type {boolean}
  15546. * @default true
  15547. */
  15548. this.specular = specular;
  15549. }
  15550. /**
  15551. * Implements the direct lighting. The specular portion is optional an can be controlled
  15552. * with the {@link PhongLightingModel#specular} flag.
  15553. *
  15554. * @param {Object} lightData - The light data.
  15555. */
  15556. direct( { lightDirection, lightColor, reflectedLight } ) {
  15557. const dotNL = normalView.dot( lightDirection ).clamp();
  15558. const irradiance = dotNL.mul( lightColor );
  15559. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15560. if ( this.specular === true ) {
  15561. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  15562. }
  15563. }
  15564. /**
  15565. * Implements the indirect lighting.
  15566. *
  15567. * @param {NodeBuilder} builder - The current node builder.
  15568. */
  15569. indirect( builder ) {
  15570. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  15571. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15572. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15573. }
  15574. }
  15575. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  15576. /**
  15577. * Node material version of {@link MeshLambertMaterial}.
  15578. *
  15579. * @augments NodeMaterial
  15580. */
  15581. class MeshLambertNodeMaterial extends NodeMaterial {
  15582. static get type() {
  15583. return 'MeshLambertNodeMaterial';
  15584. }
  15585. /**
  15586. * Constructs a new mesh lambert node material.
  15587. *
  15588. * @param {Object} [parameters] - The configuration parameter.
  15589. */
  15590. constructor( parameters ) {
  15591. super();
  15592. /**
  15593. * This flag can be used for type testing.
  15594. *
  15595. * @type {boolean}
  15596. * @readonly
  15597. * @default true
  15598. */
  15599. this.isMeshLambertNodeMaterial = true;
  15600. /**
  15601. * Set to `true` because lambert materials react on lights.
  15602. *
  15603. * @type {boolean}
  15604. * @default true
  15605. */
  15606. this.lights = true;
  15607. this.setDefaultValues( _defaultValues$8 );
  15608. this.setValues( parameters );
  15609. }
  15610. /**
  15611. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15612. * to implement the default environment mapping.
  15613. *
  15614. * @param {NodeBuilder} builder - The current node builder.
  15615. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15616. */
  15617. setupEnvironment( builder ) {
  15618. const envNode = super.setupEnvironment( builder );
  15619. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15620. }
  15621. /**
  15622. * Setups the lighting model.
  15623. *
  15624. * @return {PhongLightingModel} The lighting model.
  15625. */
  15626. setupLightingModel( /*builder*/ ) {
  15627. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  15628. }
  15629. }
  15630. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  15631. /**
  15632. * Node material version of {@link MeshPhongMaterial}.
  15633. *
  15634. * @augments NodeMaterial
  15635. */
  15636. class MeshPhongNodeMaterial extends NodeMaterial {
  15637. static get type() {
  15638. return 'MeshPhongNodeMaterial';
  15639. }
  15640. /**
  15641. * Constructs a new mesh lambert node material.
  15642. *
  15643. * @param {Object} [parameters] - The configuration parameter.
  15644. */
  15645. constructor( parameters ) {
  15646. super();
  15647. /**
  15648. * This flag can be used for type testing.
  15649. *
  15650. * @type {boolean}
  15651. * @readonly
  15652. * @default true
  15653. */
  15654. this.isMeshPhongNodeMaterial = true;
  15655. /**
  15656. * Set to `true` because phong materials react on lights.
  15657. *
  15658. * @type {boolean}
  15659. * @default true
  15660. */
  15661. this.lights = true;
  15662. /**
  15663. * The shininess of phong materials is by default inferred from the `shininess`
  15664. * property. This node property allows to overwrite the default
  15665. * and define the shininess with a node instead.
  15666. *
  15667. * If you don't want to overwrite the shininess but modify the existing
  15668. * value instead, use {@link materialShininess}.
  15669. *
  15670. * @type {?Node<float>}
  15671. * @default null
  15672. */
  15673. this.shininessNode = null;
  15674. /**
  15675. * The specular color of phong materials is by default inferred from the
  15676. * `specular` property. This node property allows to overwrite the default
  15677. * and define the specular color with a node instead.
  15678. *
  15679. * If you don't want to overwrite the specular color but modify the existing
  15680. * value instead, use {@link materialSpecular}.
  15681. *
  15682. * @type {?Node<vec3>}
  15683. * @default null
  15684. */
  15685. this.specularNode = null;
  15686. this.setDefaultValues( _defaultValues$7 );
  15687. this.setValues( parameters );
  15688. }
  15689. /**
  15690. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  15691. * to implement the default environment mapping.
  15692. *
  15693. * @param {NodeBuilder} builder - The current node builder.
  15694. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  15695. */
  15696. setupEnvironment( builder ) {
  15697. const envNode = super.setupEnvironment( builder );
  15698. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  15699. }
  15700. /**
  15701. * Setups the lighting model.
  15702. *
  15703. * @return {PhongLightingModel} The lighting model.
  15704. */
  15705. setupLightingModel( /*builder*/ ) {
  15706. return new PhongLightingModel();
  15707. }
  15708. /**
  15709. * Setups the phong specific node variables.
  15710. *
  15711. * @param {NodeBuilder} builder - The current node builder.
  15712. */
  15713. setupVariants( /*builder*/ ) {
  15714. // SHININESS
  15715. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15716. shininess.assign( shininessNode );
  15717. // SPECULAR COLOR
  15718. const specularNode = this.specularNode || materialSpecular;
  15719. specularColor.assign( specularNode );
  15720. }
  15721. copy( source ) {
  15722. this.shininessNode = source.shininessNode;
  15723. this.specularNode = source.specularNode;
  15724. return super.copy( source );
  15725. }
  15726. }
  15727. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  15728. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  15729. return float( 0 );
  15730. }
  15731. const dxy = normalViewGeometry.dFdx().abs().max( normalViewGeometry.dFdy().abs() );
  15732. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  15733. return geometryRoughness;
  15734. } );
  15735. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  15736. const { roughness } = inputs;
  15737. const geometryRoughness = getGeometryRoughness();
  15738. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  15739. roughnessFactor = roughnessFactor.add( geometryRoughness );
  15740. roughnessFactor = roughnessFactor.min( 1.0 );
  15741. return roughnessFactor;
  15742. } );
  15743. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  15744. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  15745. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  15746. const a2 = alpha.pow2();
  15747. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  15748. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  15749. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  15750. } ).setLayout( {
  15751. name: 'V_GGX_SmithCorrelated',
  15752. type: 'float',
  15753. inputs: [
  15754. { name: 'alpha', type: 'float' },
  15755. { name: 'dotNL', type: 'float' },
  15756. { name: 'dotNV', type: 'float' }
  15757. ]
  15758. } ); // validated
  15759. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15760. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  15761. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  15762. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  15763. const v = div( 0.5, gv.add( gl ) );
  15764. return v.saturate();
  15765. } ).setLayout( {
  15766. name: 'V_GGX_SmithCorrelated_Anisotropic',
  15767. type: 'float',
  15768. inputs: [
  15769. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15770. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15771. { name: 'dotTV', type: 'float', qualifier: 'in' },
  15772. { name: 'dotBV', type: 'float', qualifier: 'in' },
  15773. { name: 'dotTL', type: 'float', qualifier: 'in' },
  15774. { name: 'dotBL', type: 'float', qualifier: 'in' },
  15775. { name: 'dotNV', type: 'float', qualifier: 'in' },
  15776. { name: 'dotNL', type: 'float', qualifier: 'in' }
  15777. ]
  15778. } );
  15779. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  15780. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  15781. // alpha is "roughness squared" in Disney’s reparameterization
  15782. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  15783. const a2 = alpha.pow2();
  15784. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  15785. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  15786. } ).setLayout( {
  15787. name: 'D_GGX',
  15788. type: 'float',
  15789. inputs: [
  15790. { name: 'alpha', type: 'float' },
  15791. { name: 'dotNH', type: 'float' }
  15792. ]
  15793. } ); // validated
  15794. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  15795. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15796. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  15797. const a2 = alphaT.mul( alphaB );
  15798. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  15799. const v2 = v.dot( v );
  15800. const w2 = a2.div( v2 );
  15801. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  15802. } ).setLayout( {
  15803. name: 'D_GGX_Anisotropic',
  15804. type: 'float',
  15805. inputs: [
  15806. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15807. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15808. { name: 'dotNH', type: 'float', qualifier: 'in' },
  15809. { name: 'dotTH', type: 'float', qualifier: 'in' },
  15810. { name: 'dotBH', type: 'float', qualifier: 'in' }
  15811. ]
  15812. } );
  15813. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  15814. const BRDF_GGX = /*@__PURE__*/ Fn( ( { lightDirection, f0, f90, roughness, f, normalView: normalView$1 = normalView, USE_IRIDESCENCE, USE_ANISOTROPY } ) => {
  15815. const alpha = roughness.pow2(); // UE4's roughness
  15816. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15817. const dotNL = normalView$1.dot( lightDirection ).clamp();
  15818. const dotNV = normalView$1.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15819. const dotNH = normalView$1.dot( halfDir ).clamp();
  15820. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15821. let F = F_Schlick( { f0, f90, dotVH } );
  15822. let V, D;
  15823. if ( defined( USE_IRIDESCENCE ) ) {
  15824. F = iridescence.mix( F, f );
  15825. }
  15826. if ( defined( USE_ANISOTROPY ) ) {
  15827. const dotTL = anisotropyT.dot( lightDirection );
  15828. const dotTV = anisotropyT.dot( positionViewDirection );
  15829. const dotTH = anisotropyT.dot( halfDir );
  15830. const dotBL = anisotropyB.dot( lightDirection );
  15831. const dotBV = anisotropyB.dot( positionViewDirection );
  15832. const dotBH = anisotropyB.dot( halfDir );
  15833. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  15834. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  15835. } else {
  15836. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  15837. D = D_GGX( { alpha, dotNH } );
  15838. }
  15839. return F.mul( V ).mul( D );
  15840. } ); // validated
  15841. // Analytical approximation of the DFG LUT, one half of the
  15842. // split-sum approximation used in indirect specular lighting.
  15843. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  15844. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  15845. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  15846. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  15847. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  15848. const r = roughness.mul( c0 ).add( c1 );
  15849. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  15850. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  15851. return fab;
  15852. } ).setLayout( {
  15853. name: 'DFGApprox',
  15854. type: 'vec2',
  15855. inputs: [
  15856. { name: 'roughness', type: 'float' },
  15857. { name: 'dotNV', type: 'vec3' }
  15858. ]
  15859. } );
  15860. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  15861. const { dotNV, specularColor, specularF90, roughness } = inputs;
  15862. const fab = DFGApprox( { dotNV, roughness } );
  15863. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  15864. } );
  15865. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  15866. const x = dotVH.oneMinus().saturate();
  15867. const x2 = x.mul( x );
  15868. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  15869. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  15870. } ).setLayout( {
  15871. name: 'Schlick_to_F0',
  15872. type: 'vec3',
  15873. inputs: [
  15874. { name: 'f', type: 'vec3' },
  15875. { name: 'f90', type: 'float' },
  15876. { name: 'dotVH', type: 'float' }
  15877. ]
  15878. } );
  15879. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  15880. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  15881. const alpha = roughness.pow2();
  15882. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  15883. const invAlpha = float( 1.0 ).div( alpha );
  15884. const cos2h = dotNH.pow2();
  15885. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  15886. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  15887. } ).setLayout( {
  15888. name: 'D_Charlie',
  15889. type: 'float',
  15890. inputs: [
  15891. { name: 'roughness', type: 'float' },
  15892. { name: 'dotNH', type: 'float' }
  15893. ]
  15894. } );
  15895. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  15896. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  15897. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  15898. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  15899. } ).setLayout( {
  15900. name: 'V_Neubelt',
  15901. type: 'float',
  15902. inputs: [
  15903. { name: 'dotNV', type: 'float' },
  15904. { name: 'dotNL', type: 'float' }
  15905. ]
  15906. } );
  15907. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15908. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15909. const dotNL = normalView.dot( lightDirection ).clamp();
  15910. const dotNV = normalView.dot( positionViewDirection ).clamp();
  15911. const dotNH = normalView.dot( halfDir ).clamp();
  15912. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  15913. const V = V_Neubelt( { dotNV, dotNL } );
  15914. return sheen.mul( D ).mul( V );
  15915. } );
  15916. // Rect Area Light
  15917. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  15918. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  15919. // code: https://github.com/selfshadow/ltc_code/
  15920. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  15921. const LUT_SIZE = 64.0;
  15922. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  15923. const LUT_BIAS = 0.5 / LUT_SIZE;
  15924. const dotNV = N.dot( V ).saturate();
  15925. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  15926. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  15927. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  15928. return uv;
  15929. } ).setLayout( {
  15930. name: 'LTC_Uv',
  15931. type: 'vec2',
  15932. inputs: [
  15933. { name: 'N', type: 'vec3' },
  15934. { name: 'V', type: 'vec3' },
  15935. { name: 'roughness', type: 'float' }
  15936. ]
  15937. } );
  15938. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  15939. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  15940. // An approximation of the form factor of a horizon-clipped rectangle.
  15941. const l = f.length();
  15942. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  15943. } ).setLayout( {
  15944. name: 'LTC_ClippedSphereFormFactor',
  15945. type: 'float',
  15946. inputs: [
  15947. { name: 'f', type: 'vec3' }
  15948. ]
  15949. } );
  15950. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  15951. const x = v1.dot( v2 );
  15952. const y = x.abs().toVar();
  15953. // rational polynomial approximation to theta / sin( theta ) / 2PI
  15954. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  15955. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  15956. const v = a.div( b );
  15957. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  15958. return v1.cross( v2 ).mul( theta_sintheta );
  15959. } ).setLayout( {
  15960. name: 'LTC_EdgeVectorFormFactor',
  15961. type: 'vec3',
  15962. inputs: [
  15963. { name: 'v1', type: 'vec3' },
  15964. { name: 'v2', type: 'vec3' }
  15965. ]
  15966. } );
  15967. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  15968. // bail if point is on back side of plane of light
  15969. // assumes ccw winding order of light vertices
  15970. const v1 = p1.sub( p0 ).toVar();
  15971. const v2 = p3.sub( p0 ).toVar();
  15972. const lightNormal = v1.cross( v2 );
  15973. const result = vec3().toVar();
  15974. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15975. // construct orthonormal basis around N
  15976. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  15977. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  15978. // compute transform
  15979. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  15980. // transform rect
  15981. // & project rect onto sphere
  15982. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  15983. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  15984. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  15985. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  15986. // calculate vector form factor
  15987. const vectorFormFactor = vec3( 0 ).toVar();
  15988. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15989. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15990. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15991. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15992. // adjust for horizon clipping
  15993. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  15994. } );
  15995. return result;
  15996. } ).setLayout( {
  15997. name: 'LTC_Evaluate',
  15998. type: 'vec3',
  15999. inputs: [
  16000. { name: 'N', type: 'vec3' },
  16001. { name: 'V', type: 'vec3' },
  16002. { name: 'P', type: 'vec3' },
  16003. { name: 'mInv', type: 'mat3' },
  16004. { name: 'p0', type: 'vec3' },
  16005. { name: 'p1', type: 'vec3' },
  16006. { name: 'p2', type: 'vec3' },
  16007. { name: 'p3', type: 'vec3' }
  16008. ]
  16009. } );
  16010. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  16011. // bail if point is on back side of plane of light
  16012. // assumes ccw winding order of light vertices
  16013. const v1 = p1.sub( p0 ).toVar();
  16014. const v2 = p3.sub( p0 ).toVar();
  16015. const lightNormal = v1.cross( v2 );
  16016. const result = vec3().toVar();
  16017. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  16018. // transform rect
  16019. // & project rect onto sphere
  16020. const coords0 = p0.sub( P ).normalize().toVar();
  16021. const coords1 = p1.sub( P ).normalize().toVar();
  16022. const coords2 = p2.sub( P ).normalize().toVar();
  16023. const coords3 = p3.sub( P ).normalize().toVar();
  16024. // calculate vector form factor
  16025. const vectorFormFactor = vec3( 0 ).toVar();
  16026. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  16027. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  16028. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  16029. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  16030. // adjust for horizon clipping
  16031. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  16032. } );
  16033. return result;
  16034. } ).setLayout( {
  16035. name: 'LTC_Evaluate',
  16036. type: 'vec3',
  16037. inputs: [
  16038. { name: 'P', type: 'vec3' },
  16039. { name: 'p0', type: 'vec3' },
  16040. { name: 'p1', type: 'vec3' },
  16041. { name: 'p2', type: 'vec3' },
  16042. { name: 'p3', type: 'vec3' }
  16043. ]
  16044. } );
  16045. // Mipped Bicubic Texture Filtering by N8
  16046. // https://www.shadertoy.com/view/Dl2SDW
  16047. const bC = 1.0 / 6.0;
  16048. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  16049. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  16050. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  16051. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  16052. const g0 = ( a ) => w0( a ).add( w1( a ) );
  16053. const g1 = ( a ) => w2( a ).add( w3( a ) );
  16054. // h0 and h1 are the two offset functions
  16055. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  16056. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  16057. const bicubic = ( textureNode, texelSize, lod ) => {
  16058. const uv = textureNode.uvNode;
  16059. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  16060. const iuv = floor( uvScaled );
  16061. const fuv = fract( uvScaled );
  16062. const g0x = g0( fuv.x );
  16063. const g1x = g1( fuv.x );
  16064. const h0x = h0( fuv.x );
  16065. const h1x = h1( fuv.x );
  16066. const h0y = h0( fuv.y );
  16067. const h1y = h1( fuv.y );
  16068. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16069. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  16070. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16071. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  16072. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  16073. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  16074. return a.add( b );
  16075. };
  16076. /**
  16077. * Applies mipped bicubic texture filtering to the given texture node.
  16078. *
  16079. * @tsl
  16080. * @function
  16081. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16082. * @param {Node<float>} lodNode - Defines the LOD to sample from.
  16083. * @return {Node} The filtered texture sample.
  16084. */
  16085. const textureBicubicLevel = /*@__PURE__*/ Fn( ( [ textureNode, lodNode ] ) => {
  16086. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  16087. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  16088. const fLodSizeInv = div( 1.0, fLodSize );
  16089. const cLodSizeInv = div( 1.0, cLodSize );
  16090. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  16091. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  16092. return fract( lodNode ).mix( fSample, cSample );
  16093. } );
  16094. /**
  16095. * Applies mipped bicubic texture filtering to the given texture node.
  16096. *
  16097. * @tsl
  16098. * @function
  16099. * @param {TextureNode} textureNode - The texture node that should be filtered.
  16100. * @param {Node<float>} [strength] - Defines the strength of the bicubic filtering.
  16101. * @return {Node} The filtered texture sample.
  16102. */
  16103. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, strength ] ) => {
  16104. const lod = strength.mul( maxMipLevel( textureNode ) );
  16105. return textureBicubicLevel( textureNode, lod );
  16106. } );
  16107. //
  16108. // Transmission
  16109. //
  16110. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  16111. // Direction of refracted light.
  16112. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  16113. // Compute rotation-independent scaling of the model matrix.
  16114. const modelScale = vec3(
  16115. length( modelMatrix[ 0 ].xyz ),
  16116. length( modelMatrix[ 1 ].xyz ),
  16117. length( modelMatrix[ 2 ].xyz )
  16118. );
  16119. // The thickness is specified in local space.
  16120. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  16121. } ).setLayout( {
  16122. name: 'getVolumeTransmissionRay',
  16123. type: 'vec3',
  16124. inputs: [
  16125. { name: 'n', type: 'vec3' },
  16126. { name: 'v', type: 'vec3' },
  16127. { name: 'thickness', type: 'float' },
  16128. { name: 'ior', type: 'float' },
  16129. { name: 'modelMatrix', type: 'mat4' }
  16130. ]
  16131. } );
  16132. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  16133. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  16134. // an IOR of 1.5 results in the default amount of microfacet refraction.
  16135. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  16136. } ).setLayout( {
  16137. name: 'applyIorToRoughness',
  16138. type: 'float',
  16139. inputs: [
  16140. { name: 'roughness', type: 'float' },
  16141. { name: 'ior', type: 'float' }
  16142. ]
  16143. } );
  16144. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  16145. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  16146. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  16147. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  16148. const transmissionSample = vTexture.sample( fragCoord );
  16149. //const transmissionSample = viewportMipTexture( fragCoord );
  16150. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  16151. return textureBicubicLevel( transmissionSample, lod );
  16152. } );
  16153. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  16154. If( attenuationDistance.notEqual( 0 ), () => {
  16155. // Compute light attenuation using Beer's law.
  16156. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  16157. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  16158. return transmittance;
  16159. } );
  16160. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  16161. return vec3( 1.0 );
  16162. } ).setLayout( {
  16163. name: 'volumeAttenuation',
  16164. type: 'vec3',
  16165. inputs: [
  16166. { name: 'transmissionDistance', type: 'float' },
  16167. { name: 'attenuationColor', type: 'vec3' },
  16168. { name: 'attenuationDistance', type: 'float' }
  16169. ]
  16170. } );
  16171. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  16172. let transmittedLight, transmittance;
  16173. if ( dispersion ) {
  16174. transmittedLight = vec4().toVar();
  16175. transmittance = vec3().toVar();
  16176. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  16177. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  16178. Loop( { start: 0, end: 3 }, ( { i } ) => {
  16179. const ior = iors.element( i );
  16180. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16181. const refractedRayExit = position.add( transmissionRay );
  16182. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16183. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16184. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16185. refractionCoords.addAssign( 1.0 );
  16186. refractionCoords.divAssign( 2.0 );
  16187. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16188. // Sample framebuffer to get pixel the refracted ray hits.
  16189. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  16190. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  16191. transmittedLight.a.addAssign( transmissionSample.a );
  16192. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  16193. } );
  16194. transmittedLight.a.divAssign( 3.0 );
  16195. } else {
  16196. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  16197. const refractedRayExit = position.add( transmissionRay );
  16198. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  16199. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  16200. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  16201. refractionCoords.addAssign( 1.0 );
  16202. refractionCoords.divAssign( 2.0 );
  16203. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  16204. // Sample framebuffer to get pixel the refracted ray hits.
  16205. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  16206. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  16207. }
  16208. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  16209. const dotNV = n.dot( v ).clamp();
  16210. // Get the specular component.
  16211. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  16212. dotNV,
  16213. specularColor,
  16214. specularF90,
  16215. roughness
  16216. } ) );
  16217. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  16218. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  16219. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  16220. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  16221. } );
  16222. //
  16223. // Iridescence
  16224. //
  16225. // XYZ to linear-sRGB color space
  16226. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  16227. 3.2404542, -0.969266, 0.0556434,
  16228. -1.5371385, 1.8760108, -0.2040259,
  16229. -0.4985314, 0.0415560, 1.0572252
  16230. );
  16231. // Assume air interface for top
  16232. // Note: We don't handle the case fresnel0 == 1
  16233. const Fresnel0ToIor = ( fresnel0 ) => {
  16234. const sqrtF0 = fresnel0.sqrt();
  16235. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  16236. };
  16237. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  16238. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  16239. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  16240. };
  16241. // Fresnel equations for dielectric/dielectric interfaces.
  16242. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  16243. // Evaluation XYZ sensitivity curves in Fourier space
  16244. const evalSensitivity = ( OPD, shift ) => {
  16245. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  16246. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  16247. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  16248. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  16249. 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() );
  16250. 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() );
  16251. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  16252. const rgb = XYZ_TO_REC709.mul( xyz );
  16253. return rgb;
  16254. };
  16255. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  16256. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  16257. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  16258. // Evaluate the cosTheta on the base layer (Snell law)
  16259. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  16260. // Handle TIR:
  16261. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  16262. If( cosTheta2Sq.lessThan( 0 ), () => {
  16263. return vec3( 1.0 );
  16264. } );
  16265. const cosTheta2 = cosTheta2Sq.sqrt();
  16266. // First interface
  16267. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  16268. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  16269. //const R21 = R12;
  16270. const T121 = R12.oneMinus();
  16271. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  16272. const phi21 = float( Math.PI ).sub( phi12 );
  16273. // Second interface
  16274. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  16275. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  16276. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  16277. const phi23 = vec3(
  16278. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16279. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  16280. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  16281. );
  16282. // Phase shift
  16283. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  16284. const phi = vec3( phi21 ).add( phi23 );
  16285. // Compound terms
  16286. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  16287. const r123 = R123.sqrt();
  16288. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  16289. // Reflectance term for m = 0 (DC term amplitude)
  16290. const C0 = R12.add( Rs );
  16291. const I = C0.toVar();
  16292. // Reflectance term for m > 0 (pairs of diracs)
  16293. const Cm = Rs.sub( T121 ).toVar();
  16294. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  16295. Cm.mulAssign( r123 );
  16296. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  16297. I.addAssign( Cm.mul( Sm ) );
  16298. } );
  16299. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  16300. return I.max( vec3( 0.0 ) );
  16301. } ).setLayout( {
  16302. name: 'evalIridescence',
  16303. type: 'vec3',
  16304. inputs: [
  16305. { name: 'outsideIOR', type: 'float' },
  16306. { name: 'eta2', type: 'float' },
  16307. { name: 'cosTheta1', type: 'float' },
  16308. { name: 'thinFilmThickness', type: 'float' },
  16309. { name: 'baseF0', type: 'vec3' }
  16310. ]
  16311. } );
  16312. //
  16313. // Sheen
  16314. //
  16315. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  16316. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  16317. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  16318. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  16319. const dotNV = normal.dot( viewDir ).saturate();
  16320. const r2 = roughness.pow2();
  16321. const a = select(
  16322. roughness.lessThan( 0.25 ),
  16323. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  16324. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  16325. );
  16326. const b = select(
  16327. roughness.lessThan( 0.25 ),
  16328. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  16329. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  16330. );
  16331. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  16332. return DG.mul( 1.0 / Math.PI ).saturate();
  16333. } );
  16334. const clearcoatF0 = vec3( 0.04 );
  16335. const clearcoatF90 = float( 1 );
  16336. /**
  16337. * Represents the lighting model for a PBR material.
  16338. *
  16339. * @augments LightingModel
  16340. */
  16341. class PhysicalLightingModel extends LightingModel {
  16342. /**
  16343. * Constructs a new physical lighting model.
  16344. *
  16345. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  16346. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  16347. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  16348. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  16349. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  16350. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  16351. */
  16352. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  16353. super();
  16354. /**
  16355. * Whether clearcoat is supported or not.
  16356. *
  16357. * @type {boolean}
  16358. * @default false
  16359. */
  16360. this.clearcoat = clearcoat;
  16361. /**
  16362. * Whether sheen is supported or not.
  16363. *
  16364. * @type {boolean}
  16365. * @default false
  16366. */
  16367. this.sheen = sheen;
  16368. /**
  16369. * Whether iridescence is supported or not.
  16370. *
  16371. * @type {boolean}
  16372. * @default false
  16373. */
  16374. this.iridescence = iridescence;
  16375. /**
  16376. * Whether anisotropy is supported or not.
  16377. *
  16378. * @type {boolean}
  16379. * @default false
  16380. */
  16381. this.anisotropy = anisotropy;
  16382. /**
  16383. * Whether transmission is supported or not.
  16384. *
  16385. * @type {boolean}
  16386. * @default false
  16387. */
  16388. this.transmission = transmission;
  16389. /**
  16390. * Whether dispersion is supported or not.
  16391. *
  16392. * @type {boolean}
  16393. * @default false
  16394. */
  16395. this.dispersion = dispersion;
  16396. /**
  16397. * The clear coat radiance.
  16398. *
  16399. * @type {?Node}
  16400. * @default null
  16401. */
  16402. this.clearcoatRadiance = null;
  16403. /**
  16404. * The clear coat specular direct.
  16405. *
  16406. * @type {?Node}
  16407. * @default null
  16408. */
  16409. this.clearcoatSpecularDirect = null;
  16410. /**
  16411. * The clear coat specular indirect.
  16412. *
  16413. * @type {?Node}
  16414. * @default null
  16415. */
  16416. this.clearcoatSpecularIndirect = null;
  16417. /**
  16418. * The sheen specular direct.
  16419. *
  16420. * @type {?Node}
  16421. * @default null
  16422. */
  16423. this.sheenSpecularDirect = null;
  16424. /**
  16425. * The sheen specular indirect.
  16426. *
  16427. * @type {?Node}
  16428. * @default null
  16429. */
  16430. this.sheenSpecularIndirect = null;
  16431. /**
  16432. * The iridescence Fresnel.
  16433. *
  16434. * @type {?Node}
  16435. * @default null
  16436. */
  16437. this.iridescenceFresnel = null;
  16438. /**
  16439. * The iridescence F0.
  16440. *
  16441. * @type {?Node}
  16442. * @default null
  16443. */
  16444. this.iridescenceF0 = null;
  16445. }
  16446. /**
  16447. * Depending on what features are requested, the method prepares certain node variables
  16448. * which are later used for lighting computations.
  16449. *
  16450. * @param {NodeBuilder} builder - The current node builder.
  16451. */
  16452. start( builder ) {
  16453. if ( this.clearcoat === true ) {
  16454. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  16455. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  16456. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  16457. }
  16458. if ( this.sheen === true ) {
  16459. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  16460. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  16461. }
  16462. if ( this.iridescence === true ) {
  16463. const dotNVi = normalView.dot( positionViewDirection ).clamp();
  16464. this.iridescenceFresnel = evalIridescence( {
  16465. outsideIOR: float( 1.0 ),
  16466. eta2: iridescenceIOR,
  16467. cosTheta1: dotNVi,
  16468. thinFilmThickness: iridescenceThickness,
  16469. baseF0: specularColor
  16470. } );
  16471. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  16472. }
  16473. if ( this.transmission === true ) {
  16474. const position = positionWorld;
  16475. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  16476. const n = normalWorld;
  16477. const context = builder.context;
  16478. context.backdrop = getIBLVolumeRefraction(
  16479. n,
  16480. v,
  16481. roughness,
  16482. diffuseColor,
  16483. specularColor,
  16484. specularF90, // specularF90
  16485. position, // positionWorld
  16486. modelWorldMatrix, // modelMatrix
  16487. cameraViewMatrix, // viewMatrix
  16488. cameraProjectionMatrix, // projMatrix
  16489. ior,
  16490. thickness,
  16491. attenuationColor,
  16492. attenuationDistance,
  16493. this.dispersion ? dispersion : null
  16494. );
  16495. context.backdropAlpha = transmission;
  16496. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  16497. }
  16498. super.start( builder );
  16499. }
  16500. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  16501. // Approximates multi-scattering in order to preserve energy.
  16502. // http://www.jcgt.org/published/0008/01/03/
  16503. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  16504. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16505. const fab = DFGApprox( { roughness, dotNV } );
  16506. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  16507. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  16508. const Ess = fab.x.add( fab.y );
  16509. const Ems = Ess.oneMinus();
  16510. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  16511. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  16512. singleScatter.addAssign( FssEss );
  16513. multiScatter.addAssign( Fms.mul( Ems ) );
  16514. }
  16515. /**
  16516. * Implements the direct light.
  16517. *
  16518. * @param {Object} lightData - The light data.
  16519. * @param {NodeBuilder} builder - The current node builder.
  16520. */
  16521. direct( { lightDirection, lightColor, reflectedLight }, /* builder */ ) {
  16522. const dotNL = normalView.dot( lightDirection ).clamp();
  16523. const irradiance = dotNL.mul( lightColor );
  16524. if ( this.sheen === true ) {
  16525. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  16526. }
  16527. if ( this.clearcoat === true ) {
  16528. const dotNLcc = clearcoatNormalView.dot( lightDirection ).clamp();
  16529. const ccIrradiance = dotNLcc.mul( lightColor );
  16530. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: clearcoatNormalView } ) ) );
  16531. }
  16532. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  16533. 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 } ) ) );
  16534. }
  16535. /**
  16536. * This method is intended for implementing the direct light term for
  16537. * rect area light nodes.
  16538. *
  16539. * @param {Object} input - The input data.
  16540. * @param {NodeBuilder} builder - The current node builder.
  16541. */
  16542. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 }, /* builder */ ) {
  16543. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  16544. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  16545. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  16546. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  16547. const N = normalView;
  16548. const V = positionViewDirection;
  16549. const P = positionView.toVar();
  16550. const uv = LTC_Uv( { N, V, roughness } );
  16551. const t1 = ltc_1.sample( uv ).toVar();
  16552. const t2 = ltc_2.sample( uv ).toVar();
  16553. const mInv = mat3(
  16554. vec3( t1.x, 0, t1.y ),
  16555. vec3( 0, 1, 0 ),
  16556. vec3( t1.z, 0, t1.w )
  16557. ).toVar();
  16558. // LTC Fresnel Approximation by Stephen Hill
  16559. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  16560. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  16561. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  16562. 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 } ) ) );
  16563. }
  16564. /**
  16565. * Implements the indirect lighting.
  16566. *
  16567. * @param {NodeBuilder} builder - The current node builder.
  16568. */
  16569. indirect( builder ) {
  16570. this.indirectDiffuse( builder );
  16571. this.indirectSpecular( builder );
  16572. this.ambientOcclusion( builder );
  16573. }
  16574. /**
  16575. * Implements the indirect diffuse term.
  16576. *
  16577. * @param {NodeBuilder} builder - The current node builder.
  16578. */
  16579. indirectDiffuse( builder ) {
  16580. const { irradiance, reflectedLight } = builder.context;
  16581. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  16582. }
  16583. /**
  16584. * Implements the indirect specular term.
  16585. *
  16586. * @param {NodeBuilder} builder - The current node builder.
  16587. */
  16588. indirectSpecular( builder ) {
  16589. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  16590. if ( this.sheen === true ) {
  16591. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  16592. sheen,
  16593. IBLSheenBRDF( {
  16594. normal: normalView,
  16595. viewDir: positionViewDirection,
  16596. roughness: sheenRoughness
  16597. } )
  16598. ) );
  16599. }
  16600. if ( this.clearcoat === true ) {
  16601. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16602. const clearcoatEnv = EnvironmentBRDF( {
  16603. dotNV: dotNVcc,
  16604. specularColor: clearcoatF0,
  16605. specularF90: clearcoatF90,
  16606. roughness: clearcoatRoughness
  16607. } );
  16608. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  16609. }
  16610. // Both indirect specular and indirect diffuse light accumulate here
  16611. const singleScattering = vec3().toVar( 'singleScattering' );
  16612. const multiScattering = vec3().toVar( 'multiScattering' );
  16613. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  16614. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  16615. const totalScattering = singleScattering.add( multiScattering );
  16616. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  16617. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  16618. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  16619. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  16620. }
  16621. /**
  16622. * Implements the ambient occlusion term.
  16623. *
  16624. * @param {NodeBuilder} builder - The current node builder.
  16625. */
  16626. ambientOcclusion( builder ) {
  16627. const { ambientOcclusion, reflectedLight } = builder.context;
  16628. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  16629. const aoNV = dotNV.add( ambientOcclusion );
  16630. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  16631. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  16632. if ( this.clearcoat === true ) {
  16633. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  16634. }
  16635. if ( this.sheen === true ) {
  16636. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  16637. }
  16638. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  16639. reflectedLight.indirectSpecular.mulAssign( aoNode );
  16640. }
  16641. /**
  16642. * Used for final lighting accumulations depending on the requested features.
  16643. *
  16644. * @param {NodeBuilder} builder - The current node builder.
  16645. */
  16646. finish( { context } ) {
  16647. const { outgoingLight } = context;
  16648. if ( this.clearcoat === true ) {
  16649. const dotNVcc = clearcoatNormalView.dot( positionViewDirection ).clamp();
  16650. const Fcc = F_Schlick( {
  16651. dotVH: dotNVcc,
  16652. f0: clearcoatF0,
  16653. f90: clearcoatF90
  16654. } );
  16655. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  16656. outgoingLight.assign( clearcoatLight );
  16657. }
  16658. if ( this.sheen === true ) {
  16659. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  16660. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  16661. outgoingLight.assign( sheenLight );
  16662. }
  16663. }
  16664. }
  16665. // These defines must match with PMREMGenerator
  16666. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  16667. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  16668. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  16669. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  16670. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  16671. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  16672. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  16673. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  16674. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  16675. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  16676. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  16677. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  16678. // These shader functions convert between the UV coordinates of a single face of
  16679. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  16680. // sampling a textureCube (not generally normalized ).
  16681. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  16682. const absDirection = vec3( abs( direction ) ).toVar();
  16683. const face = float( -1 ).toVar();
  16684. If( absDirection.x.greaterThan( absDirection.z ), () => {
  16685. If( absDirection.x.greaterThan( absDirection.y ), () => {
  16686. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  16687. } ).Else( () => {
  16688. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  16689. } );
  16690. } ).Else( () => {
  16691. If( absDirection.z.greaterThan( absDirection.y ), () => {
  16692. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  16693. } ).Else( () => {
  16694. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  16695. } );
  16696. } );
  16697. return face;
  16698. } ).setLayout( {
  16699. name: 'getFace',
  16700. type: 'float',
  16701. inputs: [
  16702. { name: 'direction', type: 'vec3' }
  16703. ]
  16704. } );
  16705. // RH coordinate system; PMREM face-indexing convention
  16706. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  16707. const uv = vec2().toVar();
  16708. If( face.equal( 0.0 ), () => {
  16709. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  16710. } ).ElseIf( face.equal( 1.0 ), () => {
  16711. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  16712. } ).ElseIf( face.equal( 2.0 ), () => {
  16713. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  16714. } ).ElseIf( face.equal( 3.0 ), () => {
  16715. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  16716. } ).ElseIf( face.equal( 4.0 ), () => {
  16717. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  16718. } ).Else( () => {
  16719. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  16720. } );
  16721. return mul( 0.5, uv.add( 1.0 ) );
  16722. } ).setLayout( {
  16723. name: 'getUV',
  16724. type: 'vec2',
  16725. inputs: [
  16726. { name: 'direction', type: 'vec3' },
  16727. { name: 'face', type: 'float' }
  16728. ]
  16729. } );
  16730. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  16731. const mip = float( 0.0 ).toVar();
  16732. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  16733. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  16734. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  16735. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  16736. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  16737. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  16738. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  16739. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  16740. } ).Else( () => {
  16741. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  16742. } );
  16743. return mip;
  16744. } ).setLayout( {
  16745. name: 'roughnessToMip',
  16746. type: 'float',
  16747. inputs: [
  16748. { name: 'roughness', type: 'float' }
  16749. ]
  16750. } );
  16751. // RH coordinate system; PMREM face-indexing convention
  16752. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  16753. const uv = uv_immutable.toVar();
  16754. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  16755. const direction = vec3( uv, 1.0 ).toVar();
  16756. If( face.equal( 0.0 ), () => {
  16757. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  16758. } ).ElseIf( face.equal( 1.0 ), () => {
  16759. direction.assign( direction.xzy );
  16760. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  16761. } ).ElseIf( face.equal( 2.0 ), () => {
  16762. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  16763. } ).ElseIf( face.equal( 3.0 ), () => {
  16764. direction.assign( direction.zyx );
  16765. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  16766. } ).ElseIf( face.equal( 4.0 ), () => {
  16767. direction.assign( direction.xzy );
  16768. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  16769. } ).ElseIf( face.equal( 5.0 ), () => {
  16770. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  16771. } );
  16772. return direction;
  16773. } ).setLayout( {
  16774. name: 'getDirection',
  16775. type: 'vec3',
  16776. inputs: [
  16777. { name: 'uv', type: 'vec2' },
  16778. { name: 'face', type: 'float' }
  16779. ]
  16780. } );
  16781. //
  16782. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16783. const roughness = float( roughness_immutable );
  16784. const sampleDir = vec3( sampleDir_immutable );
  16785. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  16786. const mipF = fract( mip );
  16787. const mipInt = floor( mip );
  16788. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16789. If( mipF.notEqual( 0.0 ), () => {
  16790. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16791. color0.assign( mix( color0, color1, mipF ) );
  16792. } );
  16793. return color0;
  16794. } );
  16795. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16796. const mipInt = float( mipInt_immutable ).toVar();
  16797. const direction = vec3( direction_immutable );
  16798. const face = float( getFace( direction ) ).toVar();
  16799. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  16800. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  16801. const faceSize = float( exp2( mipInt ) ).toVar();
  16802. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  16803. If( face.greaterThan( 2.0 ), () => {
  16804. uv.y.addAssign( faceSize );
  16805. face.subAssign( 3.0 );
  16806. } );
  16807. uv.x.addAssign( face.mul( faceSize ) );
  16808. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  16809. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  16810. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  16811. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  16812. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  16813. } );
  16814. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16815. const cosTheta = cos( theta );
  16816. // Rodrigues' axis-angle rotation
  16817. const sampleDirection = outputDirection.mul( cosTheta )
  16818. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  16819. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  16820. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  16821. } );
  16822. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16823. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  16824. If( axis.equal( vec3( 0.0 ) ), () => {
  16825. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  16826. } );
  16827. axis.assign( normalize( axis ) );
  16828. const gl_FragColor = vec3().toVar();
  16829. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  16830. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  16831. If( i.greaterThanEqual( samples ), () => {
  16832. Break();
  16833. } );
  16834. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  16835. 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 } ) ) );
  16836. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  16837. } );
  16838. return vec4( gl_FragColor, 1 );
  16839. } );
  16840. const LOD_MIN = 4;
  16841. // The standard deviations (radians) associated with the extra mips. These are
  16842. // chosen to approximate a Trowbridge-Reitz distribution function times the
  16843. // geometric shadowing function. These sigma values squared must match the
  16844. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  16845. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  16846. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  16847. // samples and exit early, but not recompile the shader.
  16848. const MAX_SAMPLES = 20;
  16849. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  16850. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  16851. const _clearColor$2 = /*@__PURE__*/ new Color();
  16852. let _oldTarget = null;
  16853. let _oldActiveCubeFace = 0;
  16854. let _oldActiveMipmapLevel = 0;
  16855. // Golden Ratio
  16856. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  16857. const INV_PHI = 1 / PHI;
  16858. // Vertices of a dodecahedron (except the opposites, which represent the
  16859. // same axis), used as axis directions evenly spread on a sphere.
  16860. const _axisDirections = [
  16861. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  16862. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  16863. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  16864. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  16865. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  16866. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  16867. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  16868. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  16869. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  16870. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  16871. ];
  16872. const _origin = /*@__PURE__*/ new Vector3();
  16873. // maps blur materials to their uniforms dictionary
  16874. const _uniformsMap = new WeakMap();
  16875. // WebGPU Face indices
  16876. const _faceLib = [
  16877. 3, 1, 5,
  16878. 0, 4, 2
  16879. ];
  16880. const _direction = /*@__PURE__*/ getDirection( uv$1(), attribute( 'faceIndex' ) ).normalize();
  16881. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  16882. /**
  16883. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  16884. * (PMREM) from a cubeMap environment texture. This allows different levels of
  16885. * blur to be quickly accessed based on material roughness. It is packed into a
  16886. * special CubeUV format that allows us to perform custom interpolation so that
  16887. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  16888. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  16889. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  16890. * higher roughness levels. In this way we maintain resolution to smoothly
  16891. * interpolate diffuse lighting while limiting sampling computation.
  16892. *
  16893. * Paper: Fast, Accurate Image-Based Lighting:
  16894. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  16895. */
  16896. class PMREMGenerator {
  16897. /**
  16898. * Constructs a new PMREM generator.
  16899. *
  16900. * @param {Renderer} renderer - The renderer.
  16901. */
  16902. constructor( renderer ) {
  16903. this._renderer = renderer;
  16904. this._pingPongRenderTarget = null;
  16905. this._lodMax = 0;
  16906. this._cubeSize = 0;
  16907. this._lodPlanes = [];
  16908. this._sizeLods = [];
  16909. this._sigmas = [];
  16910. this._lodMeshes = [];
  16911. this._blurMaterial = null;
  16912. this._cubemapMaterial = null;
  16913. this._equirectMaterial = null;
  16914. this._backgroundBox = null;
  16915. }
  16916. get _hasInitialized() {
  16917. return this._renderer.hasInitialized();
  16918. }
  16919. /**
  16920. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16921. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16922. * in radians to be applied to the scene before PMREM generation. Optional near
  16923. * and far planes ensure the scene is rendered in its entirety.
  16924. *
  16925. * @param {Scene} scene - The scene to be captured.
  16926. * @param {number} [sigma=0] - The blur radius in radians.
  16927. * @param {number} [near=0.1] - The near plane distance.
  16928. * @param {number} [far=100] - The far plane distance.
  16929. * @param {Object} [options={}] - The configuration options.
  16930. * @param {number} [options.size=256] - The texture size of the PMREM.
  16931. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  16932. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16933. * @return {RenderTarget} The resulting PMREM.
  16934. * @see {@link PMREMGenerator#fromSceneAsync}
  16935. */
  16936. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16937. const {
  16938. size = 256,
  16939. position = _origin,
  16940. renderTarget = null,
  16941. } = options;
  16942. this._setSize( size );
  16943. if ( this._hasInitialized === false ) {
  16944. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  16945. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16946. options.renderTarget = cubeUVRenderTarget;
  16947. this.fromSceneAsync( scene, sigma, near, far, options );
  16948. return cubeUVRenderTarget;
  16949. }
  16950. _oldTarget = this._renderer.getRenderTarget();
  16951. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16952. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16953. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16954. cubeUVRenderTarget.depthBuffer = true;
  16955. this._init( cubeUVRenderTarget );
  16956. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  16957. if ( sigma > 0 ) {
  16958. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  16959. }
  16960. this._applyPMREM( cubeUVRenderTarget );
  16961. this._cleanup( cubeUVRenderTarget );
  16962. return cubeUVRenderTarget;
  16963. }
  16964. /**
  16965. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16966. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16967. * in radians to be applied to the scene before PMREM generation. Optional near
  16968. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  16969. * is placed at the origin).
  16970. *
  16971. * @param {Scene} scene - The scene to be captured.
  16972. * @param {number} [sigma=0] - The blur radius in radians.
  16973. * @param {number} [near=0.1] - The near plane distance.
  16974. * @param {number} [far=100] - The far plane distance.
  16975. * @param {Object} [options={}] - The configuration options.
  16976. * @param {number} [options.size=256] - The texture size of the PMREM.
  16977. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  16978. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16979. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  16980. * @see {@link PMREMGenerator#fromScene}
  16981. */
  16982. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16983. if ( this._hasInitialized === false ) await this._renderer.init();
  16984. return this.fromScene( scene, sigma, near, far, options );
  16985. }
  16986. /**
  16987. * Generates a PMREM from an equirectangular texture, which can be either LDR
  16988. * or HDR. The ideal input image size is 1k (1024 x 512),
  16989. * as this matches best with the 256 x 256 cubemap output.
  16990. *
  16991. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  16992. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16993. * @return {RenderTarget} The resulting PMREM.
  16994. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  16995. */
  16996. fromEquirectangular( equirectangular, renderTarget = null ) {
  16997. if ( this._hasInitialized === false ) {
  16998. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  16999. this._setSizeFromTexture( equirectangular );
  17000. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17001. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  17002. return cubeUVRenderTarget;
  17003. }
  17004. return this._fromTexture( equirectangular, renderTarget );
  17005. }
  17006. /**
  17007. * Generates a PMREM from an equirectangular texture, which can be either LDR
  17008. * or HDR. The ideal input image size is 1k (1024 x 512),
  17009. * as this matches best with the 256 x 256 cubemap output.
  17010. *
  17011. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  17012. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17013. * @return {Promise<RenderTarget>} The resulting PMREM.
  17014. * @see {@link PMREMGenerator#fromEquirectangular}
  17015. */
  17016. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  17017. if ( this._hasInitialized === false ) await this._renderer.init();
  17018. return this._fromTexture( equirectangular, renderTarget );
  17019. }
  17020. /**
  17021. * Generates a PMREM from an cubemap texture, which can be either LDR
  17022. * or HDR. The ideal input cube size is 256 x 256,
  17023. * as this matches best with the 256 x 256 cubemap output.
  17024. *
  17025. * @param {Texture} cubemap - The cubemap texture to be converted.
  17026. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17027. * @return {RenderTarget} The resulting PMREM.
  17028. * @see {@link PMREMGenerator#fromCubemapAsync}
  17029. */
  17030. fromCubemap( cubemap, renderTarget = null ) {
  17031. if ( this._hasInitialized === false ) {
  17032. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  17033. this._setSizeFromTexture( cubemap );
  17034. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17035. this.fromCubemapAsync( cubemap, renderTarget );
  17036. return cubeUVRenderTarget;
  17037. }
  17038. return this._fromTexture( cubemap, renderTarget );
  17039. }
  17040. /**
  17041. * Generates a PMREM from an cubemap texture, which can be either LDR
  17042. * or HDR. The ideal input cube size is 256 x 256,
  17043. * with the 256 x 256 cubemap output.
  17044. *
  17045. * @param {Texture} cubemap - The cubemap texture to be converted.
  17046. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  17047. * @return {Promise<RenderTarget>} The resulting PMREM.
  17048. * @see {@link PMREMGenerator#fromCubemap}
  17049. */
  17050. async fromCubemapAsync( cubemap, renderTarget = null ) {
  17051. if ( this._hasInitialized === false ) await this._renderer.init();
  17052. return this._fromTexture( cubemap, renderTarget );
  17053. }
  17054. /**
  17055. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  17056. * your texture's network fetch for increased concurrency.
  17057. *
  17058. * @returns {Promise}
  17059. */
  17060. async compileCubemapShader() {
  17061. if ( this._cubemapMaterial === null ) {
  17062. this._cubemapMaterial = _getCubemapMaterial();
  17063. await this._compileMaterial( this._cubemapMaterial );
  17064. }
  17065. }
  17066. /**
  17067. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  17068. * your texture's network fetch for increased concurrency.
  17069. *
  17070. * @returns {Promise}
  17071. */
  17072. async compileEquirectangularShader() {
  17073. if ( this._equirectMaterial === null ) {
  17074. this._equirectMaterial = _getEquirectMaterial();
  17075. await this._compileMaterial( this._equirectMaterial );
  17076. }
  17077. }
  17078. /**
  17079. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  17080. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  17081. * one of them will cause any others to also become unusable.
  17082. */
  17083. dispose() {
  17084. this._dispose();
  17085. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  17086. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  17087. if ( this._backgroundBox !== null ) {
  17088. this._backgroundBox.geometry.dispose();
  17089. this._backgroundBox.material.dispose();
  17090. }
  17091. }
  17092. // private interface
  17093. _setSizeFromTexture( texture ) {
  17094. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  17095. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  17096. } else { // Equirectangular
  17097. this._setSize( texture.image.width / 4 );
  17098. }
  17099. }
  17100. _setSize( cubeSize ) {
  17101. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  17102. this._cubeSize = Math.pow( 2, this._lodMax );
  17103. }
  17104. _dispose() {
  17105. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  17106. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  17107. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  17108. this._lodPlanes[ i ].dispose();
  17109. }
  17110. }
  17111. _cleanup( outputTarget ) {
  17112. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  17113. outputTarget.scissorTest = false;
  17114. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  17115. }
  17116. _fromTexture( texture, renderTarget ) {
  17117. this._setSizeFromTexture( texture );
  17118. _oldTarget = this._renderer.getRenderTarget();
  17119. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  17120. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  17121. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  17122. this._init( cubeUVRenderTarget );
  17123. this._textureToCubeUV( texture, cubeUVRenderTarget );
  17124. this._applyPMREM( cubeUVRenderTarget );
  17125. this._cleanup( cubeUVRenderTarget );
  17126. return cubeUVRenderTarget;
  17127. }
  17128. _allocateTarget() {
  17129. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  17130. const height = 4 * this._cubeSize;
  17131. const cubeUVRenderTarget = _createRenderTarget( width, height );
  17132. return cubeUVRenderTarget;
  17133. }
  17134. _init( renderTarget ) {
  17135. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  17136. if ( this._pingPongRenderTarget !== null ) {
  17137. this._dispose();
  17138. }
  17139. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  17140. const { _lodMax } = this;
  17141. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  17142. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  17143. }
  17144. }
  17145. async _compileMaterial( material ) {
  17146. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  17147. await this._renderer.compile( tmpMesh, _flatCamera );
  17148. }
  17149. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  17150. const cubeCamera = _cubeCamera;
  17151. cubeCamera.near = near;
  17152. cubeCamera.far = far;
  17153. // px, py, pz, nx, ny, nz
  17154. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  17155. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  17156. const renderer = this._renderer;
  17157. const originalAutoClear = renderer.autoClear;
  17158. renderer.getClearColor( _clearColor$2 );
  17159. renderer.autoClear = false;
  17160. let backgroundBox = this._backgroundBox;
  17161. if ( backgroundBox === null ) {
  17162. const backgroundMaterial = new MeshBasicMaterial( {
  17163. name: 'PMREM.Background',
  17164. side: BackSide,
  17165. depthWrite: false,
  17166. depthTest: false
  17167. } );
  17168. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  17169. }
  17170. let useSolidColor = false;
  17171. const background = scene.background;
  17172. if ( background ) {
  17173. if ( background.isColor ) {
  17174. backgroundBox.material.color.copy( background );
  17175. scene.background = null;
  17176. useSolidColor = true;
  17177. }
  17178. } else {
  17179. backgroundBox.material.color.copy( _clearColor$2 );
  17180. useSolidColor = true;
  17181. }
  17182. renderer.setRenderTarget( cubeUVRenderTarget );
  17183. renderer.clear();
  17184. if ( useSolidColor ) {
  17185. renderer.render( backgroundBox, cubeCamera );
  17186. }
  17187. for ( let i = 0; i < 6; i ++ ) {
  17188. const col = i % 3;
  17189. if ( col === 0 ) {
  17190. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17191. cubeCamera.position.set( position.x, position.y, position.z );
  17192. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  17193. } else if ( col === 1 ) {
  17194. cubeCamera.up.set( 0, 0, upSign[ i ] );
  17195. cubeCamera.position.set( position.x, position.y, position.z );
  17196. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  17197. } else {
  17198. cubeCamera.up.set( 0, upSign[ i ], 0 );
  17199. cubeCamera.position.set( position.x, position.y, position.z );
  17200. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  17201. }
  17202. const size = this._cubeSize;
  17203. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  17204. renderer.render( scene, cubeCamera );
  17205. }
  17206. renderer.autoClear = originalAutoClear;
  17207. scene.background = background;
  17208. }
  17209. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  17210. const renderer = this._renderer;
  17211. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  17212. if ( isCubeTexture ) {
  17213. if ( this._cubemapMaterial === null ) {
  17214. this._cubemapMaterial = _getCubemapMaterial( texture );
  17215. }
  17216. } else {
  17217. if ( this._equirectMaterial === null ) {
  17218. this._equirectMaterial = _getEquirectMaterial( texture );
  17219. }
  17220. }
  17221. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  17222. material.fragmentNode.value = texture;
  17223. const mesh = this._lodMeshes[ 0 ];
  17224. mesh.material = material;
  17225. const size = this._cubeSize;
  17226. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  17227. renderer.setRenderTarget( cubeUVRenderTarget );
  17228. renderer.render( mesh, _flatCamera );
  17229. }
  17230. _applyPMREM( cubeUVRenderTarget ) {
  17231. const renderer = this._renderer;
  17232. const autoClear = renderer.autoClear;
  17233. renderer.autoClear = false;
  17234. const n = this._lodPlanes.length;
  17235. for ( let i = 1; i < n; i ++ ) {
  17236. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  17237. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  17238. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  17239. }
  17240. renderer.autoClear = autoClear;
  17241. }
  17242. /**
  17243. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  17244. * vertically and horizontally, but this breaks down on a cube. Here we apply
  17245. * the blur latitudinally (around the poles), and then longitudinally (towards
  17246. * the poles) to approximate the orthogonally-separable blur. It is least
  17247. * accurate at the poles, but still does a decent job.
  17248. *
  17249. * @private
  17250. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  17251. * @param {number} lodIn - The input level-of-detail.
  17252. * @param {number} lodOut - The output level-of-detail.
  17253. * @param {number} sigma - The blur radius in radians.
  17254. * @param {Vector3} [poleAxis] - The pole axis.
  17255. */
  17256. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  17257. const pingPongRenderTarget = this._pingPongRenderTarget;
  17258. this._halfBlur(
  17259. cubeUVRenderTarget,
  17260. pingPongRenderTarget,
  17261. lodIn,
  17262. lodOut,
  17263. sigma,
  17264. 'latitudinal',
  17265. poleAxis );
  17266. this._halfBlur(
  17267. pingPongRenderTarget,
  17268. cubeUVRenderTarget,
  17269. lodOut,
  17270. lodOut,
  17271. sigma,
  17272. 'longitudinal',
  17273. poleAxis );
  17274. }
  17275. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  17276. const renderer = this._renderer;
  17277. const blurMaterial = this._blurMaterial;
  17278. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  17279. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  17280. }
  17281. // Number of standard deviations at which to cut off the discrete approximation.
  17282. const STANDARD_DEVIATIONS = 3;
  17283. const blurMesh = this._lodMeshes[ lodOut ];
  17284. blurMesh.material = blurMaterial;
  17285. const blurUniforms = _uniformsMap.get( blurMaterial );
  17286. const pixels = this._sizeLods[ lodIn ] - 1;
  17287. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  17288. const sigmaPixels = sigmaRadians / radiansPerPixel;
  17289. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  17290. if ( samples > MAX_SAMPLES ) {
  17291. console.warn( `sigmaRadians, ${
  17292. sigmaRadians}, is too large and will clip, as it requested ${
  17293. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  17294. }
  17295. const weights = [];
  17296. let sum = 0;
  17297. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  17298. const x = i / sigmaPixels;
  17299. const weight = Math.exp( - x * x / 2 );
  17300. weights.push( weight );
  17301. if ( i === 0 ) {
  17302. sum += weight;
  17303. } else if ( i < samples ) {
  17304. sum += 2 * weight;
  17305. }
  17306. }
  17307. for ( let i = 0; i < weights.length; i ++ ) {
  17308. weights[ i ] = weights[ i ] / sum;
  17309. }
  17310. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  17311. blurUniforms.envMap.value = targetIn.texture;
  17312. blurUniforms.samples.value = samples;
  17313. blurUniforms.weights.array = weights;
  17314. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  17315. if ( poleAxis ) {
  17316. blurUniforms.poleAxis.value = poleAxis;
  17317. }
  17318. const { _lodMax } = this;
  17319. blurUniforms.dTheta.value = radiansPerPixel;
  17320. blurUniforms.mipInt.value = _lodMax - lodIn;
  17321. const outputSize = this._sizeLods[ lodOut ];
  17322. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  17323. const y = 4 * ( this._cubeSize - outputSize );
  17324. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  17325. renderer.setRenderTarget( targetOut );
  17326. renderer.render( blurMesh, _flatCamera );
  17327. }
  17328. }
  17329. function _createPlanes( lodMax ) {
  17330. const lodPlanes = [];
  17331. const sizeLods = [];
  17332. const sigmas = [];
  17333. const lodMeshes = [];
  17334. let lod = lodMax;
  17335. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  17336. for ( let i = 0; i < totalLods; i ++ ) {
  17337. const sizeLod = Math.pow( 2, lod );
  17338. sizeLods.push( sizeLod );
  17339. let sigma = 1.0 / sizeLod;
  17340. if ( i > lodMax - LOD_MIN ) {
  17341. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  17342. } else if ( i === 0 ) {
  17343. sigma = 0;
  17344. }
  17345. sigmas.push( sigma );
  17346. const texelSize = 1.0 / ( sizeLod - 2 );
  17347. const min = - texelSize;
  17348. const max = 1 + texelSize;
  17349. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  17350. const cubeFaces = 6;
  17351. const vertices = 6;
  17352. const positionSize = 3;
  17353. const uvSize = 2;
  17354. const faceIndexSize = 1;
  17355. const position = new Float32Array( positionSize * vertices * cubeFaces );
  17356. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  17357. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  17358. for ( let face = 0; face < cubeFaces; face ++ ) {
  17359. const x = ( face % 3 ) * 2 / 3 - 1;
  17360. const y = face > 2 ? 0 : -1;
  17361. const coordinates = [
  17362. x, y, 0,
  17363. x + 2 / 3, y, 0,
  17364. x + 2 / 3, y + 1, 0,
  17365. x, y, 0,
  17366. x + 2 / 3, y + 1, 0,
  17367. x, y + 1, 0
  17368. ];
  17369. const faceIdx = _faceLib[ face ];
  17370. position.set( coordinates, positionSize * vertices * faceIdx );
  17371. uv.set( uv1, uvSize * vertices * faceIdx );
  17372. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  17373. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  17374. }
  17375. const planes = new BufferGeometry();
  17376. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  17377. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  17378. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  17379. lodPlanes.push( planes );
  17380. lodMeshes.push( new Mesh( planes, null ) );
  17381. if ( lod > LOD_MIN ) {
  17382. lod --;
  17383. }
  17384. }
  17385. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  17386. }
  17387. function _createRenderTarget( width, height ) {
  17388. const params = {
  17389. magFilter: LinearFilter,
  17390. minFilter: LinearFilter,
  17391. generateMipmaps: false,
  17392. type: HalfFloatType,
  17393. format: RGBAFormat,
  17394. colorSpace: LinearSRGBColorSpace,
  17395. //depthBuffer: false
  17396. };
  17397. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  17398. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  17399. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  17400. cubeUVRenderTarget.texture.isPMREMTexture = true;
  17401. cubeUVRenderTarget.scissorTest = true;
  17402. return cubeUVRenderTarget;
  17403. }
  17404. function _setViewport( target, x, y, width, height ) {
  17405. target.viewport.set( x, y, width, height );
  17406. target.scissor.set( x, y, width, height );
  17407. }
  17408. function _getMaterial( type ) {
  17409. const material = new NodeMaterial();
  17410. material.depthTest = false;
  17411. material.depthWrite = false;
  17412. material.blending = NoBlending;
  17413. material.name = `PMREM_${ type }`;
  17414. return material;
  17415. }
  17416. function _getBlurShader( lodMax, width, height ) {
  17417. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  17418. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  17419. const dTheta = uniform( 0 );
  17420. const n = float( MAX_SAMPLES );
  17421. const latitudinal = uniform( 0 ); // false, bool
  17422. const samples = uniform( 1 ); // int
  17423. const envMap = texture( null );
  17424. const mipInt = uniform( 0 ); // int
  17425. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  17426. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  17427. const CUBEUV_MAX_MIP = float( lodMax );
  17428. const materialUniforms = {
  17429. n,
  17430. latitudinal,
  17431. weights,
  17432. poleAxis,
  17433. outputDirection: _outputDirection,
  17434. dTheta,
  17435. samples,
  17436. envMap,
  17437. mipInt,
  17438. CUBEUV_TEXEL_WIDTH,
  17439. CUBEUV_TEXEL_HEIGHT,
  17440. CUBEUV_MAX_MIP
  17441. };
  17442. const material = _getMaterial( 'blur' );
  17443. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  17444. _uniformsMap.set( material, materialUniforms );
  17445. return material;
  17446. }
  17447. function _getCubemapMaterial( envTexture ) {
  17448. const material = _getMaterial( 'cubemap' );
  17449. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  17450. return material;
  17451. }
  17452. function _getEquirectMaterial( envTexture ) {
  17453. const material = _getMaterial( 'equirect' );
  17454. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  17455. return material;
  17456. }
  17457. const _cache = new WeakMap();
  17458. /**
  17459. * Generates the cubeUV size based on the given image height.
  17460. *
  17461. * @private
  17462. * @param {number} imageHeight - The image height.
  17463. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  17464. */
  17465. function _generateCubeUVSize( imageHeight ) {
  17466. const maxMip = Math.log2( imageHeight ) - 2;
  17467. const texelHeight = 1.0 / imageHeight;
  17468. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  17469. return { texelWidth, texelHeight, maxMip };
  17470. }
  17471. /**
  17472. * Generates a PMREM from the given texture.
  17473. *
  17474. * @private
  17475. * @param {Texture} texture - The texture to create the PMREM for.
  17476. * @param {Renderer} renderer - The renderer.
  17477. * @param {PMREMGenerator} generator - The PMREM generator.
  17478. * @return {?Texture} The PMREM.
  17479. */
  17480. function _getPMREMFromTexture( texture, renderer, generator ) {
  17481. const cache = _getCache( renderer );
  17482. let cacheTexture = cache.get( texture );
  17483. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  17484. if ( pmremVersion !== texture.pmremVersion ) {
  17485. const image = texture.image;
  17486. if ( texture.isCubeTexture ) {
  17487. if ( isCubeMapReady( image ) ) {
  17488. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  17489. } else {
  17490. return null;
  17491. }
  17492. } else {
  17493. if ( isEquirectangularMapReady( image ) ) {
  17494. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  17495. } else {
  17496. return null;
  17497. }
  17498. }
  17499. cacheTexture.pmremVersion = texture.pmremVersion;
  17500. cache.set( texture, cacheTexture );
  17501. }
  17502. return cacheTexture.texture;
  17503. }
  17504. /**
  17505. * Returns a cache that stores generated PMREMs for the respective textures.
  17506. * A cache must be maintained per renderer since PMREMs are render target textures
  17507. * which can't be shared across render contexts.
  17508. *
  17509. * @private
  17510. * @param {Renderer} renderer - The renderer.
  17511. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  17512. */
  17513. function _getCache( renderer ) {
  17514. let rendererCache = _cache.get( renderer );
  17515. if ( rendererCache === undefined ) {
  17516. rendererCache = new WeakMap();
  17517. _cache.set( renderer, rendererCache );
  17518. }
  17519. return rendererCache;
  17520. }
  17521. /**
  17522. * This node represents a PMREM which is a special type of preprocessed
  17523. * environment map intended for PBR materials.
  17524. *
  17525. * ```js
  17526. * const material = new MeshStandardNodeMaterial();
  17527. * material.envNode = pmremTexture( envMap );
  17528. * ```
  17529. *
  17530. * @augments TempNode
  17531. */
  17532. class PMREMNode extends TempNode {
  17533. static get type() {
  17534. return 'PMREMNode';
  17535. }
  17536. /**
  17537. * Constructs a new function overloading node.
  17538. *
  17539. * @param {Texture} value - The input texture.
  17540. * @param {Node<vec2>} [uvNode=null] - The uv node.
  17541. * @param {Node<float>} [levelNode=null] - The level node.
  17542. */
  17543. constructor( value, uvNode = null, levelNode = null ) {
  17544. super( 'vec3' );
  17545. /**
  17546. * Reference to the input texture.
  17547. *
  17548. * @private
  17549. * @type {Texture}
  17550. */
  17551. this._value = value;
  17552. /**
  17553. * Reference to the generated PMREM.
  17554. *
  17555. * @private
  17556. * @type {Texture | null}
  17557. * @default null
  17558. */
  17559. this._pmrem = null;
  17560. /**
  17561. * The uv node.
  17562. *
  17563. * @type {Node<vec2>}
  17564. */
  17565. this.uvNode = uvNode;
  17566. /**
  17567. * The level node.
  17568. *
  17569. * @type {Node<float>}
  17570. */
  17571. this.levelNode = levelNode;
  17572. /**
  17573. * Reference to a PMREM generator.
  17574. *
  17575. * @private
  17576. * @type {?PMREMGenerator}
  17577. * @default null
  17578. */
  17579. this._generator = null;
  17580. const defaultTexture = new Texture();
  17581. defaultTexture.isRenderTargetTexture = true;
  17582. /**
  17583. * The texture node holding the generated PMREM.
  17584. *
  17585. * @private
  17586. * @type {TextureNode}
  17587. */
  17588. this._texture = texture( defaultTexture );
  17589. /**
  17590. * A uniform representing the PMREM's width.
  17591. *
  17592. * @private
  17593. * @type {UniformNode<float>}
  17594. */
  17595. this._width = uniform( 0 );
  17596. /**
  17597. * A uniform representing the PMREM's height.
  17598. *
  17599. * @private
  17600. * @type {UniformNode<float>}
  17601. */
  17602. this._height = uniform( 0 );
  17603. /**
  17604. * A uniform representing the PMREM's max Mip.
  17605. *
  17606. * @private
  17607. * @type {UniformNode<float>}
  17608. */
  17609. this._maxMip = uniform( 0 );
  17610. /**
  17611. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  17612. *
  17613. * @type {string}
  17614. * @default 'render'
  17615. */
  17616. this.updateBeforeType = NodeUpdateType.RENDER;
  17617. }
  17618. set value( value ) {
  17619. this._value = value;
  17620. this._pmrem = null;
  17621. }
  17622. /**
  17623. * The node's texture value.
  17624. *
  17625. * @type {Texture}
  17626. */
  17627. get value() {
  17628. return this._value;
  17629. }
  17630. /**
  17631. * Uses the given PMREM texture to update internal values.
  17632. *
  17633. * @param {Texture} texture - The PMREM texture.
  17634. */
  17635. updateFromTexture( texture ) {
  17636. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  17637. this._texture.value = texture;
  17638. this._width.value = cubeUVSize.texelWidth;
  17639. this._height.value = cubeUVSize.texelHeight;
  17640. this._maxMip.value = cubeUVSize.maxMip;
  17641. }
  17642. updateBefore( frame ) {
  17643. let pmrem = this._pmrem;
  17644. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  17645. const texture = this._value;
  17646. if ( pmremVersion !== texture.pmremVersion ) {
  17647. if ( texture.isPMREMTexture === true ) {
  17648. pmrem = texture;
  17649. } else {
  17650. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  17651. }
  17652. if ( pmrem !== null ) {
  17653. this._pmrem = pmrem;
  17654. this.updateFromTexture( pmrem );
  17655. }
  17656. }
  17657. }
  17658. setup( builder ) {
  17659. if ( this._generator === null ) {
  17660. this._generator = new PMREMGenerator( builder.renderer );
  17661. }
  17662. this.updateBefore( builder );
  17663. //
  17664. let uvNode = this.uvNode;
  17665. if ( uvNode === null && builder.context.getUV ) {
  17666. uvNode = builder.context.getUV( this );
  17667. }
  17668. //
  17669. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  17670. //
  17671. let levelNode = this.levelNode;
  17672. if ( levelNode === null && builder.context.getTextureLevel ) {
  17673. levelNode = builder.context.getTextureLevel( this );
  17674. }
  17675. //
  17676. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  17677. }
  17678. dispose() {
  17679. super.dispose();
  17680. if ( this._generator !== null ) this._generator.dispose();
  17681. }
  17682. }
  17683. /**
  17684. * Returns `true` if the given cube map image has been fully loaded.
  17685. *
  17686. * @private
  17687. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  17688. * @return {boolean} Whether the given cube map is ready or not.
  17689. */
  17690. function isCubeMapReady( image ) {
  17691. if ( image === null || image === undefined ) return false;
  17692. let count = 0;
  17693. const length = 6;
  17694. for ( let i = 0; i < length; i ++ ) {
  17695. if ( image[ i ] !== undefined ) count ++;
  17696. }
  17697. return count === length;
  17698. }
  17699. /**
  17700. * Returns `true` if the given equirectangular image has been fully loaded.
  17701. *
  17702. * @private
  17703. * @param {(Image|Object)} image - The equirectangular image.
  17704. * @return {boolean} Whether the given cube map is ready or not.
  17705. */
  17706. function isEquirectangularMapReady( image ) {
  17707. if ( image === null || image === undefined ) return false;
  17708. return image.height > 0;
  17709. }
  17710. /**
  17711. * TSL function for creating a PMREM node.
  17712. *
  17713. * @tsl
  17714. * @function
  17715. * @param {Texture} value - The input texture.
  17716. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  17717. * @param {?Node<float>} [levelNode=null] - The level node.
  17718. * @returns {PMREMNode}
  17719. */
  17720. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  17721. const _envNodeCache = new WeakMap();
  17722. /**
  17723. * Represents a physical model for Image-based lighting (IBL). The environment
  17724. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  17725. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  17726. *
  17727. * @augments LightingNode
  17728. */
  17729. class EnvironmentNode extends LightingNode {
  17730. static get type() {
  17731. return 'EnvironmentNode';
  17732. }
  17733. /**
  17734. * Constructs a new environment node.
  17735. *
  17736. * @param {Node} [envNode=null] - A node representing the environment.
  17737. */
  17738. constructor( envNode = null ) {
  17739. super();
  17740. /**
  17741. * A node representing the environment.
  17742. *
  17743. * @type {?Node}
  17744. * @default null
  17745. */
  17746. this.envNode = envNode;
  17747. }
  17748. setup( builder ) {
  17749. const { material } = builder;
  17750. let envNode = this.envNode;
  17751. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  17752. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  17753. let cacheEnvNode = _envNodeCache.get( value );
  17754. if ( cacheEnvNode === undefined ) {
  17755. cacheEnvNode = pmremTexture( value );
  17756. _envNodeCache.set( value, cacheEnvNode );
  17757. }
  17758. envNode = cacheEnvNode;
  17759. }
  17760. //
  17761. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  17762. const radianceNormalView = useAnisotropy ? bentNormalView : normalView;
  17763. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  17764. const irradiance = envNode.context( createIrradianceContext( normalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  17765. const isolateRadiance = cache( radiance );
  17766. const isolateIrradiance = cache( irradiance );
  17767. //
  17768. builder.context.radiance.addAssign( isolateRadiance );
  17769. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  17770. //
  17771. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  17772. if ( clearcoatRadiance ) {
  17773. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, clearcoatNormalView ) ).mul( materialEnvIntensity );
  17774. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  17775. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  17776. }
  17777. }
  17778. }
  17779. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  17780. let reflectVec = null;
  17781. return {
  17782. getUV: () => {
  17783. if ( reflectVec === null ) {
  17784. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  17785. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  17786. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  17787. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  17788. }
  17789. return reflectVec;
  17790. },
  17791. getTextureLevel: () => {
  17792. return roughnessNode;
  17793. }
  17794. };
  17795. };
  17796. const createIrradianceContext = ( normalWorldNode ) => {
  17797. return {
  17798. getUV: () => {
  17799. return normalWorldNode;
  17800. },
  17801. getTextureLevel: () => {
  17802. return float( 1.0 );
  17803. }
  17804. };
  17805. };
  17806. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  17807. /**
  17808. * Node material version of {@link MeshStandardMaterial}.
  17809. *
  17810. * @augments NodeMaterial
  17811. */
  17812. class MeshStandardNodeMaterial extends NodeMaterial {
  17813. static get type() {
  17814. return 'MeshStandardNodeMaterial';
  17815. }
  17816. /**
  17817. * Constructs a new mesh standard node material.
  17818. *
  17819. * @param {Object} [parameters] - The configuration parameter.
  17820. */
  17821. constructor( parameters ) {
  17822. super();
  17823. /**
  17824. * This flag can be used for type testing.
  17825. *
  17826. * @type {boolean}
  17827. * @readonly
  17828. * @default true
  17829. */
  17830. this.isMeshStandardNodeMaterial = true;
  17831. /**
  17832. * Set to `true` because standard materials react on lights.
  17833. *
  17834. * @type {boolean}
  17835. * @default true
  17836. */
  17837. this.lights = true;
  17838. /**
  17839. * The emissive color of standard materials is by default inferred from the `emissive`,
  17840. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  17841. * overwrite the default and define the emissive color with a node instead.
  17842. *
  17843. * If you don't want to overwrite the emissive color but modify the existing
  17844. * value instead, use {@link materialEmissive}.
  17845. *
  17846. * @type {?Node<vec3>}
  17847. * @default null
  17848. */
  17849. this.emissiveNode = null;
  17850. /**
  17851. * The metalness of standard materials is by default inferred from the `metalness`,
  17852. * and `metalnessMap` properties. This node property allows to
  17853. * overwrite the default and define the metalness with a node instead.
  17854. *
  17855. * If you don't want to overwrite the metalness but modify the existing
  17856. * value instead, use {@link materialMetalness}.
  17857. *
  17858. * @type {?Node<float>}
  17859. * @default null
  17860. */
  17861. this.metalnessNode = null;
  17862. /**
  17863. * The roughness of standard materials is by default inferred from the `roughness`,
  17864. * and `roughnessMap` properties. This node property allows to
  17865. * overwrite the default and define the roughness with a node instead.
  17866. *
  17867. * If you don't want to overwrite the roughness but modify the existing
  17868. * value instead, use {@link materialRoughness}.
  17869. *
  17870. * @type {?Node<float>}
  17871. * @default null
  17872. */
  17873. this.roughnessNode = null;
  17874. this.setDefaultValues( _defaultValues$6 );
  17875. this.setValues( parameters );
  17876. }
  17877. /**
  17878. * Overwritten since this type of material uses {@link EnvironmentNode}
  17879. * to implement the PBR (PMREM based) environment mapping. Besides, the
  17880. * method honors `Scene.environment`.
  17881. *
  17882. * @param {NodeBuilder} builder - The current node builder.
  17883. * @return {?EnvironmentNode<vec3>} The environment node.
  17884. */
  17885. setupEnvironment( builder ) {
  17886. let envNode = super.setupEnvironment( builder );
  17887. if ( envNode === null && builder.environmentNode ) {
  17888. envNode = builder.environmentNode;
  17889. }
  17890. return envNode ? new EnvironmentNode( envNode ) : null;
  17891. }
  17892. /**
  17893. * Setups the lighting model.
  17894. *
  17895. * @return {PhysicalLightingModel} The lighting model.
  17896. */
  17897. setupLightingModel( /*builder*/ ) {
  17898. return new PhysicalLightingModel();
  17899. }
  17900. /**
  17901. * Setups the specular related node variables.
  17902. */
  17903. setupSpecular() {
  17904. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  17905. specularColor.assign( specularColorNode );
  17906. specularF90.assign( 1.0 );
  17907. }
  17908. /**
  17909. * Setups the standard specific node variables.
  17910. *
  17911. * @param {NodeBuilder} builder - The current node builder.
  17912. */
  17913. setupVariants() {
  17914. // METALNESS
  17915. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  17916. metalness.assign( metalnessNode );
  17917. // ROUGHNESS
  17918. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  17919. roughnessNode = getRoughness( { roughness: roughnessNode } );
  17920. roughness.assign( roughnessNode );
  17921. // SPECULAR COLOR
  17922. this.setupSpecular();
  17923. // DIFFUSE COLOR
  17924. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  17925. }
  17926. copy( source ) {
  17927. this.emissiveNode = source.emissiveNode;
  17928. this.metalnessNode = source.metalnessNode;
  17929. this.roughnessNode = source.roughnessNode;
  17930. return super.copy( source );
  17931. }
  17932. }
  17933. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  17934. /**
  17935. * Node material version of {@link MeshPhysicalMaterial}.
  17936. *
  17937. * @augments MeshStandardNodeMaterial
  17938. */
  17939. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  17940. static get type() {
  17941. return 'MeshPhysicalNodeMaterial';
  17942. }
  17943. /**
  17944. * Constructs a new mesh physical node material.
  17945. *
  17946. * @param {Object} [parameters] - The configuration parameter.
  17947. */
  17948. constructor( parameters ) {
  17949. super();
  17950. /**
  17951. * This flag can be used for type testing.
  17952. *
  17953. * @type {boolean}
  17954. * @readonly
  17955. * @default true
  17956. */
  17957. this.isMeshPhysicalNodeMaterial = true;
  17958. /**
  17959. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  17960. * and `clearcoatMap` properties. This node property allows to overwrite the default
  17961. * and define the clearcoat with a node instead.
  17962. *
  17963. * If you don't want to overwrite the clearcoat but modify the existing
  17964. * value instead, use {@link materialClearcoat}.
  17965. *
  17966. * @type {?Node<float>}
  17967. * @default null
  17968. */
  17969. this.clearcoatNode = null;
  17970. /**
  17971. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  17972. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  17973. * and define the clearcoat roughness with a node instead.
  17974. *
  17975. * If you don't want to overwrite the clearcoat roughness but modify the existing
  17976. * value instead, use {@link materialClearcoatRoughness}.
  17977. *
  17978. * @type {?Node<float>}
  17979. * @default null
  17980. */
  17981. this.clearcoatRoughnessNode = null;
  17982. /**
  17983. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  17984. * property. This node property allows to overwrite the default
  17985. * and define the clearcoat normal with a node instead.
  17986. *
  17987. * If you don't want to overwrite the clearcoat normal but modify the existing
  17988. * value instead, use {@link materialClearcoatNormal}.
  17989. *
  17990. * @type {?Node<vec3>}
  17991. * @default null
  17992. */
  17993. this.clearcoatNormalNode = null;
  17994. /**
  17995. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  17996. * and `sheenColorMap` properties. This node property allows to overwrite the default
  17997. * and define the sheen with a node instead.
  17998. *
  17999. * If you don't want to overwrite the sheen but modify the existing
  18000. * value instead, use {@link materialSheen}.
  18001. *
  18002. * @type {?Node<vec3>}
  18003. * @default null
  18004. */
  18005. this.sheenNode = null;
  18006. /**
  18007. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  18008. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  18009. * and define the sheen roughness with a node instead.
  18010. *
  18011. * If you don't want to overwrite the sheen roughness but modify the existing
  18012. * value instead, use {@link materialSheenRoughness}.
  18013. *
  18014. * @type {?Node<float>}
  18015. * @default null
  18016. */
  18017. this.sheenRoughnessNode = null;
  18018. /**
  18019. * The iridescence of physical materials is by default inferred from the `iridescence`
  18020. * property. This node property allows to overwrite the default
  18021. * and define the iridescence with a node instead.
  18022. *
  18023. * If you don't want to overwrite the iridescence but modify the existing
  18024. * value instead, use {@link materialIridescence}.
  18025. *
  18026. * @type {?Node<float>}
  18027. * @default null
  18028. */
  18029. this.iridescenceNode = null;
  18030. /**
  18031. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  18032. * property. This node property allows to overwrite the default
  18033. * and define the iridescence IOR with a node instead.
  18034. *
  18035. * If you don't want to overwrite the iridescence IOR but modify the existing
  18036. * value instead, use {@link materialIridescenceIOR}.
  18037. *
  18038. * @type {?Node<float>}
  18039. * @default null
  18040. */
  18041. this.iridescenceIORNode = null;
  18042. /**
  18043. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  18044. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  18045. * and define the iridescence thickness with a node instead.
  18046. *
  18047. * If you don't want to overwrite the iridescence thickness but modify the existing
  18048. * value instead, use {@link materialIridescenceThickness}.
  18049. *
  18050. * @type {?Node<float>}
  18051. * @default null
  18052. */
  18053. this.iridescenceThicknessNode = null;
  18054. /**
  18055. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  18056. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  18057. * and define the specular intensity with a node instead.
  18058. *
  18059. * If you don't want to overwrite the specular intensity but modify the existing
  18060. * value instead, use {@link materialSpecularIntensity}.
  18061. *
  18062. * @type {?Node<float>}
  18063. * @default null
  18064. */
  18065. this.specularIntensityNode = null;
  18066. /**
  18067. * The specular color of physical materials is by default inferred from the `specularColor`
  18068. * and `specularColorMap` properties. This node property allows to overwrite the default
  18069. * and define the specular color with a node instead.
  18070. *
  18071. * If you don't want to overwrite the specular color but modify the existing
  18072. * value instead, use {@link materialSpecularColor}.
  18073. *
  18074. * @type {?Node<vec3>}
  18075. * @default null
  18076. */
  18077. this.specularColorNode = null;
  18078. /**
  18079. * The ior of physical materials is by default inferred from the `ior`
  18080. * property. This node property allows to overwrite the default
  18081. * and define the ior with a node instead.
  18082. *
  18083. * If you don't want to overwrite the ior but modify the existing
  18084. * value instead, use {@link materialIOR}.
  18085. *
  18086. * @type {?Node<float>}
  18087. * @default null
  18088. */
  18089. this.iorNode = null;
  18090. /**
  18091. * The transmission of physical materials is by default inferred from the `transmission` and
  18092. * `transmissionMap` properties. This node property allows to overwrite the default
  18093. * and define the transmission with a node instead.
  18094. *
  18095. * If you don't want to overwrite the transmission but modify the existing
  18096. * value instead, use {@link materialTransmission}.
  18097. *
  18098. * @type {?Node<float>}
  18099. * @default null
  18100. */
  18101. this.transmissionNode = null;
  18102. /**
  18103. * The thickness of physical materials is by default inferred from the `thickness` and
  18104. * `thicknessMap` properties. This node property allows to overwrite the default
  18105. * and define the thickness with a node instead.
  18106. *
  18107. * If you don't want to overwrite the thickness but modify the existing
  18108. * value instead, use {@link materialThickness}.
  18109. *
  18110. * @type {?Node<float>}
  18111. * @default null
  18112. */
  18113. this.thicknessNode = null;
  18114. /**
  18115. * The attenuation distance of physical materials is by default inferred from the
  18116. * `attenuationDistance` property. This node property allows to overwrite the default
  18117. * and define the attenuation distance with a node instead.
  18118. *
  18119. * If you don't want to overwrite the attenuation distance but modify the existing
  18120. * value instead, use {@link materialAttenuationDistance}.
  18121. *
  18122. * @type {?Node<float>}
  18123. * @default null
  18124. */
  18125. this.attenuationDistanceNode = null;
  18126. /**
  18127. * The attenuation color of physical materials is by default inferred from the
  18128. * `attenuationColor` property. This node property allows to overwrite the default
  18129. * and define the attenuation color with a node instead.
  18130. *
  18131. * If you don't want to overwrite the attenuation color but modify the existing
  18132. * value instead, use {@link materialAttenuationColor}.
  18133. *
  18134. * @type {?Node<vec3>}
  18135. * @default null
  18136. */
  18137. this.attenuationColorNode = null;
  18138. /**
  18139. * The dispersion of physical materials is by default inferred from the
  18140. * `dispersion` property. This node property allows to overwrite the default
  18141. * and define the dispersion with a node instead.
  18142. *
  18143. * If you don't want to overwrite the dispersion but modify the existing
  18144. * value instead, use {@link materialDispersion}.
  18145. *
  18146. * @type {?Node<float>}
  18147. * @default null
  18148. */
  18149. this.dispersionNode = null;
  18150. /**
  18151. * The anisotropy of physical materials is by default inferred from the
  18152. * `anisotropy` property. This node property allows to overwrite the default
  18153. * and define the anisotropy with a node instead.
  18154. *
  18155. * If you don't want to overwrite the anisotropy but modify the existing
  18156. * value instead, use {@link materialAnisotropy}.
  18157. *
  18158. * @type {?Node<float>}
  18159. * @default null
  18160. */
  18161. this.anisotropyNode = null;
  18162. this.setDefaultValues( _defaultValues$5 );
  18163. this.setValues( parameters );
  18164. }
  18165. /**
  18166. * Whether the lighting model should use clearcoat or not.
  18167. *
  18168. * @type {boolean}
  18169. * @default true
  18170. */
  18171. get useClearcoat() {
  18172. return this.clearcoat > 0 || this.clearcoatNode !== null;
  18173. }
  18174. /**
  18175. * Whether the lighting model should use iridescence or not.
  18176. *
  18177. * @type {boolean}
  18178. * @default true
  18179. */
  18180. get useIridescence() {
  18181. return this.iridescence > 0 || this.iridescenceNode !== null;
  18182. }
  18183. /**
  18184. * Whether the lighting model should use sheen or not.
  18185. *
  18186. * @type {boolean}
  18187. * @default true
  18188. */
  18189. get useSheen() {
  18190. return this.sheen > 0 || this.sheenNode !== null;
  18191. }
  18192. /**
  18193. * Whether the lighting model should use anisotropy or not.
  18194. *
  18195. * @type {boolean}
  18196. * @default true
  18197. */
  18198. get useAnisotropy() {
  18199. return this.anisotropy > 0 || this.anisotropyNode !== null;
  18200. }
  18201. /**
  18202. * Whether the lighting model should use transmission or not.
  18203. *
  18204. * @type {boolean}
  18205. * @default true
  18206. */
  18207. get useTransmission() {
  18208. return this.transmission > 0 || this.transmissionNode !== null;
  18209. }
  18210. /**
  18211. * Whether the lighting model should use dispersion or not.
  18212. *
  18213. * @type {boolean}
  18214. * @default true
  18215. */
  18216. get useDispersion() {
  18217. return this.dispersion > 0 || this.dispersionNode !== null;
  18218. }
  18219. /**
  18220. * Setups the specular related node variables.
  18221. */
  18222. setupSpecular() {
  18223. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  18224. ior.assign( iorNode );
  18225. 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 ) );
  18226. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  18227. }
  18228. /**
  18229. * Setups the lighting model.
  18230. *
  18231. * @return {PhysicalLightingModel} The lighting model.
  18232. */
  18233. setupLightingModel( /*builder*/ ) {
  18234. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  18235. }
  18236. /**
  18237. * Setups the physical specific node variables.
  18238. *
  18239. * @param {NodeBuilder} builder - The current node builder.
  18240. */
  18241. setupVariants( builder ) {
  18242. super.setupVariants( builder );
  18243. // CLEARCOAT
  18244. if ( this.useClearcoat ) {
  18245. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  18246. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  18247. clearcoat.assign( clearcoatNode );
  18248. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  18249. }
  18250. // SHEEN
  18251. if ( this.useSheen ) {
  18252. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  18253. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  18254. sheen.assign( sheenNode );
  18255. sheenRoughness.assign( sheenRoughnessNode );
  18256. }
  18257. // IRIDESCENCE
  18258. if ( this.useIridescence ) {
  18259. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  18260. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  18261. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  18262. iridescence.assign( iridescenceNode );
  18263. iridescenceIOR.assign( iridescenceIORNode );
  18264. iridescenceThickness.assign( iridescenceThicknessNode );
  18265. }
  18266. // ANISOTROPY
  18267. if ( this.useAnisotropy ) {
  18268. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  18269. anisotropy.assign( anisotropyV.length() );
  18270. If( anisotropy.equal( 0.0 ), () => {
  18271. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  18272. } ).Else( () => {
  18273. anisotropyV.divAssign( vec2( anisotropy ) );
  18274. anisotropy.assign( anisotropy.saturate() );
  18275. } );
  18276. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  18277. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  18278. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  18279. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  18280. }
  18281. // TRANSMISSION
  18282. if ( this.useTransmission ) {
  18283. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  18284. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  18285. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  18286. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  18287. transmission.assign( transmissionNode );
  18288. thickness.assign( thicknessNode );
  18289. attenuationDistance.assign( attenuationDistanceNode );
  18290. attenuationColor.assign( attenuationColorNode );
  18291. if ( this.useDispersion ) {
  18292. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  18293. dispersion.assign( dispersionNode );
  18294. }
  18295. }
  18296. }
  18297. /**
  18298. * Setups the clearcoat normal node.
  18299. *
  18300. * @return {Node<vec3>} The clearcoat normal.
  18301. */
  18302. setupClearcoatNormal() {
  18303. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  18304. }
  18305. setup( builder ) {
  18306. builder.context.setupClearcoatNormal = () => subBuild( this.setupClearcoatNormal( builder ), 'NORMAL', 'vec3' );
  18307. super.setup( builder );
  18308. }
  18309. copy( source ) {
  18310. this.clearcoatNode = source.clearcoatNode;
  18311. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  18312. this.clearcoatNormalNode = source.clearcoatNormalNode;
  18313. this.sheenNode = source.sheenNode;
  18314. this.sheenRoughnessNode = source.sheenRoughnessNode;
  18315. this.iridescenceNode = source.iridescenceNode;
  18316. this.iridescenceIORNode = source.iridescenceIORNode;
  18317. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  18318. this.specularIntensityNode = source.specularIntensityNode;
  18319. this.specularColorNode = source.specularColorNode;
  18320. this.transmissionNode = source.transmissionNode;
  18321. this.thicknessNode = source.thicknessNode;
  18322. this.attenuationDistanceNode = source.attenuationDistanceNode;
  18323. this.attenuationColorNode = source.attenuationColorNode;
  18324. this.dispersionNode = source.dispersionNode;
  18325. this.anisotropyNode = source.anisotropyNode;
  18326. return super.copy( source );
  18327. }
  18328. }
  18329. /**
  18330. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  18331. *
  18332. * @augments PhysicalLightingModel
  18333. */
  18334. class SSSLightingModel extends PhysicalLightingModel {
  18335. /**
  18336. * Constructs a new physical lighting model.
  18337. *
  18338. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  18339. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  18340. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  18341. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  18342. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  18343. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  18344. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  18345. */
  18346. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  18347. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  18348. /**
  18349. * Whether the lighting model should use SSS or not.
  18350. *
  18351. * @type {boolean}
  18352. * @default false
  18353. */
  18354. this.useSSS = sss;
  18355. }
  18356. /**
  18357. * Extends the default implementation with a SSS term.
  18358. *
  18359. * 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/}
  18360. *
  18361. * @param {Object} input - The input data.
  18362. * @param {NodeBuilder} builder - The current node builder.
  18363. */
  18364. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18365. if ( this.useSSS === true ) {
  18366. const material = builder.material;
  18367. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  18368. const scatteringHalf = lightDirection.add( normalView.mul( thicknessDistortionNode ) ).normalize();
  18369. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  18370. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  18371. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  18372. }
  18373. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  18374. }
  18375. }
  18376. /**
  18377. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  18378. * that implements a Subsurface scattering (SSS) term.
  18379. *
  18380. * @augments MeshPhysicalNodeMaterial
  18381. */
  18382. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  18383. static get type() {
  18384. return 'MeshSSSNodeMaterial';
  18385. }
  18386. /**
  18387. * Constructs a new mesh SSS node material.
  18388. *
  18389. * @param {Object} [parameters] - The configuration parameter.
  18390. */
  18391. constructor( parameters ) {
  18392. super( parameters );
  18393. /**
  18394. * Represents the thickness color.
  18395. *
  18396. * @type {?Node<vec3>}
  18397. * @default null
  18398. */
  18399. this.thicknessColorNode = null;
  18400. /**
  18401. * Represents the distortion factor.
  18402. *
  18403. * @type {?Node<float>}
  18404. */
  18405. this.thicknessDistortionNode = float( 0.1 );
  18406. /**
  18407. * Represents the thickness ambient factor.
  18408. *
  18409. * @type {?Node<float>}
  18410. */
  18411. this.thicknessAmbientNode = float( 0.0 );
  18412. /**
  18413. * Represents the thickness attenuation.
  18414. *
  18415. * @type {?Node<float>}
  18416. */
  18417. this.thicknessAttenuationNode = float( .1 );
  18418. /**
  18419. * Represents the thickness power.
  18420. *
  18421. * @type {?Node<float>}
  18422. */
  18423. this.thicknessPowerNode = float( 2.0 );
  18424. /**
  18425. * Represents the thickness scale.
  18426. *
  18427. * @type {?Node<float>}
  18428. */
  18429. this.thicknessScaleNode = float( 10.0 );
  18430. }
  18431. /**
  18432. * Whether the lighting model should use SSS or not.
  18433. *
  18434. * @type {boolean}
  18435. * @default true
  18436. */
  18437. get useSSS() {
  18438. return this.thicknessColorNode !== null;
  18439. }
  18440. /**
  18441. * Setups the lighting model.
  18442. *
  18443. * @return {SSSLightingModel} The lighting model.
  18444. */
  18445. setupLightingModel( /*builder*/ ) {
  18446. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  18447. }
  18448. copy( source ) {
  18449. this.thicknessColorNode = source.thicknessColorNode;
  18450. this.thicknessDistortionNode = source.thicknessDistortionNode;
  18451. this.thicknessAmbientNode = source.thicknessAmbientNode;
  18452. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  18453. this.thicknessPowerNode = source.thicknessPowerNode;
  18454. this.thicknessScaleNode = source.thicknessScaleNode;
  18455. return super.copy( source );
  18456. }
  18457. }
  18458. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  18459. // dotNL will be from -1.0 to 1.0
  18460. const dotNL = normal.dot( lightDirection );
  18461. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  18462. if ( builder.material.gradientMap ) {
  18463. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  18464. return vec3( gradientMap.r );
  18465. } else {
  18466. const fw = coord.fwidth().mul( 0.5 );
  18467. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  18468. }
  18469. } );
  18470. /**
  18471. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  18472. *
  18473. * @augments LightingModel
  18474. */
  18475. class ToonLightingModel extends LightingModel {
  18476. /**
  18477. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  18478. * reduced to a small number of discrete shades to create a comic-like, flat look.
  18479. *
  18480. * @param {Object} lightData - The light data.
  18481. * @param {NodeBuilder} builder - The current node builder.
  18482. */
  18483. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  18484. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  18485. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  18486. }
  18487. /**
  18488. * Implements the indirect lighting.
  18489. *
  18490. * @param {NodeBuilder} builder - The current node builder.
  18491. */
  18492. indirect( builder ) {
  18493. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  18494. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  18495. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  18496. }
  18497. }
  18498. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  18499. /**
  18500. * Node material version of {@link MeshToonMaterial}.
  18501. *
  18502. * @augments NodeMaterial
  18503. */
  18504. class MeshToonNodeMaterial extends NodeMaterial {
  18505. static get type() {
  18506. return 'MeshToonNodeMaterial';
  18507. }
  18508. /**
  18509. * Constructs a new mesh toon node material.
  18510. *
  18511. * @param {Object} [parameters] - The configuration parameter.
  18512. */
  18513. constructor( parameters ) {
  18514. super();
  18515. /**
  18516. * This flag can be used for type testing.
  18517. *
  18518. * @type {boolean}
  18519. * @readonly
  18520. * @default true
  18521. */
  18522. this.isMeshToonNodeMaterial = true;
  18523. /**
  18524. * Set to `true` because toon materials react on lights.
  18525. *
  18526. * @type {boolean}
  18527. * @default true
  18528. */
  18529. this.lights = true;
  18530. this.setDefaultValues( _defaultValues$4 );
  18531. this.setValues( parameters );
  18532. }
  18533. /**
  18534. * Setups the lighting model.
  18535. *
  18536. * @return {ToonLightingModel} The lighting model.
  18537. */
  18538. setupLightingModel( /*builder*/ ) {
  18539. return new ToonLightingModel();
  18540. }
  18541. }
  18542. /**
  18543. * TSL function for creating a matcap uv node.
  18544. *
  18545. * Can be used to compute texture coordinates for projecting a
  18546. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  18547. *
  18548. * @tsl
  18549. * @function
  18550. * @returns {Node<vec2>} The matcap UV coordinates.
  18551. */
  18552. const matcapUV = /*@__PURE__*/ Fn( () => {
  18553. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  18554. const y = positionViewDirection.cross( x );
  18555. return vec2( x.dot( normalView ), y.dot( normalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  18556. } ).once( [ 'NORMAL', 'VERTEX' ] )().toVar( 'matcapUV' );
  18557. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  18558. /**
  18559. * Node material version of {@link MeshMatcapMaterial}.
  18560. *
  18561. * @augments NodeMaterial
  18562. */
  18563. class MeshMatcapNodeMaterial extends NodeMaterial {
  18564. static get type() {
  18565. return 'MeshMatcapNodeMaterial';
  18566. }
  18567. /**
  18568. * Constructs a new mesh normal node material.
  18569. *
  18570. * @param {Object} [parameters] - The configuration parameter.
  18571. */
  18572. constructor( parameters ) {
  18573. super();
  18574. /**
  18575. * This flag can be used for type testing.
  18576. *
  18577. * @type {boolean}
  18578. * @readonly
  18579. * @default true
  18580. */
  18581. this.isMeshMatcapNodeMaterial = true;
  18582. this.setDefaultValues( _defaultValues$3 );
  18583. this.setValues( parameters );
  18584. }
  18585. /**
  18586. * Setups the matcap specific node variables.
  18587. *
  18588. * @param {NodeBuilder} builder - The current node builder.
  18589. */
  18590. setupVariants( builder ) {
  18591. const uv = matcapUV;
  18592. let matcapColor;
  18593. if ( builder.material.matcap ) {
  18594. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  18595. } else {
  18596. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  18597. }
  18598. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  18599. }
  18600. }
  18601. /**
  18602. * Applies a rotation to the given position node.
  18603. *
  18604. * @augments TempNode
  18605. */
  18606. class RotateNode extends TempNode {
  18607. static get type() {
  18608. return 'RotateNode';
  18609. }
  18610. /**
  18611. * Constructs a new rotate node.
  18612. *
  18613. * @param {Node} positionNode - The position node.
  18614. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18615. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18616. */
  18617. constructor( positionNode, rotationNode ) {
  18618. super();
  18619. /**
  18620. * The position node.
  18621. *
  18622. * @type {Node}
  18623. */
  18624. this.positionNode = positionNode;
  18625. /**
  18626. * Represents the rotation that is applied to the position node.
  18627. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18628. *
  18629. * @type {Node}
  18630. */
  18631. this.rotationNode = rotationNode;
  18632. }
  18633. /**
  18634. * The type of the {@link RotateNode#positionNode} defines the node's type.
  18635. *
  18636. * @param {NodeBuilder} builder - The current node builder.
  18637. * @return {string} The node's type.
  18638. */
  18639. getNodeType( builder ) {
  18640. return this.positionNode.getNodeType( builder );
  18641. }
  18642. setup( builder ) {
  18643. const { rotationNode, positionNode } = this;
  18644. const nodeType = this.getNodeType( builder );
  18645. if ( nodeType === 'vec2' ) {
  18646. const cosAngle = rotationNode.cos();
  18647. const sinAngle = rotationNode.sin();
  18648. const rotationMatrix = mat2(
  18649. cosAngle, sinAngle,
  18650. sinAngle.negate(), cosAngle
  18651. );
  18652. return rotationMatrix.mul( positionNode );
  18653. } else {
  18654. const rotation = rotationNode;
  18655. 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 ) );
  18656. 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 ) );
  18657. 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 ) );
  18658. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  18659. }
  18660. }
  18661. }
  18662. /**
  18663. * TSL function for creating a rotate node.
  18664. *
  18665. * @tsl
  18666. * @function
  18667. * @param {Node} positionNode - The position node.
  18668. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  18669. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  18670. * @returns {RotateNode}
  18671. */
  18672. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  18673. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  18674. /**
  18675. * Node material version of {@link SpriteMaterial}.
  18676. *
  18677. * @augments NodeMaterial
  18678. */
  18679. class SpriteNodeMaterial extends NodeMaterial {
  18680. static get type() {
  18681. return 'SpriteNodeMaterial';
  18682. }
  18683. /**
  18684. * Constructs a new sprite node material.
  18685. *
  18686. * @param {Object} [parameters] - The configuration parameter.
  18687. */
  18688. constructor( parameters ) {
  18689. super();
  18690. /**
  18691. * This flag can be used for type testing.
  18692. *
  18693. * @type {boolean}
  18694. * @readonly
  18695. * @default true
  18696. */
  18697. this.isSpriteNodeMaterial = true;
  18698. this._useSizeAttenuation = true;
  18699. /**
  18700. * This property makes it possible to define the position of the sprite with a
  18701. * node. That can be useful when the material is used with instanced rendering
  18702. * and node data are defined with an instanced attribute node:
  18703. * ```js
  18704. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  18705. * material.positionNode = instancedBufferAttribute( positionAttribute );
  18706. * ```
  18707. * Another possibility is to compute the instanced data with a compute shader:
  18708. * ```js
  18709. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  18710. * particleMaterial.positionNode = positionBuffer.toAttribute();
  18711. * ```
  18712. *
  18713. * @type {?Node<vec2>}
  18714. * @default null
  18715. */
  18716. this.positionNode = null;
  18717. /**
  18718. * The rotation of sprite materials is by default inferred from the `rotation`,
  18719. * property. This node property allows to overwrite the default and define
  18720. * the rotation with a node instead.
  18721. *
  18722. * If you don't want to overwrite the rotation but modify the existing
  18723. * value instead, use {@link materialRotation}.
  18724. *
  18725. * @type {?Node<float>}
  18726. * @default null
  18727. */
  18728. this.rotationNode = null;
  18729. /**
  18730. * This node property provides an additional way to scale sprites next to
  18731. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  18732. * is multiplied with the scale value of this node in the vertex shader.
  18733. *
  18734. * @type {?Node<vec2>}
  18735. * @default null
  18736. */
  18737. this.scaleNode = null;
  18738. /**
  18739. * In Sprites, the transparent property is enabled by default.
  18740. *
  18741. * @type {boolean}
  18742. * @default true
  18743. */
  18744. this.transparent = true;
  18745. this.setDefaultValues( _defaultValues$2 );
  18746. this.setValues( parameters );
  18747. }
  18748. /**
  18749. * Setups the position node in view space. This method implements
  18750. * the sprite specific vertex shader.
  18751. *
  18752. * @param {NodeBuilder} builder - The current node builder.
  18753. * @return {Node<vec3>} The position in view space.
  18754. */
  18755. setupPositionView( builder ) {
  18756. const { object, camera } = builder;
  18757. const { positionNode, rotationNode, scaleNode, sizeAttenuation } = this;
  18758. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  18759. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  18760. if ( scaleNode !== null ) {
  18761. scale = scale.mul( vec2( scaleNode ) );
  18762. }
  18763. if ( camera.isPerspectiveCamera && sizeAttenuation === false ) {
  18764. scale = scale.mul( mvPosition.z.negate() );
  18765. }
  18766. let alignedPosition = positionGeometry.xy;
  18767. if ( object.center && object.center.isVector2 === true ) {
  18768. const center = reference$1( 'center', 'vec2', object );
  18769. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  18770. }
  18771. alignedPosition = alignedPosition.mul( scale );
  18772. const rotation = float( rotationNode || materialRotation );
  18773. const rotatedPosition = rotate( alignedPosition, rotation );
  18774. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  18775. }
  18776. copy( source ) {
  18777. this.positionNode = source.positionNode;
  18778. this.rotationNode = source.rotationNode;
  18779. this.scaleNode = source.scaleNode;
  18780. return super.copy( source );
  18781. }
  18782. /**
  18783. * Whether to use size attenuation or not.
  18784. *
  18785. * @type {boolean}
  18786. * @default true
  18787. */
  18788. get sizeAttenuation() {
  18789. return this._useSizeAttenuation;
  18790. }
  18791. set sizeAttenuation( value ) {
  18792. if ( this._useSizeAttenuation !== value ) {
  18793. this._useSizeAttenuation = value;
  18794. this.needsUpdate = true;
  18795. }
  18796. }
  18797. }
  18798. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  18799. const _size$4 = /*@__PURE__*/ new Vector2();
  18800. /**
  18801. * Node material version of {@link PointsMaterial}.
  18802. *
  18803. * This material can be used in two ways:
  18804. *
  18805. * - By rendering point primitives with {@link Points}. Since WebGPU only supports point primitives
  18806. * with a pixel size of `1`, it's not possible to define a size.
  18807. *
  18808. * ```js
  18809. * const pointCloud = new THREE.Points( geometry, new THREE.PointsNodeMaterial() );
  18810. * ```
  18811. *
  18812. * - By rendering point primitives with {@link Sprites}. In this case, size is honored,
  18813. * see {@link PointsNodeMaterial#sizeNode}.
  18814. *
  18815. * ```js
  18816. * const instancedPoints = new THREE.Sprite( new THREE.PointsNodeMaterial( { positionNode: instancedBufferAttribute( positionAttribute ) } ) );
  18817. * ```
  18818. *
  18819. * @augments SpriteNodeMaterial
  18820. */
  18821. class PointsNodeMaterial extends SpriteNodeMaterial {
  18822. static get type() {
  18823. return 'PointsNodeMaterial';
  18824. }
  18825. /**
  18826. * Constructs a new points node material.
  18827. *
  18828. * @param {Object} [parameters] - The configuration parameter.
  18829. */
  18830. constructor( parameters ) {
  18831. super();
  18832. /**
  18833. * This node property provides an additional way to set the point size.
  18834. *
  18835. * Note that WebGPU only supports point primitives with 1 pixel size. Consequently,
  18836. * this node has no effect when the material is used with {@link Points} and a WebGPU
  18837. * backend. If an application wants to render points with a size larger than 1 pixel,
  18838. * the material should be used with {@link Sprite} and instancing.
  18839. *
  18840. * @type {?Node<vec2>}
  18841. * @default null
  18842. */
  18843. this.sizeNode = null;
  18844. /**
  18845. * This flag can be used for type testing.
  18846. *
  18847. * @type {boolean}
  18848. * @readonly
  18849. * @default true
  18850. */
  18851. this.isPointsNodeMaterial = true;
  18852. this.setDefaultValues( _defaultValues$1 );
  18853. this.setValues( parameters );
  18854. }
  18855. setupPositionView() {
  18856. const { positionNode } = this;
  18857. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  18858. }
  18859. setupVertexSprite( builder ) {
  18860. const { material, camera } = builder;
  18861. const { rotationNode, scaleNode, sizeNode, sizeAttenuation } = this;
  18862. let mvp = super.setupVertex( builder );
  18863. // skip further processing if the material is not a node material
  18864. if ( material.isNodeMaterial !== true ) {
  18865. return mvp;
  18866. }
  18867. // point size
  18868. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  18869. pointSize = pointSize.mul( screenDPR );
  18870. // size attenuation
  18871. if ( camera.isPerspectiveCamera && sizeAttenuation === true ) {
  18872. // follow WebGLRenderer's implementation, and scale by half the canvas height in logical units
  18873. pointSize = pointSize.mul( scale.div( positionView.z.negate() ) );
  18874. }
  18875. // scale
  18876. if ( scaleNode && scaleNode.isNode ) {
  18877. pointSize = pointSize.mul( vec2( scaleNode ) );
  18878. }
  18879. // compute offset
  18880. let offset = positionGeometry.xy;
  18881. // apply rotation
  18882. if ( rotationNode && rotationNode.isNode ) {
  18883. const rotation = float( rotationNode );
  18884. offset = rotate( offset, rotation );
  18885. }
  18886. // account for point size
  18887. offset = offset.mul( pointSize );
  18888. // scale by viewport size
  18889. offset = offset.div( viewportSize.div( 2 ) );
  18890. // compensate for the perspective divide
  18891. offset = offset.mul( mvp.w );
  18892. // add offset
  18893. mvp = mvp.add( vec4( offset, 0, 0 ) );
  18894. return mvp;
  18895. }
  18896. setupVertex( builder ) {
  18897. if ( builder.object.isPoints ) {
  18898. return super.setupVertex( builder );
  18899. } else {
  18900. return this.setupVertexSprite( builder );
  18901. }
  18902. }
  18903. /**
  18904. * Whether alpha to coverage should be used or not.
  18905. *
  18906. * @type {boolean}
  18907. * @default true
  18908. */
  18909. get alphaToCoverage() {
  18910. return this._useAlphaToCoverage;
  18911. }
  18912. set alphaToCoverage( value ) {
  18913. if ( this._useAlphaToCoverage !== value ) {
  18914. this._useAlphaToCoverage = value;
  18915. this.needsUpdate = true;
  18916. }
  18917. }
  18918. }
  18919. const scale = /*@__PURE__*/ uniform( 1 ).onFrameUpdate( function ( { renderer } ) {
  18920. const size = renderer.getSize( _size$4 ); // logical units
  18921. this.value = 0.5 * size.y;
  18922. } );
  18923. /**
  18924. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  18925. *
  18926. * @augments LightingModel
  18927. */
  18928. class ShadowMaskModel extends LightingModel {
  18929. /**
  18930. * Constructs a new shadow mask model.
  18931. */
  18932. constructor() {
  18933. super();
  18934. /**
  18935. * The shadow mask node.
  18936. *
  18937. * @type {Node}
  18938. */
  18939. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  18940. }
  18941. /**
  18942. * Only used to save the shadow mask.
  18943. *
  18944. * @param {Object} input - The input data.
  18945. */
  18946. direct( { lightNode } ) {
  18947. if ( lightNode.shadowNode !== null ) {
  18948. this.shadowNode.mulAssign( lightNode.shadowNode );
  18949. }
  18950. }
  18951. /**
  18952. * Uses the shadow mask to produce the final color.
  18953. *
  18954. * @param {NodeBuilder} builder - The current node builder.
  18955. */
  18956. finish( { context } ) {
  18957. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  18958. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  18959. }
  18960. }
  18961. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  18962. /**
  18963. * Node material version of {@link ShadowMaterial}.
  18964. *
  18965. * @augments NodeMaterial
  18966. */
  18967. class ShadowNodeMaterial extends NodeMaterial {
  18968. static get type() {
  18969. return 'ShadowNodeMaterial';
  18970. }
  18971. /**
  18972. * Constructs a new shadow node material.
  18973. *
  18974. * @param {Object} [parameters] - The configuration parameter.
  18975. */
  18976. constructor( parameters ) {
  18977. super();
  18978. /**
  18979. * This flag can be used for type testing.
  18980. *
  18981. * @type {boolean}
  18982. * @readonly
  18983. * @default true
  18984. */
  18985. this.isShadowNodeMaterial = true;
  18986. /**
  18987. * Set to `true` because so it's possible to implement
  18988. * the shadow mask effect.
  18989. *
  18990. * @type {boolean}
  18991. * @default true
  18992. */
  18993. this.lights = true;
  18994. /**
  18995. * Overwritten since shadow materials are transparent
  18996. * by default.
  18997. *
  18998. * @type {boolean}
  18999. * @default true
  19000. */
  19001. this.transparent = true;
  19002. this.setDefaultValues( _defaultValues );
  19003. this.setValues( parameters );
  19004. }
  19005. /**
  19006. * Setups the lighting model.
  19007. *
  19008. * @return {ShadowMaskModel} The lighting model.
  19009. */
  19010. setupLightingModel( /*builder*/ ) {
  19011. return new ShadowMaskModel();
  19012. }
  19013. }
  19014. const scatteringDensity = property( 'vec3' );
  19015. const linearDepthRay = property( 'vec3' );
  19016. const outgoingRayLight = property( 'vec3' );
  19017. /**
  19018. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  19019. * This model calculates the scattering and transmittance of light through a volumetric medium.
  19020. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  19021. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  19022. *
  19023. * @augments LightingModel
  19024. */
  19025. class VolumetricLightingModel extends LightingModel {
  19026. constructor() {
  19027. super();
  19028. }
  19029. start( builder ) {
  19030. const { material, context } = builder;
  19031. const startPos = property( 'vec3' );
  19032. const endPos = property( 'vec3' );
  19033. // This approach dynamically changes the direction of the ray,
  19034. // 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.
  19035. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  19036. startPos.assign( cameraPosition );
  19037. endPos.assign( positionWorld );
  19038. } ).Else( () => {
  19039. startPos.assign( positionWorld );
  19040. endPos.assign( cameraPosition );
  19041. } );
  19042. //
  19043. const viewVector = endPos.sub( startPos );
  19044. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  19045. const stepSize = viewVector.length().div( steps ).toVar();
  19046. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  19047. const distTravelled = float( 0.0 ).toVar();
  19048. const transmittance = vec3( 1 ).toVar();
  19049. if ( material.offsetNode ) {
  19050. // reduce banding
  19051. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  19052. }
  19053. Loop( steps, () => {
  19054. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  19055. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  19056. if ( material.depthNode !== null ) {
  19057. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  19058. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  19059. }
  19060. context.positionWorld = positionRay;
  19061. context.shadowPositionWorld = positionRay;
  19062. context.positionView = positionViewRay;
  19063. scatteringDensity.assign( 0 );
  19064. let scatteringNode;
  19065. if ( material.scatteringNode ) {
  19066. scatteringNode = material.scatteringNode( {
  19067. positionRay
  19068. } );
  19069. }
  19070. super.start( builder );
  19071. if ( scatteringNode ) {
  19072. scatteringDensity.mulAssign( scatteringNode );
  19073. }
  19074. // beer's law
  19075. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  19076. transmittance.mulAssign( falloff );
  19077. // move along the ray
  19078. distTravelled.addAssign( stepSize );
  19079. } );
  19080. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  19081. }
  19082. scatteringLight( lightColor, builder ) {
  19083. const sceneDepthNode = builder.context.sceneDepthNode;
  19084. if ( sceneDepthNode ) {
  19085. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  19086. scatteringDensity.addAssign( lightColor );
  19087. } );
  19088. } else {
  19089. scatteringDensity.addAssign( lightColor );
  19090. }
  19091. }
  19092. direct( { lightNode, lightColor }, builder ) {
  19093. // Ignore lights with infinite distance
  19094. if ( lightNode.light.distance === undefined ) return;
  19095. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  19096. const directLight = lightColor.xyz.toVar();
  19097. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  19098. this.scatteringLight( directLight, builder );
  19099. }
  19100. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  19101. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  19102. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  19103. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  19104. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  19105. const P = builder.context.positionView;
  19106. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  19107. this.scatteringLight( directLight, builder );
  19108. }
  19109. finish( builder ) {
  19110. builder.context.outgoingLight.assign( outgoingRayLight );
  19111. }
  19112. }
  19113. /**
  19114. * Volume node material.
  19115. *
  19116. * @augments NodeMaterial
  19117. */
  19118. class VolumeNodeMaterial extends NodeMaterial {
  19119. static get type() {
  19120. return 'VolumeNodeMaterial';
  19121. }
  19122. /**
  19123. * Constructs a new volume node material.
  19124. *
  19125. * @param {Object} [parameters] - The configuration parameter.
  19126. */
  19127. constructor( parameters ) {
  19128. super();
  19129. /**
  19130. * This flag can be used for type testing.
  19131. *
  19132. * @type {boolean}
  19133. * @readonly
  19134. * @default true
  19135. */
  19136. this.isVolumeNodeMaterial = true;
  19137. /**
  19138. * Number of steps used for raymarching.
  19139. *
  19140. * @type {number}
  19141. * @default 25
  19142. */
  19143. this.steps = 25;
  19144. /**
  19145. * Offsets the distance a ray has been traveled through a volume.
  19146. * Can be used to implement dithering to reduce banding.
  19147. *
  19148. * @type {Node<float>}
  19149. * @default null
  19150. */
  19151. this.offsetNode = null;
  19152. /**
  19153. * Node used for scattering calculations.
  19154. *
  19155. * @type {Function|FunctionNode<vec4>}
  19156. * @default null
  19157. */
  19158. this.scatteringNode = null;
  19159. this.lights = true;
  19160. this.transparent = true;
  19161. this.side = BackSide;
  19162. this.depthTest = false;
  19163. this.depthWrite = false;
  19164. this.setValues( parameters );
  19165. }
  19166. setupLightingModel() {
  19167. return new VolumetricLightingModel();
  19168. }
  19169. }
  19170. /**
  19171. * This module manages the internal animation loop of the renderer.
  19172. *
  19173. * @private
  19174. */
  19175. class Animation {
  19176. /**
  19177. * Constructs a new animation loop management component.
  19178. *
  19179. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19180. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19181. */
  19182. constructor( nodes, info ) {
  19183. /**
  19184. * Renderer component for managing nodes related logic.
  19185. *
  19186. * @type {Nodes}
  19187. */
  19188. this.nodes = nodes;
  19189. /**
  19190. * Renderer component for managing metrics and monitoring data.
  19191. *
  19192. * @type {Info}
  19193. */
  19194. this.info = info;
  19195. /**
  19196. * A reference to the context from `requestAnimationFrame()` can
  19197. * be called (usually `window`).
  19198. *
  19199. * @type {?(Window|XRSession)}
  19200. */
  19201. this._context = typeof self !== 'undefined' ? self : null;
  19202. /**
  19203. * The user-defined animation loop.
  19204. *
  19205. * @type {?Function}
  19206. * @default null
  19207. */
  19208. this._animationLoop = null;
  19209. /**
  19210. * The requestId which is returned from the `requestAnimationFrame()` call.
  19211. * Can be used to cancel the stop the animation loop.
  19212. *
  19213. * @type {?number}
  19214. * @default null
  19215. */
  19216. this._requestId = null;
  19217. }
  19218. /**
  19219. * Starts the internal animation loop.
  19220. */
  19221. start() {
  19222. const update = ( time, xrFrame ) => {
  19223. this._requestId = this._context.requestAnimationFrame( update );
  19224. if ( this.info.autoReset === true ) this.info.reset();
  19225. this.nodes.nodeFrame.update();
  19226. this.info.frame = this.nodes.nodeFrame.frameId;
  19227. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  19228. };
  19229. update();
  19230. }
  19231. /**
  19232. * Stops the internal animation loop.
  19233. */
  19234. stop() {
  19235. this._context.cancelAnimationFrame( this._requestId );
  19236. this._requestId = null;
  19237. }
  19238. /**
  19239. * Returns the user-level animation loop.
  19240. *
  19241. * @return {?Function} The animation loop.
  19242. */
  19243. getAnimationLoop() {
  19244. return this._animationLoop;
  19245. }
  19246. /**
  19247. * Defines the user-level animation loop.
  19248. *
  19249. * @param {?Function} callback - The animation loop.
  19250. */
  19251. setAnimationLoop( callback ) {
  19252. this._animationLoop = callback;
  19253. }
  19254. /**
  19255. * Returns the animation context.
  19256. *
  19257. * @return {Window|XRSession} The animation context.
  19258. */
  19259. getContext() {
  19260. return this._context;
  19261. }
  19262. /**
  19263. * Defines the context in which `requestAnimationFrame()` is executed.
  19264. *
  19265. * @param {Window|XRSession} context - The context to set.
  19266. */
  19267. setContext( context ) {
  19268. this._context = context;
  19269. }
  19270. /**
  19271. * Frees all internal resources and stops the animation loop.
  19272. */
  19273. dispose() {
  19274. this.stop();
  19275. }
  19276. }
  19277. /**
  19278. * Data structure for the renderer. It allows defining values
  19279. * with chained, hierarchical keys. Keys are meant to be
  19280. * objects since the module internally works with Weak Maps
  19281. * for performance reasons.
  19282. *
  19283. * @private
  19284. */
  19285. class ChainMap {
  19286. /**
  19287. * Constructs a new Chain Map.
  19288. */
  19289. constructor() {
  19290. /**
  19291. * The root Weak Map.
  19292. *
  19293. * @type {WeakMap<Object, WeakMap>}
  19294. */
  19295. this.weakMap = new WeakMap();
  19296. }
  19297. /**
  19298. * Returns the value for the given array of keys.
  19299. *
  19300. * @param {Array<Object>} keys - List of keys.
  19301. * @return {any} The value. Returns `undefined` if no value was found.
  19302. */
  19303. get( keys ) {
  19304. let map = this.weakMap;
  19305. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19306. map = map.get( keys[ i ] );
  19307. if ( map === undefined ) return undefined;
  19308. }
  19309. return map.get( keys[ keys.length - 1 ] );
  19310. }
  19311. /**
  19312. * Sets the value for the given keys.
  19313. *
  19314. * @param {Array<Object>} keys - List of keys.
  19315. * @param {any} value - The value to set.
  19316. * @return {ChainMap} A reference to this Chain Map.
  19317. */
  19318. set( keys, value ) {
  19319. let map = this.weakMap;
  19320. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19321. const key = keys[ i ];
  19322. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  19323. map = map.get( key );
  19324. }
  19325. map.set( keys[ keys.length - 1 ], value );
  19326. return this;
  19327. }
  19328. /**
  19329. * Deletes a value for the given keys.
  19330. *
  19331. * @param {Array<Object>} keys - The keys.
  19332. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  19333. */
  19334. delete( keys ) {
  19335. let map = this.weakMap;
  19336. for ( let i = 0; i < keys.length - 1; i ++ ) {
  19337. map = map.get( keys[ i ] );
  19338. if ( map === undefined ) return false;
  19339. }
  19340. return map.delete( keys[ keys.length - 1 ] );
  19341. }
  19342. }
  19343. let _id$9 = 0;
  19344. function getKeys( obj ) {
  19345. const keys = Object.keys( obj );
  19346. let proto = Object.getPrototypeOf( obj );
  19347. while ( proto ) {
  19348. const descriptors = Object.getOwnPropertyDescriptors( proto );
  19349. for ( const key in descriptors ) {
  19350. if ( descriptors[ key ] !== undefined ) {
  19351. const descriptor = descriptors[ key ];
  19352. if ( descriptor && typeof descriptor.get === 'function' ) {
  19353. keys.push( key );
  19354. }
  19355. }
  19356. }
  19357. proto = Object.getPrototypeOf( proto );
  19358. }
  19359. return keys;
  19360. }
  19361. /**
  19362. * A render object is the renderer's representation of single entity that gets drawn
  19363. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  19364. * scene since render objects also depend from the used material, the current render context
  19365. * and the current scene's lighting.
  19366. *
  19367. * In general, the basic process of the renderer is:
  19368. *
  19369. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  19370. * - Process the render lists by calling one or more render commands for each render item.
  19371. * - For each render command, request a render object and perform the draw.
  19372. *
  19373. * The module provides an interface to get data required for the draw command like the actual
  19374. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  19375. * creating render objects should only be done when necessary.
  19376. *
  19377. * @private
  19378. */
  19379. class RenderObject {
  19380. /**
  19381. * Constructs a new render object.
  19382. *
  19383. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19384. * @param {Geometries} geometries - Renderer component for managing geometries.
  19385. * @param {Renderer} renderer - The renderer.
  19386. * @param {Object3D} object - The 3D object.
  19387. * @param {Material} material - The 3D object's material.
  19388. * @param {Scene} scene - The scene the 3D object belongs to.
  19389. * @param {Camera} camera - The camera the object should be rendered with.
  19390. * @param {LightsNode} lightsNode - The lights node.
  19391. * @param {RenderContext} renderContext - The render context.
  19392. * @param {ClippingContext} clippingContext - The clipping context.
  19393. */
  19394. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  19395. this.id = _id$9 ++;
  19396. /**
  19397. * Renderer component for managing nodes related logic.
  19398. *
  19399. * @type {Nodes}
  19400. * @private
  19401. */
  19402. this._nodes = nodes;
  19403. /**
  19404. * Renderer component for managing geometries.
  19405. *
  19406. * @type {Geometries}
  19407. * @private
  19408. */
  19409. this._geometries = geometries;
  19410. /**
  19411. * The renderer.
  19412. *
  19413. * @type {Renderer}
  19414. */
  19415. this.renderer = renderer;
  19416. /**
  19417. * The 3D object.
  19418. *
  19419. * @type {Object3D}
  19420. */
  19421. this.object = object;
  19422. /**
  19423. * The 3D object's material.
  19424. *
  19425. * @type {Material}
  19426. */
  19427. this.material = material;
  19428. /**
  19429. * The scene the 3D object belongs to.
  19430. *
  19431. * @type {Scene}
  19432. */
  19433. this.scene = scene;
  19434. /**
  19435. * The camera the 3D object should be rendered with.
  19436. *
  19437. * @type {Camera}
  19438. */
  19439. this.camera = camera;
  19440. /**
  19441. * The lights node.
  19442. *
  19443. * @type {LightsNode}
  19444. */
  19445. this.lightsNode = lightsNode;
  19446. /**
  19447. * The render context.
  19448. *
  19449. * @type {RenderContext}
  19450. */
  19451. this.context = renderContext;
  19452. /**
  19453. * The 3D object's geometry.
  19454. *
  19455. * @type {BufferGeometry}
  19456. */
  19457. this.geometry = object.geometry;
  19458. /**
  19459. * The render object's version.
  19460. *
  19461. * @type {number}
  19462. */
  19463. this.version = material.version;
  19464. /**
  19465. * The draw range of the geometry.
  19466. *
  19467. * @type {?Object}
  19468. * @default null
  19469. */
  19470. this.drawRange = null;
  19471. /**
  19472. * An array holding the buffer attributes
  19473. * of the render object. This entails attribute
  19474. * definitions on geometry and node level.
  19475. *
  19476. * @type {?Array<BufferAttribute>}
  19477. * @default null
  19478. */
  19479. this.attributes = null;
  19480. /**
  19481. * An object holding the version of the
  19482. * attributes. The keys are the attribute names
  19483. * and the values are the attribute versions.
  19484. *
  19485. * @type {?Object<string, number>}
  19486. * @default null
  19487. */
  19488. this.attributesId = null;
  19489. /**
  19490. * A reference to a render pipeline the render
  19491. * object is processed with.
  19492. *
  19493. * @type {RenderPipeline}
  19494. * @default null
  19495. */
  19496. this.pipeline = null;
  19497. /**
  19498. * Only relevant for objects using
  19499. * multiple materials. This represents a group entry
  19500. * from the respective `BufferGeometry`.
  19501. *
  19502. * @type {?{start: number, count: number}}
  19503. * @default null
  19504. */
  19505. this.group = null;
  19506. /**
  19507. * An array holding the vertex buffers which can
  19508. * be buffer attributes but also interleaved buffers.
  19509. *
  19510. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  19511. * @default null
  19512. */
  19513. this.vertexBuffers = null;
  19514. /**
  19515. * The parameters for the draw command.
  19516. *
  19517. * @type {?Object}
  19518. * @default null
  19519. */
  19520. this.drawParams = null;
  19521. /**
  19522. * If this render object is used inside a render bundle,
  19523. * this property points to the respective bundle group.
  19524. *
  19525. * @type {?BundleGroup}
  19526. * @default null
  19527. */
  19528. this.bundle = null;
  19529. /**
  19530. * The clipping context.
  19531. *
  19532. * @type {ClippingContext}
  19533. */
  19534. this.clippingContext = clippingContext;
  19535. /**
  19536. * The clipping context's cache key.
  19537. *
  19538. * @type {string}
  19539. */
  19540. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  19541. /**
  19542. * The initial node cache key.
  19543. *
  19544. * @type {number}
  19545. */
  19546. this.initialNodesCacheKey = this.getDynamicCacheKey();
  19547. /**
  19548. * The initial cache key.
  19549. *
  19550. * @type {number}
  19551. */
  19552. this.initialCacheKey = this.getCacheKey();
  19553. /**
  19554. * The node builder state.
  19555. *
  19556. * @type {?NodeBuilderState}
  19557. * @private
  19558. * @default null
  19559. */
  19560. this._nodeBuilderState = null;
  19561. /**
  19562. * An array of bindings.
  19563. *
  19564. * @type {?Array<BindGroup>}
  19565. * @private
  19566. * @default null
  19567. */
  19568. this._bindings = null;
  19569. /**
  19570. * Reference to the node material observer.
  19571. *
  19572. * @type {?NodeMaterialObserver}
  19573. * @private
  19574. * @default null
  19575. */
  19576. this._monitor = null;
  19577. /**
  19578. * An event listener which is defined by `RenderObjects`. It performs
  19579. * clean up tasks when `dispose()` on this render object.
  19580. *
  19581. * @method
  19582. */
  19583. this.onDispose = null;
  19584. /**
  19585. * This flag can be used for type testing.
  19586. *
  19587. * @type {boolean}
  19588. * @readonly
  19589. * @default true
  19590. */
  19591. this.isRenderObject = true;
  19592. /**
  19593. * An event listener which is executed when `dispose()` is called on
  19594. * the material of this render object.
  19595. *
  19596. * @method
  19597. */
  19598. this.onMaterialDispose = () => {
  19599. this.dispose();
  19600. };
  19601. /**
  19602. * An event listener which is executed when `dispose()` is called on
  19603. * the geometry of this render object.
  19604. *
  19605. * @method
  19606. */
  19607. this.onGeometryDispose = () => {
  19608. // clear geometry cache attributes
  19609. this.attributes = null;
  19610. this.attributesId = null;
  19611. };
  19612. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  19613. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  19614. }
  19615. /**
  19616. * Updates the clipping context.
  19617. *
  19618. * @param {ClippingContext} context - The clipping context to set.
  19619. */
  19620. updateClipping( context ) {
  19621. this.clippingContext = context;
  19622. }
  19623. /**
  19624. * Whether the clipping requires an update or not.
  19625. *
  19626. * @type {boolean}
  19627. * @readonly
  19628. */
  19629. get clippingNeedsUpdate() {
  19630. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  19631. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  19632. return true;
  19633. }
  19634. /**
  19635. * The number of clipping planes defined in context of hardware clipping.
  19636. *
  19637. * @type {number}
  19638. * @readonly
  19639. */
  19640. get hardwareClippingPlanes() {
  19641. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  19642. }
  19643. /**
  19644. * Returns the node builder state of this render object.
  19645. *
  19646. * @return {NodeBuilderState} The node builder state.
  19647. */
  19648. getNodeBuilderState() {
  19649. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  19650. }
  19651. /**
  19652. * Returns the node material observer of this render object.
  19653. *
  19654. * @return {NodeMaterialObserver} The node material observer.
  19655. */
  19656. getMonitor() {
  19657. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  19658. }
  19659. /**
  19660. * Returns an array of bind groups of this render object.
  19661. *
  19662. * @return {Array<BindGroup>} The bindings.
  19663. */
  19664. getBindings() {
  19665. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  19666. }
  19667. /**
  19668. * Returns a binding group by group name of this render object.
  19669. *
  19670. * @param {string} name - The name of the binding group.
  19671. * @return {?BindGroup} The bindings.
  19672. */
  19673. getBindingGroup( name ) {
  19674. for ( const bindingGroup of this.getBindings() ) {
  19675. if ( bindingGroup.name === name ) {
  19676. return bindingGroup;
  19677. }
  19678. }
  19679. }
  19680. /**
  19681. * Returns the index of the render object's geometry.
  19682. *
  19683. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  19684. */
  19685. getIndex() {
  19686. return this._geometries.getIndex( this );
  19687. }
  19688. /**
  19689. * Returns the indirect buffer attribute.
  19690. *
  19691. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  19692. */
  19693. getIndirect() {
  19694. return this._geometries.getIndirect( this );
  19695. }
  19696. /**
  19697. * Returns an array that acts as a key for identifying the render object in a chain map.
  19698. *
  19699. * @return {Array<Object>} An array with object references.
  19700. */
  19701. getChainArray() {
  19702. return [ this.object, this.material, this.context, this.lightsNode ];
  19703. }
  19704. /**
  19705. * This method is used when the geometry of a 3D object has been exchanged and the
  19706. * respective render object now requires an update.
  19707. *
  19708. * @param {BufferGeometry} geometry - The geometry to set.
  19709. */
  19710. setGeometry( geometry ) {
  19711. this.geometry = geometry;
  19712. this.attributes = null;
  19713. this.attributesId = null;
  19714. }
  19715. /**
  19716. * Returns the buffer attributes of the render object. The returned array holds
  19717. * attribute definitions on geometry and node level.
  19718. *
  19719. * @return {Array<BufferAttribute>} An array with buffer attributes.
  19720. */
  19721. getAttributes() {
  19722. if ( this.attributes !== null ) return this.attributes;
  19723. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  19724. const geometry = this.geometry;
  19725. const attributes = [];
  19726. const vertexBuffers = new Set();
  19727. const attributesId = {};
  19728. for ( const nodeAttribute of nodeAttributes ) {
  19729. let attribute;
  19730. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  19731. // node attribute
  19732. attribute = nodeAttribute.node.attribute;
  19733. } else {
  19734. // geometry attribute
  19735. attribute = geometry.getAttribute( nodeAttribute.name );
  19736. attributesId[ nodeAttribute.name ] = attribute.version;
  19737. }
  19738. if ( attribute === undefined ) continue;
  19739. attributes.push( attribute );
  19740. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  19741. vertexBuffers.add( bufferAttribute );
  19742. }
  19743. this.attributes = attributes;
  19744. this.attributesId = attributesId;
  19745. this.vertexBuffers = Array.from( vertexBuffers.values() );
  19746. return attributes;
  19747. }
  19748. /**
  19749. * Returns the vertex buffers of the render object.
  19750. *
  19751. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  19752. */
  19753. getVertexBuffers() {
  19754. if ( this.vertexBuffers === null ) this.getAttributes();
  19755. return this.vertexBuffers;
  19756. }
  19757. /**
  19758. * Returns the draw parameters for the render object.
  19759. *
  19760. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  19761. */
  19762. getDrawParameters() {
  19763. const { object, material, geometry, group, drawRange } = this;
  19764. const drawParams = this.drawParams || ( this.drawParams = {
  19765. vertexCount: 0,
  19766. firstVertex: 0,
  19767. instanceCount: 0,
  19768. firstInstance: 0
  19769. } );
  19770. const index = this.getIndex();
  19771. const hasIndex = ( index !== null );
  19772. let instanceCount = 1;
  19773. if ( geometry.isInstancedBufferGeometry === true ) {
  19774. instanceCount = geometry.instanceCount;
  19775. } else if ( object.count !== undefined ) {
  19776. instanceCount = Math.max( 0, object.count );
  19777. }
  19778. if ( instanceCount === 0 ) return null;
  19779. drawParams.instanceCount = instanceCount;
  19780. if ( object.isBatchedMesh === true ) return drawParams;
  19781. let rangeFactor = 1;
  19782. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  19783. rangeFactor = 2;
  19784. }
  19785. let firstVertex = drawRange.start * rangeFactor;
  19786. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  19787. if ( group !== null ) {
  19788. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  19789. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  19790. }
  19791. const position = geometry.attributes.position;
  19792. let itemCount = Infinity;
  19793. if ( hasIndex ) {
  19794. itemCount = index.count;
  19795. } else if ( position !== undefined && position !== null ) {
  19796. itemCount = position.count;
  19797. }
  19798. firstVertex = Math.max( firstVertex, 0 );
  19799. lastVertex = Math.min( lastVertex, itemCount );
  19800. const count = lastVertex - firstVertex;
  19801. if ( count < 0 || count === Infinity ) return null;
  19802. drawParams.vertexCount = count;
  19803. drawParams.firstVertex = firstVertex;
  19804. return drawParams;
  19805. }
  19806. /**
  19807. * Returns the render object's geometry cache key.
  19808. *
  19809. * The geometry cache key is part of the material cache key.
  19810. *
  19811. * @return {string} The geometry cache key.
  19812. */
  19813. getGeometryCacheKey() {
  19814. const { geometry } = this;
  19815. let cacheKey = '';
  19816. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  19817. const attribute = geometry.attributes[ name ];
  19818. cacheKey += name + ',';
  19819. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  19820. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  19821. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  19822. if ( attribute.normalized ) cacheKey += 'n,';
  19823. }
  19824. // structural equality isn't sufficient for morph targets since the
  19825. // data are maintained in textures. only if the targets are all equal
  19826. // the texture and thus the instance of `MorphNode` can be shared.
  19827. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  19828. const targets = geometry.morphAttributes[ name ];
  19829. cacheKey += 'morph-' + name + ',';
  19830. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  19831. const attribute = targets[ i ];
  19832. cacheKey += attribute.id + ',';
  19833. }
  19834. }
  19835. if ( geometry.index ) {
  19836. cacheKey += 'index,';
  19837. }
  19838. return cacheKey;
  19839. }
  19840. /**
  19841. * Returns the render object's material cache key.
  19842. *
  19843. * The material cache key is part of the render object cache key.
  19844. *
  19845. * @return {number} The material cache key.
  19846. */
  19847. getMaterialCacheKey() {
  19848. const { object, material, renderer } = this;
  19849. let cacheKey = material.customProgramCacheKey();
  19850. for ( const property of getKeys( material ) ) {
  19851. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  19852. const value = material[ property ];
  19853. let valueKey;
  19854. if ( value !== null ) {
  19855. // some material values require a formatting
  19856. const type = typeof value;
  19857. if ( type === 'number' ) {
  19858. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  19859. } else if ( type === 'object' ) {
  19860. valueKey = '{';
  19861. if ( value.isTexture ) {
  19862. valueKey += value.mapping;
  19863. // WebGPU must honor the sampler data because they are part of the bindings
  19864. if ( renderer.backend.isWebGPUBackend === true ) {
  19865. valueKey += value.magFilter;
  19866. valueKey += value.minFilter;
  19867. valueKey += value.wrapS;
  19868. valueKey += value.wrapT;
  19869. valueKey += value.wrapR;
  19870. }
  19871. }
  19872. valueKey += '}';
  19873. } else {
  19874. valueKey = String( value );
  19875. }
  19876. } else {
  19877. valueKey = String( value );
  19878. }
  19879. cacheKey += /*property + ':' +*/ valueKey + ',';
  19880. }
  19881. cacheKey += this.clippingContextCacheKey + ',';
  19882. if ( object.geometry ) {
  19883. cacheKey += this.getGeometryCacheKey();
  19884. }
  19885. if ( object.skeleton ) {
  19886. cacheKey += object.skeleton.bones.length + ',';
  19887. }
  19888. if ( object.isBatchedMesh ) {
  19889. cacheKey += object._matricesTexture.uuid + ',';
  19890. if ( object._colorsTexture !== null ) {
  19891. cacheKey += object._colorsTexture.uuid + ',';
  19892. }
  19893. }
  19894. if ( object.isInstancedMesh || object.count > 1 ) {
  19895. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  19896. cacheKey += object.uuid + ',';
  19897. }
  19898. cacheKey += object.receiveShadow + ',';
  19899. return hashString( cacheKey );
  19900. }
  19901. /**
  19902. * Whether the geometry requires an update or not.
  19903. *
  19904. * @type {boolean}
  19905. * @readonly
  19906. */
  19907. get needsGeometryUpdate() {
  19908. if ( this.geometry.id !== this.object.geometry.id ) return true;
  19909. if ( this.attributes !== null ) {
  19910. const attributesId = this.attributesId;
  19911. for ( const name in attributesId ) {
  19912. const attribute = this.geometry.getAttribute( name );
  19913. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  19914. return true;
  19915. }
  19916. }
  19917. }
  19918. return false;
  19919. }
  19920. /**
  19921. * Whether the render object requires an update or not.
  19922. *
  19923. * Note: There are two distinct places where render objects are checked for an update.
  19924. *
  19925. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  19926. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  19927. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  19928. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  19929. * a need for a refresh due to material, geometry or object related value changes.
  19930. *
  19931. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  19932. * that performs the 'needsUpdate' check.
  19933. *
  19934. * @type {boolean}
  19935. * @readonly
  19936. */
  19937. get needsUpdate() {
  19938. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  19939. }
  19940. /**
  19941. * Returns the dynamic cache key which represents a key that is computed per draw command.
  19942. *
  19943. * @return {number} The cache key.
  19944. */
  19945. getDynamicCacheKey() {
  19946. let cacheKey = 0;
  19947. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  19948. // the renderer is inside a shadow pass.
  19949. if ( this.material.isShadowPassMaterial !== true ) {
  19950. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  19951. }
  19952. if ( this.camera.isArrayCamera ) {
  19953. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  19954. }
  19955. if ( this.object.receiveShadow ) {
  19956. cacheKey = hash$1( cacheKey, 1 );
  19957. }
  19958. return cacheKey;
  19959. }
  19960. /**
  19961. * Returns the render object's cache key.
  19962. *
  19963. * @return {number} The cache key.
  19964. */
  19965. getCacheKey() {
  19966. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  19967. }
  19968. /**
  19969. * Frees internal resources.
  19970. */
  19971. dispose() {
  19972. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  19973. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  19974. this.onDispose();
  19975. }
  19976. }
  19977. const _chainKeys$5 = [];
  19978. /**
  19979. * This module manages the render objects of the renderer.
  19980. *
  19981. * @private
  19982. */
  19983. class RenderObjects {
  19984. /**
  19985. * Constructs a new render object management component.
  19986. *
  19987. * @param {Renderer} renderer - The renderer.
  19988. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19989. * @param {Geometries} geometries - Renderer component for managing geometries.
  19990. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  19991. * @param {Bindings} bindings - Renderer component for managing bindings.
  19992. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19993. */
  19994. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  19995. /**
  19996. * The renderer.
  19997. *
  19998. * @type {Renderer}
  19999. */
  20000. this.renderer = renderer;
  20001. /**
  20002. * Renderer component for managing nodes related logic.
  20003. *
  20004. * @type {Nodes}
  20005. */
  20006. this.nodes = nodes;
  20007. /**
  20008. * Renderer component for managing geometries.
  20009. *
  20010. * @type {Geometries}
  20011. */
  20012. this.geometries = geometries;
  20013. /**
  20014. * Renderer component for managing pipelines.
  20015. *
  20016. * @type {Pipelines}
  20017. */
  20018. this.pipelines = pipelines;
  20019. /**
  20020. * Renderer component for managing bindings.
  20021. *
  20022. * @type {Bindings}
  20023. */
  20024. this.bindings = bindings;
  20025. /**
  20026. * Renderer component for managing metrics and monitoring data.
  20027. *
  20028. * @type {Info}
  20029. */
  20030. this.info = info;
  20031. /**
  20032. * A dictionary that manages render contexts in chain maps
  20033. * for each pass ID.
  20034. *
  20035. * @type {Object<string,ChainMap>}
  20036. */
  20037. this.chainMaps = {};
  20038. }
  20039. /**
  20040. * Returns a render object for the given object and state data.
  20041. *
  20042. * @param {Object3D} object - The 3D object.
  20043. * @param {Material} material - The 3D object's material.
  20044. * @param {Scene} scene - The scene the 3D object belongs to.
  20045. * @param {Camera} camera - The camera the 3D object should be rendered with.
  20046. * @param {LightsNode} lightsNode - The lights node.
  20047. * @param {RenderContext} renderContext - The render context.
  20048. * @param {ClippingContext} clippingContext - The clipping context.
  20049. * @param {string} [passId] - An optional ID for identifying the pass.
  20050. * @return {RenderObject} The render object.
  20051. */
  20052. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20053. const chainMap = this.getChainMap( passId );
  20054. // reuse chainArray
  20055. _chainKeys$5[ 0 ] = object;
  20056. _chainKeys$5[ 1 ] = material;
  20057. _chainKeys$5[ 2 ] = renderContext;
  20058. _chainKeys$5[ 3 ] = lightsNode;
  20059. let renderObject = chainMap.get( _chainKeys$5 );
  20060. if ( renderObject === undefined ) {
  20061. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20062. chainMap.set( _chainKeys$5, renderObject );
  20063. } else {
  20064. renderObject.updateClipping( clippingContext );
  20065. if ( renderObject.needsGeometryUpdate ) {
  20066. renderObject.setGeometry( object.geometry );
  20067. }
  20068. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  20069. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  20070. renderObject.dispose();
  20071. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  20072. } else {
  20073. renderObject.version = material.version;
  20074. }
  20075. }
  20076. }
  20077. _chainKeys$5.length = 0;
  20078. return renderObject;
  20079. }
  20080. /**
  20081. * Returns a chain map for the given pass ID.
  20082. *
  20083. * @param {string} [passId='default'] - The pass ID.
  20084. * @return {ChainMap} The chain map.
  20085. */
  20086. getChainMap( passId = 'default' ) {
  20087. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  20088. }
  20089. /**
  20090. * Frees internal resources.
  20091. */
  20092. dispose() {
  20093. this.chainMaps = {};
  20094. }
  20095. /**
  20096. * Factory method for creating render objects with the given list of parameters.
  20097. *
  20098. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20099. * @param {Geometries} geometries - Renderer component for managing geometries.
  20100. * @param {Renderer} renderer - The renderer.
  20101. * @param {Object3D} object - The 3D object.
  20102. * @param {Material} material - The object's material.
  20103. * @param {Scene} scene - The scene the 3D object belongs to.
  20104. * @param {Camera} camera - The camera the object should be rendered with.
  20105. * @param {LightsNode} lightsNode - The lights node.
  20106. * @param {RenderContext} renderContext - The render context.
  20107. * @param {ClippingContext} clippingContext - The clipping context.
  20108. * @param {string} [passId] - An optional ID for identifying the pass.
  20109. * @return {RenderObject} The render object.
  20110. */
  20111. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  20112. const chainMap = this.getChainMap( passId );
  20113. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  20114. renderObject.onDispose = () => {
  20115. this.pipelines.delete( renderObject );
  20116. this.bindings.delete( renderObject );
  20117. this.nodes.delete( renderObject );
  20118. chainMap.delete( renderObject.getChainArray() );
  20119. };
  20120. return renderObject;
  20121. }
  20122. }
  20123. /**
  20124. * Data structure for the renderer. It is intended to manage
  20125. * data of objects in dictionaries.
  20126. *
  20127. * @private
  20128. */
  20129. class DataMap {
  20130. /**
  20131. * Constructs a new data map.
  20132. */
  20133. constructor() {
  20134. /**
  20135. * `DataMap` internally uses a weak map
  20136. * to manage its data.
  20137. *
  20138. * @type {WeakMap<Object, Object>}
  20139. */
  20140. this.data = new WeakMap();
  20141. }
  20142. /**
  20143. * Returns the dictionary for the given object.
  20144. *
  20145. * @param {Object} object - The object.
  20146. * @return {Object} The dictionary.
  20147. */
  20148. get( object ) {
  20149. let map = this.data.get( object );
  20150. if ( map === undefined ) {
  20151. map = {};
  20152. this.data.set( object, map );
  20153. }
  20154. return map;
  20155. }
  20156. /**
  20157. * Deletes the dictionary for the given object.
  20158. *
  20159. * @param {Object} object - The object.
  20160. * @return {?Object} The deleted dictionary.
  20161. */
  20162. delete( object ) {
  20163. let map = null;
  20164. if ( this.data.has( object ) ) {
  20165. map = this.data.get( object );
  20166. this.data.delete( object );
  20167. }
  20168. return map;
  20169. }
  20170. /**
  20171. * Returns `true` if the given object has a dictionary defined.
  20172. *
  20173. * @param {Object} object - The object to test.
  20174. * @return {boolean} Whether a dictionary is defined or not.
  20175. */
  20176. has( object ) {
  20177. return this.data.has( object );
  20178. }
  20179. /**
  20180. * Frees internal resources.
  20181. */
  20182. dispose() {
  20183. this.data = new WeakMap();
  20184. }
  20185. }
  20186. const AttributeType = {
  20187. VERTEX: 1,
  20188. INDEX: 2,
  20189. STORAGE: 3,
  20190. INDIRECT: 4
  20191. };
  20192. // size of a chunk in bytes (STD140 layout)
  20193. const GPU_CHUNK_BYTES = 16;
  20194. // @TODO: Move to src/constants.js
  20195. const BlendColorFactor = 211;
  20196. const OneMinusBlendColorFactor = 212;
  20197. /**
  20198. * This renderer module manages geometry attributes.
  20199. *
  20200. * @private
  20201. * @augments DataMap
  20202. */
  20203. class Attributes extends DataMap {
  20204. /**
  20205. * Constructs a new attribute management component.
  20206. *
  20207. * @param {Backend} backend - The renderer's backend.
  20208. */
  20209. constructor( backend ) {
  20210. super();
  20211. /**
  20212. * The renderer's backend.
  20213. *
  20214. * @type {Backend}
  20215. */
  20216. this.backend = backend;
  20217. }
  20218. /**
  20219. * Deletes the data for the given attribute.
  20220. *
  20221. * @param {BufferAttribute} attribute - The attribute.
  20222. * @return {?Object} The deleted attribute data.
  20223. */
  20224. delete( attribute ) {
  20225. const attributeData = super.delete( attribute );
  20226. if ( attributeData !== null ) {
  20227. this.backend.destroyAttribute( attribute );
  20228. }
  20229. return attributeData;
  20230. }
  20231. /**
  20232. * Updates the given attribute. This method creates attribute buffers
  20233. * for new attributes and updates data for existing ones.
  20234. *
  20235. * @param {BufferAttribute} attribute - The attribute to update.
  20236. * @param {number} type - The attribute type.
  20237. */
  20238. update( attribute, type ) {
  20239. const data = this.get( attribute );
  20240. if ( data.version === undefined ) {
  20241. if ( type === AttributeType.VERTEX ) {
  20242. this.backend.createAttribute( attribute );
  20243. } else if ( type === AttributeType.INDEX ) {
  20244. this.backend.createIndexAttribute( attribute );
  20245. } else if ( type === AttributeType.STORAGE ) {
  20246. this.backend.createStorageAttribute( attribute );
  20247. } else if ( type === AttributeType.INDIRECT ) {
  20248. this.backend.createIndirectStorageAttribute( attribute );
  20249. }
  20250. data.version = this._getBufferAttribute( attribute ).version;
  20251. } else {
  20252. const bufferAttribute = this._getBufferAttribute( attribute );
  20253. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  20254. this.backend.updateAttribute( attribute );
  20255. data.version = bufferAttribute.version;
  20256. }
  20257. }
  20258. }
  20259. /**
  20260. * Utility method for handling interleaved buffer attributes correctly.
  20261. * To process them, their `InterleavedBuffer` is returned.
  20262. *
  20263. * @param {BufferAttribute} attribute - The attribute.
  20264. * @return {BufferAttribute|InterleavedBuffer}
  20265. */
  20266. _getBufferAttribute( attribute ) {
  20267. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  20268. return attribute;
  20269. }
  20270. }
  20271. /**
  20272. * Returns the wireframe version for the given geometry.
  20273. *
  20274. * @private
  20275. * @function
  20276. * @param {BufferGeometry} geometry - The geometry.
  20277. * @return {number} The version.
  20278. */
  20279. function getWireframeVersion( geometry ) {
  20280. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  20281. }
  20282. /**
  20283. * Returns a wireframe index attribute for the given geometry.
  20284. *
  20285. * @private
  20286. * @function
  20287. * @param {BufferGeometry} geometry - The geometry.
  20288. * @return {BufferAttribute} The wireframe index attribute.
  20289. */
  20290. function getWireframeIndex( geometry ) {
  20291. const indices = [];
  20292. const geometryIndex = geometry.index;
  20293. const geometryPosition = geometry.attributes.position;
  20294. if ( geometryIndex !== null ) {
  20295. const array = geometryIndex.array;
  20296. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  20297. const a = array[ i + 0 ];
  20298. const b = array[ i + 1 ];
  20299. const c = array[ i + 2 ];
  20300. indices.push( a, b, b, c, c, a );
  20301. }
  20302. } else {
  20303. const array = geometryPosition.array;
  20304. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  20305. const a = i + 0;
  20306. const b = i + 1;
  20307. const c = i + 2;
  20308. indices.push( a, b, b, c, c, a );
  20309. }
  20310. }
  20311. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  20312. attribute.version = getWireframeVersion( geometry );
  20313. return attribute;
  20314. }
  20315. /**
  20316. * This renderer module manages geometries.
  20317. *
  20318. * @private
  20319. * @augments DataMap
  20320. */
  20321. class Geometries extends DataMap {
  20322. /**
  20323. * Constructs a new geometry management component.
  20324. *
  20325. * @param {Attributes} attributes - Renderer component for managing attributes.
  20326. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20327. */
  20328. constructor( attributes, info ) {
  20329. super();
  20330. /**
  20331. * Renderer component for managing attributes.
  20332. *
  20333. * @type {Attributes}
  20334. */
  20335. this.attributes = attributes;
  20336. /**
  20337. * Renderer component for managing metrics and monitoring data.
  20338. *
  20339. * @type {Info}
  20340. */
  20341. this.info = info;
  20342. /**
  20343. * Weak Map for managing attributes for wireframe rendering.
  20344. *
  20345. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  20346. */
  20347. this.wireframes = new WeakMap();
  20348. /**
  20349. * This Weak Map is used to make sure buffer attributes are
  20350. * updated only once per render call.
  20351. *
  20352. * @type {WeakMap<BufferAttribute,number>}
  20353. */
  20354. this.attributeCall = new WeakMap();
  20355. }
  20356. /**
  20357. * Returns `true` if the given render object has an initialized geometry.
  20358. *
  20359. * @param {RenderObject} renderObject - The render object.
  20360. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  20361. */
  20362. has( renderObject ) {
  20363. const geometry = renderObject.geometry;
  20364. return super.has( geometry ) && this.get( geometry ).initialized === true;
  20365. }
  20366. /**
  20367. * Prepares the geometry of the given render object for rendering.
  20368. *
  20369. * @param {RenderObject} renderObject - The render object.
  20370. */
  20371. updateForRender( renderObject ) {
  20372. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  20373. this.updateAttributes( renderObject );
  20374. }
  20375. /**
  20376. * Initializes the geometry of the given render object.
  20377. *
  20378. * @param {RenderObject} renderObject - The render object.
  20379. */
  20380. initGeometry( renderObject ) {
  20381. const geometry = renderObject.geometry;
  20382. const geometryData = this.get( geometry );
  20383. geometryData.initialized = true;
  20384. this.info.memory.geometries ++;
  20385. const onDispose = () => {
  20386. this.info.memory.geometries --;
  20387. const index = geometry.index;
  20388. const geometryAttributes = renderObject.getAttributes();
  20389. if ( index !== null ) {
  20390. this.attributes.delete( index );
  20391. }
  20392. for ( const geometryAttribute of geometryAttributes ) {
  20393. this.attributes.delete( geometryAttribute );
  20394. }
  20395. const wireframeAttribute = this.wireframes.get( geometry );
  20396. if ( wireframeAttribute !== undefined ) {
  20397. this.attributes.delete( wireframeAttribute );
  20398. }
  20399. geometry.removeEventListener( 'dispose', onDispose );
  20400. };
  20401. geometry.addEventListener( 'dispose', onDispose );
  20402. }
  20403. /**
  20404. * Updates the geometry attributes of the given render object.
  20405. *
  20406. * @param {RenderObject} renderObject - The render object.
  20407. */
  20408. updateAttributes( renderObject ) {
  20409. // attributes
  20410. const attributes = renderObject.getAttributes();
  20411. for ( const attribute of attributes ) {
  20412. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  20413. this.updateAttribute( attribute, AttributeType.STORAGE );
  20414. } else {
  20415. this.updateAttribute( attribute, AttributeType.VERTEX );
  20416. }
  20417. }
  20418. // indexes
  20419. const index = this.getIndex( renderObject );
  20420. if ( index !== null ) {
  20421. this.updateAttribute( index, AttributeType.INDEX );
  20422. }
  20423. // indirect
  20424. const indirect = renderObject.geometry.indirect;
  20425. if ( indirect !== null ) {
  20426. this.updateAttribute( indirect, AttributeType.INDIRECT );
  20427. }
  20428. }
  20429. /**
  20430. * Updates the given attribute.
  20431. *
  20432. * @param {BufferAttribute} attribute - The attribute to update.
  20433. * @param {number} type - The attribute type.
  20434. */
  20435. updateAttribute( attribute, type ) {
  20436. const callId = this.info.render.calls;
  20437. if ( ! attribute.isInterleavedBufferAttribute ) {
  20438. if ( this.attributeCall.get( attribute ) !== callId ) {
  20439. this.attributes.update( attribute, type );
  20440. this.attributeCall.set( attribute, callId );
  20441. }
  20442. } else {
  20443. if ( this.attributeCall.get( attribute ) === undefined ) {
  20444. this.attributes.update( attribute, type );
  20445. this.attributeCall.set( attribute, callId );
  20446. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  20447. this.attributes.update( attribute, type );
  20448. this.attributeCall.set( attribute.data, callId );
  20449. this.attributeCall.set( attribute, callId );
  20450. }
  20451. }
  20452. }
  20453. /**
  20454. * Returns the indirect buffer attribute of the given render object.
  20455. *
  20456. * @param {RenderObject} renderObject - The render object.
  20457. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  20458. */
  20459. getIndirect( renderObject ) {
  20460. return renderObject.geometry.indirect;
  20461. }
  20462. /**
  20463. * Returns the index of the given render object's geometry. This is implemented
  20464. * in a method to return a wireframe index if necessary.
  20465. *
  20466. * @param {RenderObject} renderObject - The render object.
  20467. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  20468. */
  20469. getIndex( renderObject ) {
  20470. const { geometry, material } = renderObject;
  20471. let index = geometry.index;
  20472. if ( material.wireframe === true ) {
  20473. const wireframes = this.wireframes;
  20474. let wireframeAttribute = wireframes.get( geometry );
  20475. if ( wireframeAttribute === undefined ) {
  20476. wireframeAttribute = getWireframeIndex( geometry );
  20477. wireframes.set( geometry, wireframeAttribute );
  20478. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  20479. this.attributes.delete( wireframeAttribute );
  20480. wireframeAttribute = getWireframeIndex( geometry );
  20481. wireframes.set( geometry, wireframeAttribute );
  20482. }
  20483. index = wireframeAttribute;
  20484. }
  20485. return index;
  20486. }
  20487. }
  20488. /**
  20489. * This renderer module provides a series of statistical information
  20490. * about the GPU memory and the rendering process. Useful for debugging
  20491. * and monitoring.
  20492. */
  20493. class Info {
  20494. /**
  20495. * Constructs a new info component.
  20496. */
  20497. constructor() {
  20498. /**
  20499. * Whether frame related metrics should automatically
  20500. * be resetted or not. This property should be set to `false`
  20501. * by apps which manage their own animation loop. They must
  20502. * then call `renderer.info.reset()` once per frame manually.
  20503. *
  20504. * @type {boolean}
  20505. * @default true
  20506. */
  20507. this.autoReset = true;
  20508. /**
  20509. * The current frame ID. This ID is managed
  20510. * by `NodeFrame`.
  20511. *
  20512. * @type {number}
  20513. * @readonly
  20514. * @default 0
  20515. */
  20516. this.frame = 0;
  20517. /**
  20518. * The number of render calls since the
  20519. * app has been started.
  20520. *
  20521. * @type {number}
  20522. * @readonly
  20523. * @default 0
  20524. */
  20525. this.calls = 0;
  20526. /**
  20527. * Render related metrics.
  20528. *
  20529. * @type {Object}
  20530. * @readonly
  20531. * @property {number} calls - The number of render calls since the app has been started.
  20532. * @property {number} frameCalls - The number of render calls of the current frame.
  20533. * @property {number} drawCalls - The number of draw calls of the current frame.
  20534. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  20535. * @property {number} points - The number of rendered point primitives of the current frame.
  20536. * @property {number} lines - The number of rendered line primitives of the current frame.
  20537. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  20538. */
  20539. this.render = {
  20540. calls: 0,
  20541. frameCalls: 0,
  20542. drawCalls: 0,
  20543. triangles: 0,
  20544. points: 0,
  20545. lines: 0,
  20546. timestamp: 0,
  20547. };
  20548. /**
  20549. * Compute related metrics.
  20550. *
  20551. * @type {Object}
  20552. * @readonly
  20553. * @property {number} calls - The number of compute calls since the app has been started.
  20554. * @property {number} frameCalls - The number of compute calls of the current frame.
  20555. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  20556. */
  20557. this.compute = {
  20558. calls: 0,
  20559. frameCalls: 0,
  20560. timestamp: 0
  20561. };
  20562. /**
  20563. * Memory related metrics.
  20564. *
  20565. * @type {Object}
  20566. * @readonly
  20567. * @property {number} geometries - The number of active geometries.
  20568. * @property {number} frameCalls - The number of active textures.
  20569. */
  20570. this.memory = {
  20571. geometries: 0,
  20572. textures: 0
  20573. };
  20574. }
  20575. /**
  20576. * This method should be executed per draw call and updates the corresponding metrics.
  20577. *
  20578. * @param {Object3D} object - The 3D object that is going to be rendered.
  20579. * @param {number} count - The vertex or index count.
  20580. * @param {number} instanceCount - The instance count.
  20581. */
  20582. update( object, count, instanceCount ) {
  20583. this.render.drawCalls ++;
  20584. if ( object.isMesh || object.isSprite ) {
  20585. this.render.triangles += instanceCount * ( count / 3 );
  20586. } else if ( object.isPoints ) {
  20587. this.render.points += instanceCount * count;
  20588. } else if ( object.isLineSegments ) {
  20589. this.render.lines += instanceCount * ( count / 2 );
  20590. } else if ( object.isLine ) {
  20591. this.render.lines += instanceCount * ( count - 1 );
  20592. } else {
  20593. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  20594. }
  20595. }
  20596. /**
  20597. * Resets frame related metrics.
  20598. */
  20599. reset() {
  20600. this.render.drawCalls = 0;
  20601. this.render.frameCalls = 0;
  20602. this.compute.frameCalls = 0;
  20603. this.render.triangles = 0;
  20604. this.render.points = 0;
  20605. this.render.lines = 0;
  20606. }
  20607. /**
  20608. * Performs a complete reset of the object.
  20609. */
  20610. dispose() {
  20611. this.reset();
  20612. this.calls = 0;
  20613. this.render.calls = 0;
  20614. this.compute.calls = 0;
  20615. this.render.timestamp = 0;
  20616. this.compute.timestamp = 0;
  20617. this.memory.geometries = 0;
  20618. this.memory.textures = 0;
  20619. }
  20620. }
  20621. /**
  20622. * Abstract class for representing pipelines.
  20623. *
  20624. * @private
  20625. * @abstract
  20626. */
  20627. class Pipeline {
  20628. /**
  20629. * Constructs a new pipeline.
  20630. *
  20631. * @param {string} cacheKey - The pipeline's cache key.
  20632. */
  20633. constructor( cacheKey ) {
  20634. /**
  20635. * The pipeline's cache key.
  20636. *
  20637. * @type {string}
  20638. */
  20639. this.cacheKey = cacheKey;
  20640. /**
  20641. * How often the pipeline is currently in use.
  20642. *
  20643. * @type {number}
  20644. * @default 0
  20645. */
  20646. this.usedTimes = 0;
  20647. }
  20648. }
  20649. /**
  20650. * Class for representing render pipelines.
  20651. *
  20652. * @private
  20653. * @augments Pipeline
  20654. */
  20655. class RenderPipeline extends Pipeline {
  20656. /**
  20657. * Constructs a new render pipeline.
  20658. *
  20659. * @param {string} cacheKey - The pipeline's cache key.
  20660. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  20661. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  20662. */
  20663. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  20664. super( cacheKey );
  20665. /**
  20666. * The pipeline's vertex shader.
  20667. *
  20668. * @type {ProgrammableStage}
  20669. */
  20670. this.vertexProgram = vertexProgram;
  20671. /**
  20672. * The pipeline's fragment shader.
  20673. *
  20674. * @type {ProgrammableStage}
  20675. */
  20676. this.fragmentProgram = fragmentProgram;
  20677. }
  20678. }
  20679. /**
  20680. * Class for representing compute pipelines.
  20681. *
  20682. * @private
  20683. * @augments Pipeline
  20684. */
  20685. class ComputePipeline extends Pipeline {
  20686. /**
  20687. * Constructs a new render pipeline.
  20688. *
  20689. * @param {string} cacheKey - The pipeline's cache key.
  20690. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  20691. */
  20692. constructor( cacheKey, computeProgram ) {
  20693. super( cacheKey );
  20694. /**
  20695. * The pipeline's compute shader.
  20696. *
  20697. * @type {ProgrammableStage}
  20698. */
  20699. this.computeProgram = computeProgram;
  20700. /**
  20701. * This flag can be used for type testing.
  20702. *
  20703. * @type {boolean}
  20704. * @readonly
  20705. * @default true
  20706. */
  20707. this.isComputePipeline = true;
  20708. }
  20709. }
  20710. let _id$8 = 0;
  20711. /**
  20712. * Class for representing programmable stages which are vertex,
  20713. * fragment or compute shaders. Unlike fixed-function states (like blending),
  20714. * they represent the programmable part of a pipeline.
  20715. *
  20716. * @private
  20717. */
  20718. class ProgrammableStage {
  20719. /**
  20720. * Constructs a new programmable stage.
  20721. *
  20722. * @param {string} code - The shader code.
  20723. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  20724. * @param {string} name - The name of the shader.
  20725. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20726. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20727. */
  20728. constructor( code, stage, name, transforms = null, attributes = null ) {
  20729. /**
  20730. * The id of the programmable stage.
  20731. *
  20732. * @type {number}
  20733. */
  20734. this.id = _id$8 ++;
  20735. /**
  20736. * The shader code.
  20737. *
  20738. * @type {string}
  20739. */
  20740. this.code = code;
  20741. /**
  20742. * The type of stage.
  20743. *
  20744. * @type {string}
  20745. */
  20746. this.stage = stage;
  20747. /**
  20748. * The name of the stage.
  20749. * This is used for debugging purposes.
  20750. *
  20751. * @type {string}
  20752. */
  20753. this.name = name;
  20754. /**
  20755. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20756. *
  20757. * @type {?Array<Object>}
  20758. */
  20759. this.transforms = transforms;
  20760. /**
  20761. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20762. *
  20763. * @type {?Array<Object>}
  20764. */
  20765. this.attributes = attributes;
  20766. /**
  20767. * How often the programmable stage is currently in use.
  20768. *
  20769. * @type {number}
  20770. * @default 0
  20771. */
  20772. this.usedTimes = 0;
  20773. }
  20774. }
  20775. /**
  20776. * This renderer module manages the pipelines of the renderer.
  20777. *
  20778. * @private
  20779. * @augments DataMap
  20780. */
  20781. class Pipelines extends DataMap {
  20782. /**
  20783. * Constructs a new pipeline management component.
  20784. *
  20785. * @param {Backend} backend - The renderer's backend.
  20786. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20787. */
  20788. constructor( backend, nodes ) {
  20789. super();
  20790. /**
  20791. * The renderer's backend.
  20792. *
  20793. * @type {Backend}
  20794. */
  20795. this.backend = backend;
  20796. /**
  20797. * Renderer component for managing nodes related logic.
  20798. *
  20799. * @type {Nodes}
  20800. */
  20801. this.nodes = nodes;
  20802. /**
  20803. * A references to the bindings management component.
  20804. * This reference will be set inside the `Bindings`
  20805. * constructor.
  20806. *
  20807. * @type {?Bindings}
  20808. * @default null
  20809. */
  20810. this.bindings = null;
  20811. /**
  20812. * Internal cache for maintaining pipelines.
  20813. * The key of the map is a cache key, the value the pipeline.
  20814. *
  20815. * @type {Map<string,Pipeline>}
  20816. */
  20817. this.caches = new Map();
  20818. /**
  20819. * This dictionary maintains for each shader stage type (vertex,
  20820. * fragment and compute) the programmable stage objects which
  20821. * represent the actual shader code.
  20822. *
  20823. * @type {Object<string,Map<string, ProgrammableStage>>}
  20824. */
  20825. this.programs = {
  20826. vertex: new Map(),
  20827. fragment: new Map(),
  20828. compute: new Map()
  20829. };
  20830. }
  20831. /**
  20832. * Returns a compute pipeline for the given compute node.
  20833. *
  20834. * @param {Node} computeNode - The compute node.
  20835. * @param {Array<BindGroup>} bindings - The bindings.
  20836. * @return {ComputePipeline} The compute pipeline.
  20837. */
  20838. getForCompute( computeNode, bindings ) {
  20839. const { backend } = this;
  20840. const data = this.get( computeNode );
  20841. if ( this._needsComputeUpdate( computeNode ) ) {
  20842. const previousPipeline = data.pipeline;
  20843. if ( previousPipeline ) {
  20844. previousPipeline.usedTimes --;
  20845. previousPipeline.computeProgram.usedTimes --;
  20846. }
  20847. // get shader
  20848. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  20849. // programmable stage
  20850. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  20851. if ( stageCompute === undefined ) {
  20852. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  20853. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  20854. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  20855. backend.createProgram( stageCompute );
  20856. }
  20857. // determine compute pipeline
  20858. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  20859. let pipeline = this.caches.get( cacheKey );
  20860. if ( pipeline === undefined ) {
  20861. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  20862. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  20863. }
  20864. // keep track of all used times
  20865. pipeline.usedTimes ++;
  20866. stageCompute.usedTimes ++;
  20867. //
  20868. data.version = computeNode.version;
  20869. data.pipeline = pipeline;
  20870. }
  20871. return data.pipeline;
  20872. }
  20873. /**
  20874. * Returns a render pipeline for the given render object.
  20875. *
  20876. * @param {RenderObject} renderObject - The render object.
  20877. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  20878. * @return {RenderPipeline} The render pipeline.
  20879. */
  20880. getForRender( renderObject, promises = null ) {
  20881. const { backend } = this;
  20882. const data = this.get( renderObject );
  20883. if ( this._needsRenderUpdate( renderObject ) ) {
  20884. const previousPipeline = data.pipeline;
  20885. if ( previousPipeline ) {
  20886. previousPipeline.usedTimes --;
  20887. previousPipeline.vertexProgram.usedTimes --;
  20888. previousPipeline.fragmentProgram.usedTimes --;
  20889. }
  20890. // get shader
  20891. const nodeBuilderState = renderObject.getNodeBuilderState();
  20892. const name = renderObject.material ? renderObject.material.name : '';
  20893. // programmable stages
  20894. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  20895. if ( stageVertex === undefined ) {
  20896. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  20897. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  20898. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  20899. backend.createProgram( stageVertex );
  20900. }
  20901. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  20902. if ( stageFragment === undefined ) {
  20903. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  20904. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  20905. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  20906. backend.createProgram( stageFragment );
  20907. }
  20908. // determine render pipeline
  20909. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  20910. let pipeline = this.caches.get( cacheKey );
  20911. if ( pipeline === undefined ) {
  20912. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  20913. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  20914. } else {
  20915. renderObject.pipeline = pipeline;
  20916. }
  20917. // keep track of all used times
  20918. pipeline.usedTimes ++;
  20919. stageVertex.usedTimes ++;
  20920. stageFragment.usedTimes ++;
  20921. //
  20922. data.pipeline = pipeline;
  20923. }
  20924. return data.pipeline;
  20925. }
  20926. /**
  20927. * Deletes the pipeline for the given render object.
  20928. *
  20929. * @param {RenderObject} object - The render object.
  20930. * @return {?Object} The deleted dictionary.
  20931. */
  20932. delete( object ) {
  20933. const pipeline = this.get( object ).pipeline;
  20934. if ( pipeline ) {
  20935. // pipeline
  20936. pipeline.usedTimes --;
  20937. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  20938. // programs
  20939. if ( pipeline.isComputePipeline ) {
  20940. pipeline.computeProgram.usedTimes --;
  20941. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  20942. } else {
  20943. pipeline.fragmentProgram.usedTimes --;
  20944. pipeline.vertexProgram.usedTimes --;
  20945. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  20946. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  20947. }
  20948. }
  20949. return super.delete( object );
  20950. }
  20951. /**
  20952. * Frees internal resources.
  20953. */
  20954. dispose() {
  20955. super.dispose();
  20956. this.caches = new Map();
  20957. this.programs = {
  20958. vertex: new Map(),
  20959. fragment: new Map(),
  20960. compute: new Map()
  20961. };
  20962. }
  20963. /**
  20964. * Updates the pipeline for the given render object.
  20965. *
  20966. * @param {RenderObject} renderObject - The render object.
  20967. */
  20968. updateForRender( renderObject ) {
  20969. this.getForRender( renderObject );
  20970. }
  20971. /**
  20972. * Returns a compute pipeline for the given parameters.
  20973. *
  20974. * @private
  20975. * @param {Node} computeNode - The compute node.
  20976. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  20977. * @param {string} cacheKey - The cache key.
  20978. * @param {Array<BindGroup>} bindings - The bindings.
  20979. * @return {ComputePipeline} The compute pipeline.
  20980. */
  20981. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  20982. // check for existing pipeline
  20983. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  20984. let pipeline = this.caches.get( cacheKey );
  20985. if ( pipeline === undefined ) {
  20986. pipeline = new ComputePipeline( cacheKey, stageCompute );
  20987. this.caches.set( cacheKey, pipeline );
  20988. this.backend.createComputePipeline( pipeline, bindings );
  20989. }
  20990. return pipeline;
  20991. }
  20992. /**
  20993. * Returns a render pipeline for the given parameters.
  20994. *
  20995. * @private
  20996. * @param {RenderObject} renderObject - The render object.
  20997. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  20998. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  20999. * @param {string} cacheKey - The cache key.
  21000. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  21001. * @return {ComputePipeline} The compute pipeline.
  21002. */
  21003. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  21004. // check for existing pipeline
  21005. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  21006. let pipeline = this.caches.get( cacheKey );
  21007. if ( pipeline === undefined ) {
  21008. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  21009. this.caches.set( cacheKey, pipeline );
  21010. renderObject.pipeline = pipeline;
  21011. // The `promises` array is `null` by default and only set to an empty array when
  21012. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  21013. // pending promises that resolve when the render pipelines are ready for rendering.
  21014. this.backend.createRenderPipeline( renderObject, promises );
  21015. }
  21016. return pipeline;
  21017. }
  21018. /**
  21019. * Computes a cache key representing a compute pipeline.
  21020. *
  21021. * @private
  21022. * @param {Node} computeNode - The compute node.
  21023. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  21024. * @return {string} The cache key.
  21025. */
  21026. _getComputeCacheKey( computeNode, stageCompute ) {
  21027. return computeNode.id + ',' + stageCompute.id;
  21028. }
  21029. /**
  21030. * Computes a cache key representing a render pipeline.
  21031. *
  21032. * @private
  21033. * @param {RenderObject} renderObject - The render object.
  21034. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  21035. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  21036. * @return {string} The cache key.
  21037. */
  21038. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  21039. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  21040. }
  21041. /**
  21042. * Releases the given pipeline.
  21043. *
  21044. * @private
  21045. * @param {Pipeline} pipeline - The pipeline to release.
  21046. */
  21047. _releasePipeline( pipeline ) {
  21048. this.caches.delete( pipeline.cacheKey );
  21049. }
  21050. /**
  21051. * Releases the shader program.
  21052. *
  21053. * @private
  21054. * @param {Object} program - The shader program to release.
  21055. */
  21056. _releaseProgram( program ) {
  21057. const code = program.code;
  21058. const stage = program.stage;
  21059. this.programs[ stage ].delete( code );
  21060. }
  21061. /**
  21062. * Returns `true` if the compute pipeline for the given compute node requires an update.
  21063. *
  21064. * @private
  21065. * @param {Node} computeNode - The compute node.
  21066. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  21067. */
  21068. _needsComputeUpdate( computeNode ) {
  21069. const data = this.get( computeNode );
  21070. return data.pipeline === undefined || data.version !== computeNode.version;
  21071. }
  21072. /**
  21073. * Returns `true` if the render pipeline for the given render object requires an update.
  21074. *
  21075. * @private
  21076. * @param {RenderObject} renderObject - The render object.
  21077. * @return {boolean} Whether the render object for the given render object requires an update or not.
  21078. */
  21079. _needsRenderUpdate( renderObject ) {
  21080. const data = this.get( renderObject );
  21081. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  21082. }
  21083. }
  21084. /**
  21085. * This renderer module manages the bindings of the renderer.
  21086. *
  21087. * @private
  21088. * @augments DataMap
  21089. */
  21090. class Bindings extends DataMap {
  21091. /**
  21092. * Constructs a new bindings management component.
  21093. *
  21094. * @param {Backend} backend - The renderer's backend.
  21095. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  21096. * @param {Textures} textures - Renderer component for managing textures.
  21097. * @param {Attributes} attributes - Renderer component for managing attributes.
  21098. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  21099. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21100. */
  21101. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  21102. super();
  21103. /**
  21104. * The renderer's backend.
  21105. *
  21106. * @type {Backend}
  21107. */
  21108. this.backend = backend;
  21109. /**
  21110. * Renderer component for managing textures.
  21111. *
  21112. * @type {Textures}
  21113. */
  21114. this.textures = textures;
  21115. /**
  21116. * Renderer component for managing pipelines.
  21117. *
  21118. * @type {Pipelines}
  21119. */
  21120. this.pipelines = pipelines;
  21121. /**
  21122. * Renderer component for managing attributes.
  21123. *
  21124. * @type {Attributes}
  21125. */
  21126. this.attributes = attributes;
  21127. /**
  21128. * Renderer component for managing nodes related logic.
  21129. *
  21130. * @type {Nodes}
  21131. */
  21132. this.nodes = nodes;
  21133. /**
  21134. * Renderer component for managing metrics and monitoring data.
  21135. *
  21136. * @type {Info}
  21137. */
  21138. this.info = info;
  21139. this.pipelines.bindings = this; // assign bindings to pipelines
  21140. }
  21141. /**
  21142. * Returns the bind groups for the given render object.
  21143. *
  21144. * @param {RenderObject} renderObject - The render object.
  21145. * @return {Array<BindGroup>} The bind groups.
  21146. */
  21147. getForRender( renderObject ) {
  21148. const bindings = renderObject.getBindings();
  21149. for ( const bindGroup of bindings ) {
  21150. const groupData = this.get( bindGroup );
  21151. if ( groupData.bindGroup === undefined ) {
  21152. // each object defines an array of bindings (ubos, textures, samplers etc.)
  21153. this._init( bindGroup );
  21154. this.backend.createBindings( bindGroup, bindings, 0 );
  21155. groupData.bindGroup = bindGroup;
  21156. }
  21157. }
  21158. return bindings;
  21159. }
  21160. /**
  21161. * Returns the bind groups for the given compute node.
  21162. *
  21163. * @param {Node} computeNode - The compute node.
  21164. * @return {Array<BindGroup>} The bind groups.
  21165. */
  21166. getForCompute( computeNode ) {
  21167. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  21168. for ( const bindGroup of bindings ) {
  21169. const groupData = this.get( bindGroup );
  21170. if ( groupData.bindGroup === undefined ) {
  21171. this._init( bindGroup );
  21172. this.backend.createBindings( bindGroup, bindings, 0 );
  21173. groupData.bindGroup = bindGroup;
  21174. }
  21175. }
  21176. return bindings;
  21177. }
  21178. /**
  21179. * Updates the bindings for the given compute node.
  21180. *
  21181. * @param {Node} computeNode - The compute node.
  21182. */
  21183. updateForCompute( computeNode ) {
  21184. this._updateBindings( this.getForCompute( computeNode ) );
  21185. }
  21186. /**
  21187. * Updates the bindings for the given render object.
  21188. *
  21189. * @param {RenderObject} renderObject - The render object.
  21190. */
  21191. updateForRender( renderObject ) {
  21192. this._updateBindings( this.getForRender( renderObject ) );
  21193. }
  21194. /**
  21195. * Updates the given array of bindings.
  21196. *
  21197. * @param {Array<BindGroup>} bindings - The bind groups.
  21198. */
  21199. _updateBindings( bindings ) {
  21200. for ( const bindGroup of bindings ) {
  21201. this._update( bindGroup, bindings );
  21202. }
  21203. }
  21204. /**
  21205. * Initializes the given bind group.
  21206. *
  21207. * @param {BindGroup} bindGroup - The bind group to initialize.
  21208. */
  21209. _init( bindGroup ) {
  21210. for ( const binding of bindGroup.bindings ) {
  21211. if ( binding.isSampledTexture ) {
  21212. this.textures.updateTexture( binding.texture );
  21213. } else if ( binding.isStorageBuffer ) {
  21214. const attribute = binding.attribute;
  21215. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21216. this.attributes.update( attribute, attributeType );
  21217. }
  21218. }
  21219. }
  21220. /**
  21221. * Updates the given bind group.
  21222. *
  21223. * @param {BindGroup} bindGroup - The bind group to update.
  21224. * @param {Array<BindGroup>} bindings - The bind groups.
  21225. */
  21226. _update( bindGroup, bindings ) {
  21227. const { backend } = this;
  21228. let needsBindingsUpdate = false;
  21229. let cacheBindings = true;
  21230. let cacheIndex = 0;
  21231. let version = 0;
  21232. // iterate over all bindings and check if buffer updates or a new binding group is required
  21233. for ( const binding of bindGroup.bindings ) {
  21234. if ( binding.isNodeUniformsGroup ) {
  21235. const updated = this.nodes.updateGroup( binding );
  21236. // every uniforms group is a uniform buffer. So if no update is required,
  21237. // we move one with the next binding. Otherwise the next if block will update the group.
  21238. if ( updated === false ) continue;
  21239. }
  21240. if ( binding.isStorageBuffer ) {
  21241. const attribute = binding.attribute;
  21242. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  21243. this.attributes.update( attribute, attributeType );
  21244. }
  21245. if ( binding.isUniformBuffer ) {
  21246. const updated = binding.update();
  21247. if ( updated ) {
  21248. backend.updateBinding( binding );
  21249. }
  21250. } else if ( binding.isSampledTexture ) {
  21251. const updated = binding.update();
  21252. // get the texture data after the update, to sync the texture reference from node
  21253. const texture = binding.texture;
  21254. const texturesTextureData = this.textures.get( texture );
  21255. if ( updated ) {
  21256. // version: update the texture data or create a new one
  21257. this.textures.updateTexture( texture );
  21258. // generation: update the bindings if a new texture has been created
  21259. if ( binding.generation !== texturesTextureData.generation ) {
  21260. binding.generation = texturesTextureData.generation;
  21261. needsBindingsUpdate = true;
  21262. cacheBindings = false;
  21263. }
  21264. }
  21265. const textureData = backend.get( texture );
  21266. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  21267. cacheBindings = false;
  21268. } else {
  21269. cacheIndex = cacheIndex * 10 + texture.id;
  21270. version += texture.version;
  21271. }
  21272. if ( texture.isStorageTexture === true ) {
  21273. const textureData = this.get( texture );
  21274. if ( binding.store === true ) {
  21275. textureData.needsMipmap = true;
  21276. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  21277. this.backend.generateMipmaps( texture );
  21278. textureData.needsMipmap = false;
  21279. }
  21280. }
  21281. } else if ( binding.isSampler ) {
  21282. binding.update();
  21283. }
  21284. }
  21285. if ( needsBindingsUpdate === true ) {
  21286. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  21287. }
  21288. }
  21289. }
  21290. /**
  21291. * Default sorting function for opaque render items.
  21292. *
  21293. * @private
  21294. * @function
  21295. * @param {Object} a - The first render item.
  21296. * @param {Object} b - The second render item.
  21297. * @return {number} A numeric value which defines the sort order.
  21298. */
  21299. function painterSortStable( a, b ) {
  21300. if ( a.groupOrder !== b.groupOrder ) {
  21301. return a.groupOrder - b.groupOrder;
  21302. } else if ( a.renderOrder !== b.renderOrder ) {
  21303. return a.renderOrder - b.renderOrder;
  21304. } else if ( a.z !== b.z ) {
  21305. return a.z - b.z;
  21306. } else {
  21307. return a.id - b.id;
  21308. }
  21309. }
  21310. /**
  21311. * Default sorting function for transparent render items.
  21312. *
  21313. * @private
  21314. * @function
  21315. * @param {Object} a - The first render item.
  21316. * @param {Object} b - The second render item.
  21317. * @return {number} A numeric value which defines the sort order.
  21318. */
  21319. function reversePainterSortStable( a, b ) {
  21320. if ( a.groupOrder !== b.groupOrder ) {
  21321. return a.groupOrder - b.groupOrder;
  21322. } else if ( a.renderOrder !== b.renderOrder ) {
  21323. return a.renderOrder - b.renderOrder;
  21324. } else if ( a.z !== b.z ) {
  21325. return b.z - a.z;
  21326. } else {
  21327. return a.id - b.id;
  21328. }
  21329. }
  21330. /**
  21331. * Returns `true` if the given transparent material requires a double pass.
  21332. *
  21333. * @private
  21334. * @function
  21335. * @param {Material} material - The transparent material.
  21336. * @return {boolean} Whether the given material requires a double pass or not.
  21337. */
  21338. function needsDoublePass( material ) {
  21339. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  21340. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  21341. }
  21342. /**
  21343. * When the renderer analyzes the scene at the beginning of a render call,
  21344. * it stores 3D object for further processing in render lists. Depending on the
  21345. * properties of a 3D objects (like their transformation or material state), the
  21346. * objects are maintained in ordered lists for the actual rendering.
  21347. *
  21348. * Render lists are unique per scene and camera combination.
  21349. *
  21350. * @private
  21351. * @augments Pipeline
  21352. */
  21353. class RenderList {
  21354. /**
  21355. * Constructs a render list.
  21356. *
  21357. * @param {Lighting} lighting - The lighting management component.
  21358. * @param {Scene} scene - The scene.
  21359. * @param {Camera} camera - The camera the scene is rendered with.
  21360. */
  21361. constructor( lighting, scene, camera ) {
  21362. /**
  21363. * 3D objects are transformed into render items and stored in this array.
  21364. *
  21365. * @type {Array<Object>}
  21366. */
  21367. this.renderItems = [];
  21368. /**
  21369. * The current render items index.
  21370. *
  21371. * @type {number}
  21372. * @default 0
  21373. */
  21374. this.renderItemsIndex = 0;
  21375. /**
  21376. * A list with opaque render items.
  21377. *
  21378. * @type {Array<Object>}
  21379. */
  21380. this.opaque = [];
  21381. /**
  21382. * A list with transparent render items which require
  21383. * double pass rendering (e.g. transmissive objects).
  21384. *
  21385. * @type {Array<Object>}
  21386. */
  21387. this.transparentDoublePass = [];
  21388. /**
  21389. * A list with transparent render items.
  21390. *
  21391. * @type {Array<Object>}
  21392. */
  21393. this.transparent = [];
  21394. /**
  21395. * A list with transparent render bundle data.
  21396. *
  21397. * @type {Array<Object>}
  21398. */
  21399. this.bundles = [];
  21400. /**
  21401. * The render list's lights node. This node is later
  21402. * relevant for the actual analytical light nodes which
  21403. * compute the scene's lighting in the shader.
  21404. *
  21405. * @type {LightsNode}
  21406. */
  21407. this.lightsNode = lighting.getNode( scene, camera );
  21408. /**
  21409. * The scene's lights stored in an array. This array
  21410. * is used to setup the lights node.
  21411. *
  21412. * @type {Array<Light>}
  21413. */
  21414. this.lightsArray = [];
  21415. /**
  21416. * The scene.
  21417. *
  21418. * @type {Scene}
  21419. */
  21420. this.scene = scene;
  21421. /**
  21422. * The camera the scene is rendered with.
  21423. *
  21424. * @type {Camera}
  21425. */
  21426. this.camera = camera;
  21427. /**
  21428. * How many objects perform occlusion query tests.
  21429. *
  21430. * @type {number}
  21431. * @default 0
  21432. */
  21433. this.occlusionQueryCount = 0;
  21434. }
  21435. /**
  21436. * This method is called right at the beginning of a render call
  21437. * before the scene is analyzed. It prepares the internal data
  21438. * structures for the upcoming render lists generation.
  21439. *
  21440. * @return {RenderList} A reference to this render list.
  21441. */
  21442. begin() {
  21443. this.renderItemsIndex = 0;
  21444. this.opaque.length = 0;
  21445. this.transparentDoublePass.length = 0;
  21446. this.transparent.length = 0;
  21447. this.bundles.length = 0;
  21448. this.lightsArray.length = 0;
  21449. this.occlusionQueryCount = 0;
  21450. return this;
  21451. }
  21452. /**
  21453. * Returns a render item for the giving render item state. The state is defined
  21454. * by a series of object-related parameters.
  21455. *
  21456. * The method avoids object creation by holding render items and reusing them in
  21457. * subsequent render calls (just with different property values).
  21458. *
  21459. * @param {Object3D} object - The 3D object.
  21460. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21461. * @param {Material} material - The 3D object's material.
  21462. * @param {number} groupOrder - The current group order.
  21463. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21464. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21465. * @param {ClippingContext} clippingContext - The current clipping context.
  21466. * @return {Object} The render item.
  21467. */
  21468. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21469. let renderItem = this.renderItems[ this.renderItemsIndex ];
  21470. if ( renderItem === undefined ) {
  21471. renderItem = {
  21472. id: object.id,
  21473. object: object,
  21474. geometry: geometry,
  21475. material: material,
  21476. groupOrder: groupOrder,
  21477. renderOrder: object.renderOrder,
  21478. z: z,
  21479. group: group,
  21480. clippingContext: clippingContext
  21481. };
  21482. this.renderItems[ this.renderItemsIndex ] = renderItem;
  21483. } else {
  21484. renderItem.id = object.id;
  21485. renderItem.object = object;
  21486. renderItem.geometry = geometry;
  21487. renderItem.material = material;
  21488. renderItem.groupOrder = groupOrder;
  21489. renderItem.renderOrder = object.renderOrder;
  21490. renderItem.z = z;
  21491. renderItem.group = group;
  21492. renderItem.clippingContext = clippingContext;
  21493. }
  21494. this.renderItemsIndex ++;
  21495. return renderItem;
  21496. }
  21497. /**
  21498. * Pushes the given object as a render item to the internal render lists.
  21499. * The selected lists depend on the object properties.
  21500. *
  21501. * @param {Object3D} object - The 3D object.
  21502. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21503. * @param {Material} material - The 3D object's material.
  21504. * @param {number} groupOrder - The current group order.
  21505. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21506. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21507. * @param {ClippingContext} clippingContext - The current clipping context.
  21508. */
  21509. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21510. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21511. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  21512. if ( material.transparent === true || material.transmission > 0 ) {
  21513. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  21514. this.transparent.push( renderItem );
  21515. } else {
  21516. this.opaque.push( renderItem );
  21517. }
  21518. }
  21519. /**
  21520. * Inserts the given object as a render item at the start of the internal render lists.
  21521. * The selected lists depend on the object properties.
  21522. *
  21523. * @param {Object3D} object - The 3D object.
  21524. * @param {BufferGeometry} geometry - The 3D object's geometry.
  21525. * @param {Material} material - The 3D object's material.
  21526. * @param {number} groupOrder - The current group order.
  21527. * @param {number} z - Th 3D object's depth value (z value in clip space).
  21528. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  21529. * @param {ClippingContext} clippingContext - The current clipping context.
  21530. */
  21531. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  21532. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  21533. if ( material.transparent === true || material.transmission > 0 ) {
  21534. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  21535. this.transparent.unshift( renderItem );
  21536. } else {
  21537. this.opaque.unshift( renderItem );
  21538. }
  21539. }
  21540. /**
  21541. * Pushes render bundle group data into the render list.
  21542. *
  21543. * @param {Object} group - Bundle group data.
  21544. */
  21545. pushBundle( group ) {
  21546. this.bundles.push( group );
  21547. }
  21548. /**
  21549. * Pushes a light into the render list.
  21550. *
  21551. * @param {Light} light - The light.
  21552. */
  21553. pushLight( light ) {
  21554. this.lightsArray.push( light );
  21555. }
  21556. /**
  21557. * Sorts the internal render lists.
  21558. *
  21559. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  21560. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  21561. */
  21562. sort( customOpaqueSort, customTransparentSort ) {
  21563. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  21564. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  21565. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  21566. }
  21567. /**
  21568. * This method performs finalizing tasks right after the render lists
  21569. * have been generated.
  21570. */
  21571. finish() {
  21572. // update lights
  21573. this.lightsNode.setLights( this.lightsArray );
  21574. // Clear references from inactive renderItems in the list
  21575. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  21576. const renderItem = this.renderItems[ i ];
  21577. if ( renderItem.id === null ) break;
  21578. renderItem.id = null;
  21579. renderItem.object = null;
  21580. renderItem.geometry = null;
  21581. renderItem.material = null;
  21582. renderItem.groupOrder = null;
  21583. renderItem.renderOrder = null;
  21584. renderItem.z = null;
  21585. renderItem.group = null;
  21586. renderItem.clippingContext = null;
  21587. }
  21588. }
  21589. }
  21590. const _chainKeys$4 = [];
  21591. /**
  21592. * This renderer module manages the render lists which are unique
  21593. * per scene and camera combination.
  21594. *
  21595. * @private
  21596. */
  21597. class RenderLists {
  21598. /**
  21599. * Constructs a render lists management component.
  21600. *
  21601. * @param {Lighting} lighting - The lighting management component.
  21602. */
  21603. constructor( lighting ) {
  21604. /**
  21605. * The lighting management component.
  21606. *
  21607. * @type {Lighting}
  21608. */
  21609. this.lighting = lighting;
  21610. /**
  21611. * The internal chain map which holds the render lists.
  21612. *
  21613. * @type {ChainMap}
  21614. */
  21615. this.lists = new ChainMap();
  21616. }
  21617. /**
  21618. * Returns a render list for the given scene and camera.
  21619. *
  21620. * @param {Scene} scene - The scene.
  21621. * @param {Camera} camera - The camera.
  21622. * @return {RenderList} The render list.
  21623. */
  21624. get( scene, camera ) {
  21625. const lists = this.lists;
  21626. _chainKeys$4[ 0 ] = scene;
  21627. _chainKeys$4[ 1 ] = camera;
  21628. let list = lists.get( _chainKeys$4 );
  21629. if ( list === undefined ) {
  21630. list = new RenderList( this.lighting, scene, camera );
  21631. lists.set( _chainKeys$4, list );
  21632. }
  21633. _chainKeys$4.length = 0;
  21634. return list;
  21635. }
  21636. /**
  21637. * Frees all internal resources.
  21638. */
  21639. dispose() {
  21640. this.lists = new ChainMap();
  21641. }
  21642. }
  21643. let _id$7 = 0;
  21644. /**
  21645. * Any render or compute command is executed in a specific context that defines
  21646. * the state of the renderer and its backend. Typical examples for such context
  21647. * data are the current clear values or data from the active framebuffer. This
  21648. * module is used to represent these contexts as objects.
  21649. *
  21650. * @private
  21651. */
  21652. class RenderContext {
  21653. /**
  21654. * Constructs a new render context.
  21655. */
  21656. constructor() {
  21657. /**
  21658. * The context's ID.
  21659. *
  21660. * @type {number}
  21661. */
  21662. this.id = _id$7 ++;
  21663. /**
  21664. * Whether the current active framebuffer has a color attachment.
  21665. *
  21666. * @type {boolean}
  21667. * @default true
  21668. */
  21669. this.color = true;
  21670. /**
  21671. * Whether the color attachment should be cleared or not.
  21672. *
  21673. * @type {boolean}
  21674. * @default true
  21675. */
  21676. this.clearColor = true;
  21677. /**
  21678. * The clear color value.
  21679. *
  21680. * @type {Object}
  21681. * @default true
  21682. */
  21683. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  21684. /**
  21685. * Whether the current active framebuffer has a depth attachment.
  21686. *
  21687. * @type {boolean}
  21688. * @default true
  21689. */
  21690. this.depth = true;
  21691. /**
  21692. * Whether the depth attachment should be cleared or not.
  21693. *
  21694. * @type {boolean}
  21695. * @default true
  21696. */
  21697. this.clearDepth = true;
  21698. /**
  21699. * The clear depth value.
  21700. *
  21701. * @type {number}
  21702. * @default 1
  21703. */
  21704. this.clearDepthValue = 1;
  21705. /**
  21706. * Whether the current active framebuffer has a stencil attachment.
  21707. *
  21708. * @type {boolean}
  21709. * @default false
  21710. */
  21711. this.stencil = false;
  21712. /**
  21713. * Whether the stencil attachment should be cleared or not.
  21714. *
  21715. * @type {boolean}
  21716. * @default true
  21717. */
  21718. this.clearStencil = true;
  21719. /**
  21720. * The clear stencil value.
  21721. *
  21722. * @type {number}
  21723. * @default 1
  21724. */
  21725. this.clearStencilValue = 1;
  21726. /**
  21727. * By default the viewport encloses the entire framebuffer If a smaller
  21728. * viewport is manually defined, this property is to `true` by the renderer.
  21729. *
  21730. * @type {boolean}
  21731. * @default false
  21732. */
  21733. this.viewport = false;
  21734. /**
  21735. * The viewport value. This value is in physical pixels meaning it incorporates
  21736. * the renderer's pixel ratio. The viewport property of render targets or
  21737. * the renderer is in logical pixels.
  21738. *
  21739. * @type {Vector4}
  21740. */
  21741. this.viewportValue = new Vector4();
  21742. /**
  21743. * When the scissor test is active and scissor rectangle smaller than the
  21744. * framebuffers dimensions, this property is to `true` by the renderer.
  21745. *
  21746. * @type {boolean}
  21747. * @default false
  21748. */
  21749. this.scissor = false;
  21750. /**
  21751. * The scissor rectangle.
  21752. *
  21753. * @type {Vector4}
  21754. */
  21755. this.scissorValue = new Vector4();
  21756. /**
  21757. * The active render target.
  21758. *
  21759. * @type {?RenderTarget}
  21760. * @default null
  21761. */
  21762. this.renderTarget = null;
  21763. /**
  21764. * The textures of the active render target.
  21765. * `null` when no render target is set.
  21766. *
  21767. * @type {?Array<Texture>}
  21768. * @default null
  21769. */
  21770. this.textures = null;
  21771. /**
  21772. * The depth texture of the active render target.
  21773. * `null` when no render target is set.
  21774. *
  21775. * @type {?DepthTexture}
  21776. * @default null
  21777. */
  21778. this.depthTexture = null;
  21779. /**
  21780. * The active cube face.
  21781. *
  21782. * @type {number}
  21783. * @default 0
  21784. */
  21785. this.activeCubeFace = 0;
  21786. /**
  21787. * The active mipmap level.
  21788. *
  21789. * @type {number}
  21790. * @default 0
  21791. */
  21792. this.activeMipmapLevel = 0;
  21793. /**
  21794. * The number of MSAA samples. This value is always `1` when
  21795. * MSAA isn't used.
  21796. *
  21797. * @type {number}
  21798. * @default 1
  21799. */
  21800. this.sampleCount = 1;
  21801. /**
  21802. * The active render target's width in physical pixels.
  21803. *
  21804. * @type {number}
  21805. * @default 0
  21806. */
  21807. this.width = 0;
  21808. /**
  21809. * The active render target's height in physical pixels.
  21810. *
  21811. * @type {number}
  21812. * @default 0
  21813. */
  21814. this.height = 0;
  21815. /**
  21816. * The occlusion query count.
  21817. *
  21818. * @type {number}
  21819. * @default 0
  21820. */
  21821. this.occlusionQueryCount = 0;
  21822. /**
  21823. * The current clipping context.
  21824. *
  21825. * @type {?ClippingContext}
  21826. * @default null
  21827. */
  21828. this.clippingContext = null;
  21829. /**
  21830. * This flag can be used for type testing.
  21831. *
  21832. * @type {boolean}
  21833. * @readonly
  21834. * @default true
  21835. */
  21836. this.isRenderContext = true;
  21837. }
  21838. /**
  21839. * Returns the cache key of this render context.
  21840. *
  21841. * @return {number} The cache key.
  21842. */
  21843. getCacheKey() {
  21844. return getCacheKey( this );
  21845. }
  21846. }
  21847. /**
  21848. * Computes a cache key for the given render context. This key
  21849. * should identify the render target state so it is possible to
  21850. * configure the correct attachments in the respective backend.
  21851. *
  21852. * @param {RenderContext} renderContext - The render context.
  21853. * @return {number} The cache key.
  21854. */
  21855. function getCacheKey( renderContext ) {
  21856. const { textures, activeCubeFace, activeMipmapLevel } = renderContext;
  21857. const values = [ activeCubeFace, activeMipmapLevel ];
  21858. for ( const texture of textures ) {
  21859. values.push( texture.id );
  21860. }
  21861. return hashArray( values );
  21862. }
  21863. const _chainKeys$3 = [];
  21864. const _defaultScene = /*@__PURE__*/ new Scene();
  21865. const _defaultCamera = /*@__PURE__*/ new Camera();
  21866. /**
  21867. * This module manages the render contexts of the renderer.
  21868. *
  21869. * @private
  21870. */
  21871. class RenderContexts {
  21872. /**
  21873. * Constructs a new render context management component.
  21874. */
  21875. constructor() {
  21876. /**
  21877. * A dictionary that manages render contexts in chain maps
  21878. * for each attachment state.
  21879. *
  21880. * @type {Object<string,ChainMap>}
  21881. */
  21882. this.chainMaps = {};
  21883. }
  21884. /**
  21885. * Returns a render context for the given scene, camera and render target.
  21886. *
  21887. * @param {Scene} scene - The scene.
  21888. * @param {Camera} camera - The camera that is used to render the scene.
  21889. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  21890. * @return {RenderContext} The render context.
  21891. */
  21892. get( scene, camera, renderTarget = null ) {
  21893. _chainKeys$3[ 0 ] = scene;
  21894. _chainKeys$3[ 1 ] = camera;
  21895. let attachmentState;
  21896. if ( renderTarget === null ) {
  21897. attachmentState = 'default';
  21898. } else {
  21899. const format = renderTarget.texture.format;
  21900. const count = renderTarget.textures.length;
  21901. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  21902. }
  21903. const chainMap = this._getChainMap( attachmentState );
  21904. let renderState = chainMap.get( _chainKeys$3 );
  21905. if ( renderState === undefined ) {
  21906. renderState = new RenderContext();
  21907. chainMap.set( _chainKeys$3, renderState );
  21908. }
  21909. _chainKeys$3.length = 0;
  21910. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  21911. return renderState;
  21912. }
  21913. /**
  21914. * Returns a render context intended for clear operations.
  21915. *
  21916. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  21917. * @return {RenderContext} The render context.
  21918. */
  21919. getForClear( renderTarget = null ) {
  21920. return this.get( _defaultScene, _defaultCamera, renderTarget );
  21921. }
  21922. /**
  21923. * Returns a chain map for the given attachment state.
  21924. *
  21925. * @private
  21926. * @param {string} attachmentState - The attachment state.
  21927. * @return {ChainMap} The chain map.
  21928. */
  21929. _getChainMap( attachmentState ) {
  21930. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  21931. }
  21932. /**
  21933. * Frees internal resources.
  21934. */
  21935. dispose() {
  21936. this.chainMaps = {};
  21937. }
  21938. }
  21939. const _size$3 = /*@__PURE__*/ new Vector3();
  21940. /**
  21941. * This module manages the textures of the renderer.
  21942. *
  21943. * @private
  21944. * @augments DataMap
  21945. */
  21946. class Textures extends DataMap {
  21947. /**
  21948. * Constructs a new texture management component.
  21949. *
  21950. * @param {Renderer} renderer - The renderer.
  21951. * @param {Backend} backend - The renderer's backend.
  21952. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21953. */
  21954. constructor( renderer, backend, info ) {
  21955. super();
  21956. /**
  21957. * The renderer.
  21958. *
  21959. * @type {Renderer}
  21960. */
  21961. this.renderer = renderer;
  21962. /**
  21963. * The backend.
  21964. *
  21965. * @type {Backend}
  21966. */
  21967. this.backend = backend;
  21968. /**
  21969. * Renderer component for managing metrics and monitoring data.
  21970. *
  21971. * @type {Info}
  21972. */
  21973. this.info = info;
  21974. }
  21975. /**
  21976. * Updates the given render target. Based on the given render target configuration,
  21977. * it updates the texture states representing the attachments of the framebuffer.
  21978. *
  21979. * @param {RenderTarget} renderTarget - The render target to update.
  21980. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  21981. */
  21982. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  21983. const renderTargetData = this.get( renderTarget );
  21984. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  21985. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  21986. const textures = renderTarget.textures;
  21987. const size = this.getSize( textures[ 0 ] );
  21988. const mipWidth = size.width >> activeMipmapLevel;
  21989. const mipHeight = size.height >> activeMipmapLevel;
  21990. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  21991. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  21992. let textureNeedsUpdate = false;
  21993. if ( depthTexture === undefined && useDepthTexture ) {
  21994. depthTexture = new DepthTexture();
  21995. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  21996. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  21997. depthTexture.image.width = mipWidth;
  21998. depthTexture.image.height = mipHeight;
  21999. depthTexture.image.depth = size.depth;
  22000. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  22001. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  22002. }
  22003. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  22004. textureNeedsUpdate = true;
  22005. if ( depthTexture ) {
  22006. depthTexture.needsUpdate = true;
  22007. depthTexture.image.width = mipWidth;
  22008. depthTexture.image.height = mipHeight;
  22009. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  22010. }
  22011. }
  22012. renderTargetData.width = size.width;
  22013. renderTargetData.height = size.height;
  22014. renderTargetData.textures = textures;
  22015. renderTargetData.depthTexture = depthTexture || null;
  22016. renderTargetData.depth = renderTarget.depthBuffer;
  22017. renderTargetData.stencil = renderTarget.stencilBuffer;
  22018. renderTargetData.renderTarget = renderTarget;
  22019. if ( renderTargetData.sampleCount !== sampleCount ) {
  22020. textureNeedsUpdate = true;
  22021. if ( depthTexture ) {
  22022. depthTexture.needsUpdate = true;
  22023. }
  22024. renderTargetData.sampleCount = sampleCount;
  22025. }
  22026. //
  22027. const options = { sampleCount };
  22028. // XR render targets require no texture updates
  22029. if ( renderTarget.isXRRenderTarget !== true ) {
  22030. for ( let i = 0; i < textures.length; i ++ ) {
  22031. const texture = textures[ i ];
  22032. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  22033. this.updateTexture( texture, options );
  22034. }
  22035. if ( depthTexture ) {
  22036. this.updateTexture( depthTexture, options );
  22037. }
  22038. }
  22039. // dispose handler
  22040. if ( renderTargetData.initialized !== true ) {
  22041. renderTargetData.initialized = true;
  22042. // dispose
  22043. const onDispose = () => {
  22044. renderTarget.removeEventListener( 'dispose', onDispose );
  22045. for ( let i = 0; i < textures.length; i ++ ) {
  22046. this._destroyTexture( textures[ i ] );
  22047. }
  22048. if ( depthTexture ) {
  22049. this._destroyTexture( depthTexture );
  22050. }
  22051. this.delete( renderTarget );
  22052. this.backend.delete( renderTarget );
  22053. };
  22054. renderTarget.addEventListener( 'dispose', onDispose );
  22055. }
  22056. }
  22057. /**
  22058. * Updates the given texture. Depending on the texture state, this method
  22059. * triggers the upload of texture data to the GPU memory. If the texture data are
  22060. * not yet ready for the upload, it uses default texture data for as a placeholder.
  22061. *
  22062. * @param {Texture} texture - The texture to update.
  22063. * @param {Object} [options={}] - The options.
  22064. */
  22065. updateTexture( texture, options = {} ) {
  22066. const textureData = this.get( texture );
  22067. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  22068. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  22069. const backend = this.backend;
  22070. if ( isRenderTarget && textureData.initialized === true ) {
  22071. // it's an update
  22072. backend.destroySampler( texture );
  22073. backend.destroyTexture( texture );
  22074. }
  22075. //
  22076. if ( texture.isFramebufferTexture ) {
  22077. const renderTarget = this.renderer.getRenderTarget();
  22078. if ( renderTarget ) {
  22079. texture.type = renderTarget.texture.type;
  22080. } else {
  22081. texture.type = UnsignedByteType;
  22082. }
  22083. }
  22084. //
  22085. const { width, height, depth } = this.getSize( texture );
  22086. options.width = width;
  22087. options.height = height;
  22088. options.depth = depth;
  22089. options.needsMipmaps = this.needsMipmaps( texture );
  22090. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  22091. // TODO: Uniformly handle mipmap definitions
  22092. // Normal textures and compressed cube textures define base level + mips with their mipmap array
  22093. // Uncompressed cube textures use their mipmap array only for mips (no base level)
  22094. if ( texture.isCubeTexture && texture.mipmaps.length > 0 ) options.levels ++;
  22095. //
  22096. if ( isRenderTarget || texture.isStorageTexture === true || texture.isExternalTexture === true ) {
  22097. backend.createSampler( texture );
  22098. backend.createTexture( texture, options );
  22099. textureData.generation = texture.version;
  22100. } else {
  22101. const needsCreate = textureData.initialized !== true;
  22102. if ( needsCreate ) backend.createSampler( texture );
  22103. if ( texture.version > 0 ) {
  22104. const image = texture.image;
  22105. if ( image === undefined ) {
  22106. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  22107. } else if ( image.complete === false ) {
  22108. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  22109. } else {
  22110. if ( texture.images ) {
  22111. const images = [];
  22112. for ( const image of texture.images ) {
  22113. images.push( image );
  22114. }
  22115. options.images = images;
  22116. } else {
  22117. options.image = image;
  22118. }
  22119. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  22120. backend.createTexture( texture, options );
  22121. textureData.isDefaultTexture = false;
  22122. textureData.generation = texture.version;
  22123. }
  22124. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  22125. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  22126. if ( texture.onUpdate ) texture.onUpdate( texture );
  22127. }
  22128. } else {
  22129. // async update
  22130. backend.createDefaultTexture( texture );
  22131. textureData.isDefaultTexture = true;
  22132. textureData.generation = texture.version;
  22133. }
  22134. }
  22135. // dispose handler
  22136. if ( textureData.initialized !== true ) {
  22137. textureData.initialized = true;
  22138. textureData.generation = texture.version;
  22139. //
  22140. this.info.memory.textures ++;
  22141. //
  22142. if ( texture.isVideoTexture && ColorManagement.getTransfer( texture.colorSpace ) !== SRGBTransfer ) {
  22143. console.warn( 'WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace.' );
  22144. }
  22145. // dispose
  22146. const onDispose = () => {
  22147. texture.removeEventListener( 'dispose', onDispose );
  22148. this._destroyTexture( texture );
  22149. };
  22150. texture.addEventListener( 'dispose', onDispose );
  22151. }
  22152. //
  22153. textureData.version = texture.version;
  22154. }
  22155. /**
  22156. * Computes the size of the given texture and writes the result
  22157. * into the target vector. This vector is also returned by the
  22158. * method.
  22159. *
  22160. * If no texture data are available for the compute yet, the method
  22161. * returns default size values.
  22162. *
  22163. * @param {Texture} texture - The texture to compute the size for.
  22164. * @param {Vector3} target - The target vector.
  22165. * @return {Vector3} The target vector.
  22166. */
  22167. getSize( texture, target = _size$3 ) {
  22168. let image = texture.images ? texture.images[ 0 ] : texture.image;
  22169. if ( image ) {
  22170. if ( image.image !== undefined ) image = image.image;
  22171. if ( ( typeof HTMLVideoElement !== 'undefined' ) && ( image instanceof HTMLVideoElement ) ) {
  22172. target.width = image.videoWidth || 1;
  22173. target.height = image.videoHeight || 1;
  22174. target.depth = 1;
  22175. } else if ( image instanceof VideoFrame ) {
  22176. target.width = image.displayWidth || 1;
  22177. target.height = image.displayHeight || 1;
  22178. target.depth = 1;
  22179. } else {
  22180. target.width = image.width || 1;
  22181. target.height = image.height || 1;
  22182. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  22183. }
  22184. } else {
  22185. target.width = target.height = target.depth = 1;
  22186. }
  22187. return target;
  22188. }
  22189. /**
  22190. * Computes the number of mipmap levels for the given texture.
  22191. *
  22192. * @param {Texture} texture - The texture.
  22193. * @param {number} width - The texture's width.
  22194. * @param {number} height - The texture's height.
  22195. * @return {number} The number of mipmap levels.
  22196. */
  22197. getMipLevels( texture, width, height ) {
  22198. let mipLevelCount;
  22199. if ( texture.mipmaps.length > 0 ) {
  22200. mipLevelCount = texture.mipmaps.length;
  22201. } else {
  22202. if ( texture.isCompressedTexture === true ) {
  22203. // it is not possible to compute mipmaps for compressed textures. So
  22204. // when no mipmaps are defined in "texture.mipmaps", force a texture
  22205. // level of 1
  22206. mipLevelCount = 1;
  22207. } else {
  22208. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  22209. }
  22210. }
  22211. return mipLevelCount;
  22212. }
  22213. /**
  22214. * Returns `true` if the given texture makes use of mipmapping.
  22215. *
  22216. * @param {Texture} texture - The texture.
  22217. * @return {boolean} Whether mipmaps are required or not.
  22218. */
  22219. needsMipmaps( texture ) {
  22220. return texture.generateMipmaps === true || texture.mipmaps.length > 0;
  22221. }
  22222. /**
  22223. * Frees internal resource when the given texture isn't
  22224. * required anymore.
  22225. *
  22226. * @param {Texture} texture - The texture to destroy.
  22227. */
  22228. _destroyTexture( texture ) {
  22229. if ( this.has( texture ) === true ) {
  22230. this.backend.destroySampler( texture );
  22231. this.backend.destroyTexture( texture );
  22232. this.delete( texture );
  22233. this.info.memory.textures --;
  22234. }
  22235. }
  22236. }
  22237. /**
  22238. * A four-component version of {@link Color} which is internally
  22239. * used by the renderer to represents clear color with alpha as
  22240. * one object.
  22241. *
  22242. * @private
  22243. * @augments Color
  22244. */
  22245. class Color4 extends Color {
  22246. /**
  22247. * Constructs a new four-component color.
  22248. * You can also pass a single THREE.Color, hex or
  22249. * string argument to this constructor.
  22250. *
  22251. * @param {number|string} [r=1] - The red value.
  22252. * @param {number} [g=1] - The green value.
  22253. * @param {number} [b=1] - The blue value.
  22254. * @param {number} [a=1] - The alpha value.
  22255. */
  22256. constructor( r, g, b, a = 1 ) {
  22257. super( r, g, b );
  22258. this.a = a;
  22259. }
  22260. /**
  22261. * Overwrites the default to honor alpha.
  22262. * You can also pass a single THREE.Color, hex or
  22263. * string argument to this method.
  22264. *
  22265. * @param {number|string|Color} r - The red value.
  22266. * @param {number} [g] - The green value.
  22267. * @param {number} [b] - The blue value.
  22268. * @param {number} [a=1] - The alpha value.
  22269. * @return {Color4} A reference to this object.
  22270. */
  22271. set( r, g, b, a = 1 ) {
  22272. this.a = a;
  22273. return super.set( r, g, b );
  22274. }
  22275. /**
  22276. * Overwrites the default to honor alpha.
  22277. *
  22278. * @param {Color4} color - The color to copy.
  22279. * @return {Color4} A reference to this object.
  22280. */
  22281. copy( color ) {
  22282. if ( color.a !== undefined ) this.a = color.a;
  22283. return super.copy( color );
  22284. }
  22285. /**
  22286. * Overwrites the default to honor alpha.
  22287. *
  22288. * @return {Color4} The cloned color.
  22289. */
  22290. clone() {
  22291. return new this.constructor( this.r, this.g, this.b, this.a );
  22292. }
  22293. }
  22294. /**
  22295. * Special version of {@link PropertyNode} which is used for parameters.
  22296. *
  22297. * @augments PropertyNode
  22298. */
  22299. class ParameterNode extends PropertyNode {
  22300. static get type() {
  22301. return 'ParameterNode';
  22302. }
  22303. /**
  22304. * Constructs a new parameter node.
  22305. *
  22306. * @param {string} nodeType - The type of the node.
  22307. * @param {?string} [name=null] - The name of the parameter in the shader.
  22308. */
  22309. constructor( nodeType, name = null ) {
  22310. super( nodeType, name );
  22311. /**
  22312. * This flag can be used for type testing.
  22313. *
  22314. * @type {boolean}
  22315. * @readonly
  22316. * @default true
  22317. */
  22318. this.isParameterNode = true;
  22319. }
  22320. getHash() {
  22321. return this.uuid;
  22322. }
  22323. generate() {
  22324. return this.name;
  22325. }
  22326. }
  22327. /**
  22328. * TSL function for creating a parameter node.
  22329. *
  22330. * @tsl
  22331. * @function
  22332. * @param {string} type - The type of the node.
  22333. * @param {?string} name - The name of the parameter in the shader.
  22334. * @returns {ParameterNode}
  22335. */
  22336. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  22337. /**
  22338. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  22339. * They are usually needed in cases like `If`, `Else`.
  22340. *
  22341. * @augments Node
  22342. */
  22343. class StackNode extends Node {
  22344. static get type() {
  22345. return 'StackNode';
  22346. }
  22347. /**
  22348. * Constructs a new stack node.
  22349. *
  22350. * @param {?StackNode} [parent=null] - The parent stack node.
  22351. */
  22352. constructor( parent = null ) {
  22353. super();
  22354. /**
  22355. * List of nodes.
  22356. *
  22357. * @type {Array<Node>}
  22358. */
  22359. this.nodes = [];
  22360. /**
  22361. * The output node.
  22362. *
  22363. * @type {?Node}
  22364. * @default null
  22365. */
  22366. this.outputNode = null;
  22367. /**
  22368. * The parent stack node.
  22369. *
  22370. * @type {?StackNode}
  22371. * @default null
  22372. */
  22373. this.parent = parent;
  22374. /**
  22375. * The current conditional node.
  22376. *
  22377. * @private
  22378. * @type {ConditionalNode}
  22379. * @default null
  22380. */
  22381. this._currentCond = null;
  22382. /**
  22383. * The expression node. Only
  22384. * relevant for Switch/Case.
  22385. *
  22386. * @private
  22387. * @type {Node}
  22388. * @default null
  22389. */
  22390. this._expressionNode = null;
  22391. /**
  22392. * This flag can be used for type testing.
  22393. *
  22394. * @type {boolean}
  22395. * @readonly
  22396. * @default true
  22397. */
  22398. this.isStackNode = true;
  22399. }
  22400. getNodeType( builder ) {
  22401. return this.hasOutput ? this.outputNode.getNodeType( builder ) : 'void';
  22402. }
  22403. getMemberType( builder, name ) {
  22404. return this.hasOutput ? this.outputNode.getMemberType( builder, name ) : 'void';
  22405. }
  22406. /**
  22407. * Adds a node to this stack.
  22408. *
  22409. * @param {Node} node - The node to add.
  22410. * @return {StackNode} A reference to this stack node.
  22411. */
  22412. add( node ) {
  22413. if ( node.isNode !== true ) {
  22414. console.error( 'THREE.TSL: Invalid node added to stack.' );
  22415. return this;
  22416. }
  22417. this.nodes.push( node );
  22418. return this;
  22419. }
  22420. /**
  22421. * Represent an `if` statement in TSL.
  22422. *
  22423. * @param {Node} boolNode - Represents the condition.
  22424. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22425. * @return {StackNode} A reference to this stack node.
  22426. */
  22427. If( boolNode, method ) {
  22428. const methodNode = new ShaderNode( method );
  22429. this._currentCond = select( boolNode, methodNode );
  22430. return this.add( this._currentCond );
  22431. }
  22432. /**
  22433. * Represent an `elseif` statement in TSL.
  22434. *
  22435. * @param {Node} boolNode - Represents the condition.
  22436. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22437. * @return {StackNode} A reference to this stack node.
  22438. */
  22439. ElseIf( boolNode, method ) {
  22440. const methodNode = new ShaderNode( method );
  22441. const ifNode = select( boolNode, methodNode );
  22442. this._currentCond.elseNode = ifNode;
  22443. this._currentCond = ifNode;
  22444. return this;
  22445. }
  22446. /**
  22447. * Represent an `else` statement in TSL.
  22448. *
  22449. * @param {Function} method - TSL code which is executed in the `else` case.
  22450. * @return {StackNode} A reference to this stack node.
  22451. */
  22452. Else( method ) {
  22453. this._currentCond.elseNode = new ShaderNode( method );
  22454. return this;
  22455. }
  22456. /**
  22457. * Represents a `switch` statement in TSL.
  22458. *
  22459. * @param {any} expression - Represents the expression.
  22460. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  22461. * @return {StackNode} A reference to this stack node.
  22462. */
  22463. Switch( expression ) {
  22464. this._expressionNode = nodeObject( expression );
  22465. return this;
  22466. }
  22467. /**
  22468. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  22469. * The last parameter must be the callback method that should be executed in the `true` case.
  22470. *
  22471. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  22472. * @return {StackNode} A reference to this stack node.
  22473. */
  22474. Case( ...params ) {
  22475. const caseNodes = [];
  22476. // extract case nodes from the parameter list
  22477. if ( params.length >= 2 ) {
  22478. for ( let i = 0; i < params.length - 1; i ++ ) {
  22479. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  22480. }
  22481. } else {
  22482. console.error( 'THREE.TSL: Invalid parameter length. Case() requires at least two parameters.' );
  22483. }
  22484. // extract method
  22485. const method = params[ params.length - 1 ];
  22486. const methodNode = new ShaderNode( method );
  22487. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  22488. let caseNode = caseNodes[ 0 ];
  22489. for ( let i = 1; i < caseNodes.length; i ++ ) {
  22490. caseNode = caseNode.or( caseNodes[ i ] );
  22491. }
  22492. // build condition
  22493. const condNode = select( caseNode, methodNode );
  22494. if ( this._currentCond === null ) {
  22495. this._currentCond = condNode;
  22496. return this.add( this._currentCond );
  22497. } else {
  22498. this._currentCond.elseNode = condNode;
  22499. this._currentCond = condNode;
  22500. return this;
  22501. }
  22502. }
  22503. /**
  22504. * Represents the default code block of a Switch/Case statement.
  22505. *
  22506. * @param {Function} method - TSL code which is executed in the `else` case.
  22507. * @return {StackNode} A reference to this stack node.
  22508. */
  22509. Default( method ) {
  22510. this.Else( method );
  22511. return this;
  22512. }
  22513. setup( builder ) {
  22514. const nodeProperties = builder.getNodeProperties( this );
  22515. let index = 0;
  22516. for ( const childNode of this.getChildren() ) {
  22517. if ( childNode.isVarNode && childNode.intent === true ) {
  22518. const properties = builder.getNodeProperties( childNode );
  22519. if ( properties.assign !== true ) {
  22520. continue;
  22521. }
  22522. }
  22523. nodeProperties[ 'node' + index ++ ] = childNode;
  22524. }
  22525. // return a outputNode if exists or null
  22526. return nodeProperties.outputNode || null;
  22527. }
  22528. get hasOutput() {
  22529. return this.outputNode && this.outputNode.isNode;
  22530. }
  22531. build( builder, ...params ) {
  22532. const previousBuildStack = builder.currentStack;
  22533. const previousStack = getCurrentStack();
  22534. setCurrentStack( this );
  22535. builder.currentStack = this;
  22536. const buildStage = builder.buildStage;
  22537. for ( const node of this.nodes ) {
  22538. if ( node.isVarNode && node.intent === true ) {
  22539. const properties = builder.getNodeProperties( node );
  22540. if ( properties.assign !== true ) {
  22541. continue;
  22542. }
  22543. }
  22544. if ( buildStage === 'setup' ) {
  22545. node.build( builder );
  22546. } else if ( buildStage === 'analyze' ) {
  22547. node.build( builder, this );
  22548. } else if ( buildStage === 'generate' ) {
  22549. const stages = builder.getDataFromNode( node, 'any' ).stages;
  22550. const parents = stages && stages[ builder.shaderStage ];
  22551. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  22552. continue; // skip var nodes that are only used in .toVarying()
  22553. }
  22554. node.build( builder, 'void' );
  22555. }
  22556. }
  22557. //
  22558. let result;
  22559. if ( this.hasOutput ) {
  22560. result = this.outputNode.build( builder, ...params );
  22561. } else {
  22562. result = super.build( builder, ...params );
  22563. }
  22564. setCurrentStack( previousStack );
  22565. builder.currentStack = previousBuildStack;
  22566. return result;
  22567. }
  22568. }
  22569. /**
  22570. * TSL function for creating a stack node.
  22571. *
  22572. * @tsl
  22573. * @function
  22574. * @param {?StackNode} [parent=null] - The parent stack node.
  22575. * @returns {StackNode}
  22576. */
  22577. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  22578. /**
  22579. * Generates a layout for struct members.
  22580. * This function takes an object representing struct members and returns an array of member layouts.
  22581. * Each member layout includes the member's name, type, and whether it is atomic.
  22582. *
  22583. * @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.
  22584. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  22585. */
  22586. function getMembersLayout( members ) {
  22587. return Object.entries( members ).map( ( [ name, value ] ) => {
  22588. if ( typeof value === 'string' ) {
  22589. return { name, type: value, atomic: false };
  22590. }
  22591. return { name, type: value.type, atomic: value.atomic || false };
  22592. } );
  22593. }
  22594. /**
  22595. * Represents a struct type node in the node-based system.
  22596. * This class is used to define and manage the layout and types of struct members.
  22597. * It extends the base Node class and provides methods to get the length of the struct,
  22598. * retrieve member types, and generate the struct type for a builder.
  22599. *
  22600. * @augments Node
  22601. */
  22602. class StructTypeNode extends Node {
  22603. static get type() {
  22604. return 'StructTypeNode';
  22605. }
  22606. /**
  22607. * Creates an instance of StructTypeNode.
  22608. *
  22609. * @param {Object} membersLayout - The layout of the members for the struct.
  22610. * @param {?string} [name=null] - The optional name of the struct.
  22611. */
  22612. constructor( membersLayout, name = null ) {
  22613. super( 'struct' );
  22614. /**
  22615. * The layout of the members for the struct
  22616. *
  22617. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  22618. */
  22619. this.membersLayout = getMembersLayout( membersLayout );
  22620. /**
  22621. * The name of the struct.
  22622. *
  22623. * @type {?string}
  22624. * @default null
  22625. */
  22626. this.name = name;
  22627. /**
  22628. * This flag can be used for type testing.
  22629. *
  22630. * @type {boolean}
  22631. * @readonly
  22632. * @default true
  22633. */
  22634. this.isStructLayoutNode = true;
  22635. }
  22636. /**
  22637. * Returns the length of the struct.
  22638. * The length is calculated by summing the lengths of the struct's members.
  22639. *
  22640. * @returns {number} The length of the struct.
  22641. */
  22642. getLength() {
  22643. const GPU_CHUNK_BYTES = 8;
  22644. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  22645. let offset = 0; // global buffer offset in bytes
  22646. for ( const member of this.membersLayout ) {
  22647. const type = member.type;
  22648. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  22649. const boundary = getByteBoundaryFromType( type );
  22650. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  22651. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  22652. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  22653. offset += chunkPadding;
  22654. // Check for chunk overflow
  22655. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  22656. // Add padding to the end of the chunk
  22657. offset += ( GPU_CHUNK_BYTES - chunkStart );
  22658. }
  22659. offset += itemSize;
  22660. }
  22661. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  22662. }
  22663. getMemberType( builder, name ) {
  22664. const member = this.membersLayout.find( m => m.name === name );
  22665. return member ? member.type : 'void';
  22666. }
  22667. getNodeType( builder ) {
  22668. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  22669. return structType.name;
  22670. }
  22671. setup( builder ) {
  22672. builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  22673. builder.addInclude( this );
  22674. }
  22675. generate( builder ) {
  22676. return this.getNodeType( builder );
  22677. }
  22678. }
  22679. /**
  22680. * StructNode allows to create custom structures with multiple members.
  22681. * This can also be used to define structures in attribute and uniform data.
  22682. *
  22683. * ```js
  22684. * // Define a custom struct
  22685. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  22686. *
  22687. * // Create a new instance of the struct
  22688. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  22689. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  22690. *
  22691. * // Access the struct members
  22692. * const min = bb.get( 'min' );
  22693. *
  22694. * // Assign a new value to a member
  22695. * min.assign( vec3() );
  22696. * ```
  22697. * @augments Node
  22698. */
  22699. class StructNode extends Node {
  22700. static get type() {
  22701. return 'StructNode';
  22702. }
  22703. constructor( structTypeNode, values ) {
  22704. super( 'vec3' );
  22705. this.structTypeNode = structTypeNode;
  22706. this.values = values;
  22707. this.isStructNode = true;
  22708. }
  22709. getNodeType( builder ) {
  22710. return this.structTypeNode.getNodeType( builder );
  22711. }
  22712. getMemberType( builder, name ) {
  22713. return this.structTypeNode.getMemberType( builder, name );
  22714. }
  22715. generate( builder ) {
  22716. const nodeVar = builder.getVarFromNode( this );
  22717. const structType = nodeVar.type;
  22718. const propertyName = builder.getPropertyName( nodeVar );
  22719. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structTypeNode.membersLayout, this.values ) }`, this );
  22720. return nodeVar.name;
  22721. }
  22722. }
  22723. /**
  22724. * TSL function for creating a struct node.
  22725. *
  22726. * @tsl
  22727. * @function
  22728. * @param {Object} membersLayout - The layout of the struct members.
  22729. * @param {?string} [name=null] - The name of the struct.
  22730. * @returns {Function} The struct function.
  22731. */
  22732. const struct = ( membersLayout, name = null ) => {
  22733. const structLayout = new StructTypeNode( membersLayout, name );
  22734. const struct = ( ...params ) => {
  22735. let values = null;
  22736. if ( params.length > 0 ) {
  22737. if ( params[ 0 ].isNode ) {
  22738. values = {};
  22739. const names = Object.keys( membersLayout );
  22740. for ( let i = 0; i < params.length; i ++ ) {
  22741. values[ names[ i ] ] = params[ i ];
  22742. }
  22743. } else {
  22744. values = params[ 0 ];
  22745. }
  22746. }
  22747. return nodeObject( new StructNode( structLayout, values ) );
  22748. };
  22749. struct.layout = structLayout;
  22750. struct.isStruct = true;
  22751. return struct;
  22752. };
  22753. /**
  22754. * This node can be used to define multiple outputs in a shader programs.
  22755. *
  22756. * @augments Node
  22757. */
  22758. class OutputStructNode extends Node {
  22759. static get type() {
  22760. return 'OutputStructNode';
  22761. }
  22762. /**
  22763. * Constructs a new output struct node. The constructor can be invoked with an
  22764. * arbitrary number of nodes representing the members.
  22765. *
  22766. * @param {...Node} members - A parameter list of nodes.
  22767. */
  22768. constructor( ...members ) {
  22769. super();
  22770. /**
  22771. * An array of nodes which defines the output.
  22772. *
  22773. * @type {Array<Node>}
  22774. */
  22775. this.members = members;
  22776. /**
  22777. * This flag can be used for type testing.
  22778. *
  22779. * @type {boolean}
  22780. * @readonly
  22781. * @default true
  22782. */
  22783. this.isOutputStructNode = true;
  22784. }
  22785. getNodeType( builder ) {
  22786. const properties = builder.getNodeProperties( this );
  22787. if ( properties.membersLayout === undefined ) {
  22788. const members = this.members;
  22789. const membersLayout = [];
  22790. for ( let i = 0; i < members.length; i ++ ) {
  22791. const name = 'm' + i;
  22792. const type = members[ i ].getNodeType( builder );
  22793. membersLayout.push( { name, type, index: i } );
  22794. }
  22795. properties.membersLayout = membersLayout;
  22796. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  22797. }
  22798. return properties.structType.name;
  22799. }
  22800. generate( builder ) {
  22801. const propertyName = builder.getOutputStructName();
  22802. const members = this.members;
  22803. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  22804. for ( let i = 0; i < members.length; i ++ ) {
  22805. const snippet = members[ i ].build( builder );
  22806. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  22807. }
  22808. return propertyName;
  22809. }
  22810. }
  22811. /**
  22812. * TSL function for creating an output struct node.
  22813. *
  22814. * @tsl
  22815. * @function
  22816. * @param {...Node} members - A parameter list of nodes.
  22817. * @returns {OutputStructNode}
  22818. */
  22819. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  22820. /**
  22821. * Returns the MRT texture index for the given name.
  22822. *
  22823. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  22824. * @param {string} name - The name of the MRT texture which index is requested.
  22825. * @return {number} The texture index.
  22826. */
  22827. function getTextureIndex( textures, name ) {
  22828. for ( let i = 0; i < textures.length; i ++ ) {
  22829. if ( textures[ i ].name === name ) {
  22830. return i;
  22831. }
  22832. }
  22833. return -1;
  22834. }
  22835. /**
  22836. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  22837. * post-processing is shown below:
  22838. * ```js
  22839. * const mrtNode = mrt( {
  22840. * output: output,
  22841. * normal: normalView
  22842. * } ) );
  22843. * ```
  22844. * The MRT output is defined as a dictionary.
  22845. *
  22846. * @augments OutputStructNode
  22847. */
  22848. class MRTNode extends OutputStructNode {
  22849. static get type() {
  22850. return 'MRTNode';
  22851. }
  22852. /**
  22853. * Constructs a new output struct node.
  22854. *
  22855. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  22856. */
  22857. constructor( outputNodes ) {
  22858. super();
  22859. /**
  22860. * A dictionary representing the MRT outputs. The key
  22861. * is the name of the output, the value the node which produces
  22862. * the output result.
  22863. *
  22864. * @type {Object<string, Node>}
  22865. */
  22866. this.outputNodes = outputNodes;
  22867. /**
  22868. * This flag can be used for type testing.
  22869. *
  22870. * @type {boolean}
  22871. * @readonly
  22872. * @default true
  22873. */
  22874. this.isMRTNode = true;
  22875. }
  22876. /**
  22877. * Returns `true` if the MRT node has an output with the given name.
  22878. *
  22879. * @param {string} name - The name of the output.
  22880. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  22881. */
  22882. has( name ) {
  22883. return this.outputNodes[ name ] !== undefined;
  22884. }
  22885. /**
  22886. * Returns the output node for the given name.
  22887. *
  22888. * @param {string} name - The name of the output.
  22889. * @return {Node} The output node.
  22890. */
  22891. get( name ) {
  22892. return this.outputNodes[ name ];
  22893. }
  22894. /**
  22895. * Merges the outputs of the given MRT node with the outputs of this node.
  22896. *
  22897. * @param {MRTNode} mrtNode - The MRT to merge.
  22898. * @return {MRTNode} A new MRT node with merged outputs..
  22899. */
  22900. merge( mrtNode ) {
  22901. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  22902. return mrt( outputs );
  22903. }
  22904. setup( builder ) {
  22905. const outputNodes = this.outputNodes;
  22906. const mrt = builder.renderer.getRenderTarget();
  22907. const members = [];
  22908. const textures = mrt.textures;
  22909. for ( const name in outputNodes ) {
  22910. const index = getTextureIndex( textures, name );
  22911. members[ index ] = vec4( outputNodes[ name ] );
  22912. }
  22913. this.members = members;
  22914. return super.setup( builder );
  22915. }
  22916. }
  22917. /**
  22918. * TSL function for creating a MRT node.
  22919. *
  22920. * @tsl
  22921. * @function
  22922. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  22923. * @returns {MRTNode}
  22924. */
  22925. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  22926. /**
  22927. * This node represents an operation that reinterprets the bit representation of a value
  22928. * in one type as a value in another type.
  22929. *
  22930. * @augments TempNode
  22931. */
  22932. class BitcastNode extends TempNode {
  22933. static get type() {
  22934. return 'BitcastNode';
  22935. }
  22936. /**
  22937. * Constructs a new bitcast node.
  22938. *
  22939. * @param {Node} valueNode - The value to convert.
  22940. * @param {string} conversionType - The type to convert to.
  22941. * @param {?string} [inputType = null] - The expected input data type of the bitcast operation.
  22942. */
  22943. constructor( valueNode, conversionType, inputType = null ) {
  22944. super();
  22945. /**
  22946. * The data to bitcast to a new type.
  22947. *
  22948. * @type {Node}
  22949. */
  22950. this.valueNode = valueNode;
  22951. /**
  22952. * The type the value will be converted to.
  22953. *
  22954. * @type {string}
  22955. */
  22956. this.conversionType = conversionType;
  22957. /**
  22958. * The expected input data type of the bitcast operation.
  22959. *
  22960. *
  22961. * @type {string}
  22962. * @default null
  22963. */
  22964. this.inputType = inputType;
  22965. /**
  22966. * This flag can be used for type testing.
  22967. *
  22968. * @type {boolean}
  22969. * @readonly
  22970. * @default true
  22971. */
  22972. this.isBitcastNode = true;
  22973. }
  22974. getNodeType( builder ) {
  22975. // GLSL aliasing
  22976. if ( this.inputType !== null ) {
  22977. const valueType = this.valueNode.getNodeType( builder );
  22978. const valueLength = builder.getTypeLength( valueType );
  22979. return builder.getTypeFromLength( valueLength, this.conversionType );
  22980. }
  22981. return this.conversionType;
  22982. }
  22983. generate( builder ) {
  22984. const type = this.getNodeType( builder );
  22985. let inputType = '';
  22986. if ( this.inputType !== null ) {
  22987. const valueType = this.valueNode.getNodeType( builder );
  22988. const valueTypeLength = builder.getTypeLength( valueType );
  22989. inputType = valueTypeLength === 1 ? this.inputType : builder.changeComponentType( valueType, this.inputType );
  22990. } else {
  22991. inputType = this.valueNode.getNodeType( builder );
  22992. }
  22993. return `${ builder.getBitcastMethod( type, inputType ) }( ${ this.valueNode.build( builder, inputType ) } )`;
  22994. }
  22995. }
  22996. /**
  22997. * Reinterpret the bit representation of a value in one type as a value in another type.
  22998. *
  22999. * @tsl
  23000. * @function
  23001. * @param {Node | number} x - The parameter.
  23002. * @param {string} y - The new type.
  23003. * @returns {Node}
  23004. */
  23005. const bitcast = /*@__PURE__*/ nodeProxyIntent( BitcastNode ).setParameterLength( 2 );
  23006. /**
  23007. * Bitcasts a float or a vector of floats to a corresponding integer type with the same element size.
  23008. *
  23009. * @tsl
  23010. * @function
  23011. * @param {Node<float>} value - The float or vector of floats to bitcast.
  23012. * @returns {BitcastNode}
  23013. */
  23014. const floatBitsToInt = ( value ) => new BitcastNode( value, 'int', 'float' );
  23015. /**
  23016. * Bitcasts a float or a vector of floats to a corresponding unsigned integer type with the same element size.
  23017. *
  23018. * @tsl
  23019. * @function
  23020. * @param {Node<float>} value - The float or vector of floats to bitcast.
  23021. * @returns {BitcastNode}
  23022. */
  23023. const floatBitsToUint = ( value ) => new BitcastNode( value, 'uint', 'float' );
  23024. /**
  23025. * Bitcasts an integer or a vector of integers to a corresponding float type with the same element size.
  23026. *
  23027. * @tsl
  23028. * @function
  23029. * @param {Node<int>} value - The integer or vector of integers to bitcast.
  23030. * @returns {BitcastNode}
  23031. */
  23032. const intBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'int' );
  23033. /**
  23034. * Bitcast an unsigned integer or a vector of unsigned integers to a corresponding float type with the same element size.
  23035. *
  23036. * @tsl
  23037. * @function
  23038. * @param {Node<uint>} value - The unsigned integer or vector of unsigned integers to bitcast.
  23039. * @returns {BitcastNode}
  23040. */
  23041. const uintBitsToFloat = ( value ) => new BitcastNode( value, 'float', 'uint' );
  23042. /**
  23043. * Generates a hash value in the range `[0, 1]` from the given seed.
  23044. *
  23045. * @tsl
  23046. * @function
  23047. * @param {Node<float>} seed - The seed.
  23048. * @return {Node<float>} The hash value.
  23049. */
  23050. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  23051. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  23052. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  23053. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  23054. const result = word.shiftRight( 22 ).bitXor( word );
  23055. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  23056. } );
  23057. /**
  23058. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23059. * The corners are mapped to `0` and the center to `1`.
  23060. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23061. *
  23062. * @tsl
  23063. * @function
  23064. * @param {Node<float>} x - The value to remap.
  23065. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  23066. * @return {Node<float>} The remapped value.
  23067. */
  23068. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  23069. /**
  23070. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23071. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  23072. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23073. *
  23074. * @tsl
  23075. * @function
  23076. * @param {Node<float>} x - The value to remap.
  23077. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  23078. * @return {Node<float>} The remapped value.
  23079. */
  23080. 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 ) );
  23081. /**
  23082. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  23083. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  23084. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23085. *
  23086. * @tsl
  23087. * @function
  23088. * @param {Node<float>} x - The value to remap.
  23089. * @param {Node<float>} a - First control parameter.
  23090. * @param {Node<float>} b - Second control parameter.
  23091. * @return {Node<float>} The remapped value.
  23092. */
  23093. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  23094. /**
  23095. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  23096. * Reference: {@link https://iquilezles.org/articles/functions/}.
  23097. *
  23098. * @tsl
  23099. * @function
  23100. * @param {Node<float>} x - The value to compute the sin for.
  23101. * @param {Node<float>} k - Controls the amount of bounces.
  23102. * @return {Node<float>} The result value.
  23103. */
  23104. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  23105. // https://github.com/cabbibo/glsl-tri-noise-3d
  23106. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  23107. return x.fract().sub( .5 ).abs();
  23108. } ).setLayout( {
  23109. name: 'tri',
  23110. type: 'float',
  23111. inputs: [
  23112. { name: 'x', type: 'float' }
  23113. ]
  23114. } );
  23115. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  23116. 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. ) ) ) ) );
  23117. } ).setLayout( {
  23118. name: 'tri3',
  23119. type: 'vec3',
  23120. inputs: [
  23121. { name: 'p', type: 'vec3' }
  23122. ]
  23123. } );
  23124. /**
  23125. * Generates a noise value from the given position, speed and time parameters.
  23126. *
  23127. * @tsl
  23128. * @function
  23129. * @param {Node<vec3>} position - The position.
  23130. * @param {Node<float>} speed - The speed.
  23131. * @param {Node<float>} time - The time.
  23132. * @return {Node<float>} The generated noise.
  23133. */
  23134. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  23135. const p = vec3( position ).toVar();
  23136. const z = float( 1.4 ).toVar();
  23137. const rz = float( 0.0 ).toVar();
  23138. const bp = vec3( p ).toVar();
  23139. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  23140. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  23141. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  23142. bp.mulAssign( 1.8 );
  23143. z.mulAssign( 1.5 );
  23144. p.mulAssign( 1.2 );
  23145. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  23146. rz.addAssign( t.div( z ) );
  23147. bp.addAssign( 0.14 );
  23148. } );
  23149. return rz;
  23150. } ).setLayout( {
  23151. name: 'triNoise3D',
  23152. type: 'float',
  23153. inputs: [
  23154. { name: 'position', type: 'vec3' },
  23155. { name: 'speed', type: 'float' },
  23156. { name: 'time', type: 'float' }
  23157. ]
  23158. } );
  23159. /**
  23160. * This class allows to define multiple overloaded versions
  23161. * of the same function. Depending on the parameters of the function
  23162. * call, the node picks the best-fit overloaded version.
  23163. *
  23164. * @augments Node
  23165. */
  23166. class FunctionOverloadingNode extends Node {
  23167. static get type() {
  23168. return 'FunctionOverloadingNode';
  23169. }
  23170. /**
  23171. * Constructs a new function overloading node.
  23172. *
  23173. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  23174. * @param {...Node} parametersNodes - A list of parameter nodes.
  23175. */
  23176. constructor( functionNodes = [], ...parametersNodes ) {
  23177. super();
  23178. /**
  23179. * Array of `Fn` function definitions.
  23180. *
  23181. * @type {Array<Function>}
  23182. */
  23183. this.functionNodes = functionNodes;
  23184. /**
  23185. * A list of parameter nodes.
  23186. *
  23187. * @type {Array<Node>}
  23188. */
  23189. this.parametersNodes = parametersNodes;
  23190. /**
  23191. * The selected overloaded function call.
  23192. *
  23193. * @private
  23194. * @type {ShaderCallNodeInternal}
  23195. */
  23196. this._candidateFnCall = null;
  23197. /**
  23198. * This node is marked as global.
  23199. *
  23200. * @type {boolean}
  23201. * @default true
  23202. */
  23203. this.global = true;
  23204. }
  23205. /**
  23206. * This method is overwritten since the node type is inferred from
  23207. * the function's return type.
  23208. *
  23209. * @param {NodeBuilder} builder - The current node builder.
  23210. * @return {string} The node type.
  23211. */
  23212. getNodeType() {
  23213. return this.functionNodes[ 0 ].shaderNode.layout.type;
  23214. }
  23215. setup( builder ) {
  23216. const params = this.parametersNodes;
  23217. let candidateFnCall = this._candidateFnCall;
  23218. if ( candidateFnCall === null ) {
  23219. let candidateFn = null;
  23220. let candidateScore = -1;
  23221. for ( const functionNode of this.functionNodes ) {
  23222. const shaderNode = functionNode.shaderNode;
  23223. const layout = shaderNode.layout;
  23224. if ( layout === null ) {
  23225. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  23226. }
  23227. const inputs = layout.inputs;
  23228. if ( params.length === inputs.length ) {
  23229. let score = 0;
  23230. for ( let i = 0; i < params.length; i ++ ) {
  23231. const param = params[ i ];
  23232. const input = inputs[ i ];
  23233. if ( param.getNodeType( builder ) === input.type ) {
  23234. score ++;
  23235. } else {
  23236. score = 0;
  23237. }
  23238. }
  23239. if ( score > candidateScore ) {
  23240. candidateFn = functionNode;
  23241. candidateScore = score;
  23242. }
  23243. }
  23244. }
  23245. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  23246. }
  23247. return candidateFnCall;
  23248. }
  23249. }
  23250. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  23251. /**
  23252. * TSL function for creating a function overloading node.
  23253. *
  23254. * @tsl
  23255. * @function
  23256. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  23257. * @returns {FunctionOverloadingNode}
  23258. */
  23259. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  23260. /**
  23261. * Represents the elapsed time in seconds.
  23262. *
  23263. * @tsl
  23264. * @type {UniformNode<float>}
  23265. */
  23266. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  23267. /**
  23268. * Represents the delta time in seconds.
  23269. *
  23270. * @tsl
  23271. * @type {UniformNode<float>}
  23272. */
  23273. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  23274. /**
  23275. * Represents the current frame ID.
  23276. *
  23277. * @tsl
  23278. * @type {UniformNode<uint>}
  23279. */
  23280. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  23281. /**
  23282. * Generates a sine wave oscillation based on a timer.
  23283. *
  23284. * @tsl
  23285. * @function
  23286. * @param {Node<float>} t - The timer to generate the oscillation with.
  23287. * @return {Node<float>} The oscillation node.
  23288. */
  23289. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  23290. /**
  23291. * Generates a square wave oscillation based on a timer.
  23292. *
  23293. * @tsl
  23294. * @function
  23295. * @param {Node<float>} t - The timer to generate the oscillation with.
  23296. * @return {Node<float>} The oscillation node.
  23297. */
  23298. const oscSquare = ( t = time ) => t.fract().round();
  23299. /**
  23300. * Generates a triangle wave oscillation based on a timer.
  23301. *
  23302. * @tsl
  23303. * @function
  23304. * @param {Node<float>} t - The timer to generate the oscillation with.
  23305. * @return {Node<float>} The oscillation node.
  23306. */
  23307. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  23308. /**
  23309. * Generates a sawtooth wave oscillation based on a timer.
  23310. *
  23311. * @tsl
  23312. * @function
  23313. * @param {Node<float>} t - The timer to generate the oscillation with.
  23314. * @return {Node<float>} The oscillation node.
  23315. */
  23316. const oscSawtooth = ( t = time ) => t.fract();
  23317. /**
  23318. * Rotates the given uv coordinates around a center point
  23319. *
  23320. * @tsl
  23321. * @function
  23322. * @param {Node<vec2>} uv - The uv coordinates.
  23323. * @param {Node<float>} rotation - The rotation defined in radians.
  23324. * @param {Node<vec2>} center - The center of rotation
  23325. * @return {Node<vec2>} The rotated uv coordinates.
  23326. */
  23327. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  23328. return rotate( uv.sub( center ), rotation ).add( center );
  23329. } );
  23330. /**
  23331. * Applies a spherical warping effect to the given uv coordinates.
  23332. *
  23333. * @tsl
  23334. * @function
  23335. * @param {Node<vec2>} uv - The uv coordinates.
  23336. * @param {Node<float>} strength - The strength of the effect.
  23337. * @param {Node<vec2>} center - The center point
  23338. * @return {Node<vec2>} The updated uv coordinates.
  23339. */
  23340. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  23341. const delta = uv.sub( center );
  23342. const delta2 = delta.dot( delta );
  23343. const delta4 = delta2.mul( delta2 );
  23344. const deltaOffset = delta4.mul( strength );
  23345. return uv.add( delta.mul( deltaOffset ) );
  23346. } );
  23347. /**
  23348. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  23349. * oriented always towards the camera.
  23350. *
  23351. * ```js
  23352. * material.vertexNode = billboarding();
  23353. * ```
  23354. *
  23355. * @tsl
  23356. * @function
  23357. * @param {Object} config - The configuration object.
  23358. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  23359. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  23360. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  23361. * @return {Node<vec3>} The updated vertex position in clip space.
  23362. */
  23363. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  23364. let worldMatrix;
  23365. if ( position !== null ) {
  23366. worldMatrix = modelWorldMatrix.toVar();
  23367. worldMatrix[ 3 ][ 0 ] = position.x;
  23368. worldMatrix[ 3 ][ 1 ] = position.y;
  23369. worldMatrix[ 3 ][ 2 ] = position.z;
  23370. } else {
  23371. worldMatrix = modelWorldMatrix;
  23372. }
  23373. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  23374. if ( defined( horizontal ) ) {
  23375. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  23376. modelViewMatrix[ 0 ][ 1 ] = 0;
  23377. modelViewMatrix[ 0 ][ 2 ] = 0;
  23378. }
  23379. if ( defined( vertical ) ) {
  23380. modelViewMatrix[ 1 ][ 0 ] = 0;
  23381. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  23382. modelViewMatrix[ 1 ][ 2 ] = 0;
  23383. }
  23384. modelViewMatrix[ 2 ][ 0 ] = 0;
  23385. modelViewMatrix[ 2 ][ 1 ] = 0;
  23386. modelViewMatrix[ 2 ][ 2 ] = 1;
  23387. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  23388. } );
  23389. /**
  23390. * A special version of a screen uv function that involves a depth comparison
  23391. * when computing the final uvs. The function mitigates visual errors when
  23392. * using viewport texture nodes for refraction purposes. Without this function
  23393. * objects in front of a refractive surface might appear on the refractive surface
  23394. * which is incorrect.
  23395. *
  23396. * @tsl
  23397. * @function
  23398. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  23399. * @return {Node<vec2>} The update uv coordinates.
  23400. */
  23401. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  23402. const depth = linearDepth();
  23403. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  23404. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  23405. return finalUV;
  23406. } );
  23407. /**
  23408. * Can be used to compute texture coordinates for animated sprite sheets.
  23409. *
  23410. * ```js
  23411. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  23412. *
  23413. * material.colorNode = texture( spriteSheet, uvNode );
  23414. * ```
  23415. *
  23416. * @augments Node
  23417. */
  23418. class SpriteSheetUVNode extends Node {
  23419. static get type() {
  23420. return 'SpriteSheetUVNode';
  23421. }
  23422. /**
  23423. * Constructs a new sprite sheet uv node.
  23424. *
  23425. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23426. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  23427. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  23428. */
  23429. constructor( countNode, uvNode = uv$1(), frameNode = float( 0 ) ) {
  23430. super( 'vec2' );
  23431. /**
  23432. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23433. *
  23434. * @type {Node<vec2>}
  23435. */
  23436. this.countNode = countNode;
  23437. /**
  23438. * The uv node.
  23439. *
  23440. * @type {Node<vec2>}
  23441. */
  23442. this.uvNode = uvNode;
  23443. /**
  23444. * The node that defines the current frame/sprite.
  23445. *
  23446. * @type {Node<float>}
  23447. */
  23448. this.frameNode = frameNode;
  23449. }
  23450. setup() {
  23451. const { frameNode, uvNode, countNode } = this;
  23452. const { width, height } = countNode;
  23453. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  23454. const column = frameNum.mod( width );
  23455. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  23456. const scale = countNode.reciprocal();
  23457. const uvFrameOffset = vec2( column, row );
  23458. return uvNode.add( uvFrameOffset ).mul( scale );
  23459. }
  23460. }
  23461. /**
  23462. * TSL function for creating a sprite sheet uv node.
  23463. *
  23464. * @tsl
  23465. * @function
  23466. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  23467. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  23468. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  23469. * @returns {SpriteSheetUVNode}
  23470. */
  23471. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  23472. /**
  23473. * TSL function for creating a triplanar textures node.
  23474. *
  23475. * Can be used for triplanar texture mapping.
  23476. *
  23477. * ```js
  23478. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  23479. * ```
  23480. *
  23481. * @tsl
  23482. * @function
  23483. * @param {Node} textureXNode - First texture node.
  23484. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23485. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23486. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23487. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23488. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23489. * @returns {Node<vec4>}
  23490. */
  23491. const triplanarTextures = /*@__PURE__*/ Fn( ( [ textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ] ) => {
  23492. // Reference: https://github.com/keijiro/StandardTriplanar
  23493. // Blending factor of triplanar mapping
  23494. let bf = normalNode.abs().normalize();
  23495. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  23496. // Triplanar mapping
  23497. const tx = positionNode.yz.mul( scaleNode );
  23498. const ty = positionNode.zx.mul( scaleNode );
  23499. const tz = positionNode.xy.mul( scaleNode );
  23500. // Base color
  23501. const textureX = textureXNode.value;
  23502. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  23503. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  23504. const cx = texture( textureX, tx ).mul( bf.x );
  23505. const cy = texture( textureY, ty ).mul( bf.y );
  23506. const cz = texture( textureZ, tz ).mul( bf.z );
  23507. return add( cx, cy, cz );
  23508. } );
  23509. /**
  23510. * TSL function for creating a triplanar textures node.
  23511. *
  23512. * @tsl
  23513. * @function
  23514. * @param {Node} textureXNode - First texture node.
  23515. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  23516. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  23517. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  23518. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  23519. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  23520. * @returns {Node<vec4>}
  23521. */
  23522. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  23523. const _reflectorPlane = new Plane();
  23524. const _normal = new Vector3();
  23525. const _reflectorWorldPosition = new Vector3();
  23526. const _cameraWorldPosition = new Vector3();
  23527. const _rotationMatrix = new Matrix4();
  23528. const _lookAtPosition = new Vector3( 0, 0, -1 );
  23529. const clipPlane = new Vector4();
  23530. const _view = new Vector3();
  23531. const _target = new Vector3();
  23532. const _q = new Vector4();
  23533. const _size$2 = new Vector2();
  23534. const _defaultRT = new RenderTarget();
  23535. const _defaultUV = screenUV.flipX();
  23536. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  23537. let _inReflector = false;
  23538. /**
  23539. * This node can be used to implement mirror-like flat reflective surfaces.
  23540. *
  23541. * ```js
  23542. * const groundReflector = reflector();
  23543. * material.colorNode = groundReflector;
  23544. *
  23545. * const plane = new Mesh( geometry, material );
  23546. * plane.add( groundReflector.target );
  23547. * ```
  23548. *
  23549. * @augments TextureNode
  23550. */
  23551. class ReflectorNode extends TextureNode {
  23552. static get type() {
  23553. return 'ReflectorNode';
  23554. }
  23555. /**
  23556. * Constructs a new reflector node.
  23557. *
  23558. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23559. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23560. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  23561. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23562. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23563. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23564. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  23565. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  23566. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  23567. */
  23568. constructor( parameters = {} ) {
  23569. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  23570. /**
  23571. * A reference to the internal reflector base node which holds the actual implementation.
  23572. *
  23573. * @private
  23574. * @type {ReflectorBaseNode}
  23575. * @default ReflectorBaseNode
  23576. */
  23577. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  23578. /**
  23579. * A reference to the internal depth node.
  23580. *
  23581. * @private
  23582. * @type {?Node}
  23583. * @default null
  23584. */
  23585. this._depthNode = null;
  23586. this.setUpdateMatrix( false );
  23587. }
  23588. /**
  23589. * A reference to the internal reflector node.
  23590. *
  23591. * @type {ReflectorBaseNode}
  23592. */
  23593. get reflector() {
  23594. return this._reflectorBaseNode;
  23595. }
  23596. /**
  23597. * A reference to 3D object the reflector is linked to.
  23598. *
  23599. * @type {Object3D}
  23600. */
  23601. get target() {
  23602. return this._reflectorBaseNode.target;
  23603. }
  23604. /**
  23605. * Returns a node representing the mirror's depth. That can be used
  23606. * to implement more advanced reflection effects like distance attenuation.
  23607. *
  23608. * @return {Node} The depth node.
  23609. */
  23610. getDepthNode() {
  23611. if ( this._depthNode === null ) {
  23612. if ( this._reflectorBaseNode.depth !== true ) {
  23613. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  23614. }
  23615. this._depthNode = nodeObject( new ReflectorNode( {
  23616. defaultTexture: _defaultRT.depthTexture,
  23617. reflector: this._reflectorBaseNode
  23618. } ) );
  23619. }
  23620. return this._depthNode;
  23621. }
  23622. setup( builder ) {
  23623. // ignore if used in post-processing
  23624. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  23625. return super.setup( builder );
  23626. }
  23627. clone() {
  23628. const newNode = new this.constructor( this.reflectorNode );
  23629. newNode.uvNode = this.uvNode;
  23630. newNode.levelNode = this.levelNode;
  23631. newNode.biasNode = this.biasNode;
  23632. newNode.sampler = this.sampler;
  23633. newNode.depthNode = this.depthNode;
  23634. newNode.compareNode = this.compareNode;
  23635. newNode.gradNode = this.gradNode;
  23636. newNode._reflectorBaseNode = this._reflectorBaseNode;
  23637. return newNode;
  23638. }
  23639. /**
  23640. * Frees internal resources. Should be called when the node is no longer in use.
  23641. */
  23642. dispose() {
  23643. super.dispose();
  23644. this._reflectorBaseNode.dispose();
  23645. }
  23646. }
  23647. /**
  23648. * Holds the actual implementation of the reflector.
  23649. *
  23650. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  23651. * in `ReflectorNode`, see #29619.
  23652. *
  23653. * @private
  23654. * @augments Node
  23655. */
  23656. class ReflectorBaseNode extends Node {
  23657. static get type() {
  23658. return 'ReflectorBaseNode';
  23659. }
  23660. /**
  23661. * Constructs a new reflector base node.
  23662. *
  23663. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  23664. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23665. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23666. * @param {number} [parameters.resolutionScale=1] - The resolution scale.
  23667. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23668. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23669. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23670. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  23671. */
  23672. constructor( textureNode, parameters = {} ) {
  23673. super();
  23674. const {
  23675. target = new Object3D(),
  23676. resolutionScale = 1,
  23677. generateMipmaps = false,
  23678. bounces = true,
  23679. depth = false,
  23680. samples = 0
  23681. } = parameters;
  23682. /**
  23683. * Represents the rendered reflections as a texture node.
  23684. *
  23685. * @type {TextureNode}
  23686. */
  23687. this.textureNode = textureNode;
  23688. /**
  23689. * The 3D object the reflector is linked to.
  23690. *
  23691. * @type {Object3D}
  23692. * @default {new Object3D()}
  23693. */
  23694. this.target = target;
  23695. /**
  23696. * The resolution scale.
  23697. *
  23698. * @type {number}
  23699. * @default {1}
  23700. */
  23701. this.resolutionScale = resolutionScale;
  23702. if ( parameters.resolution !== undefined ) {
  23703. warnOnce( 'THREE.ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".' ); // @deprecated r180
  23704. this.resolutionScale = parameters.resolution;
  23705. }
  23706. /**
  23707. * Whether mipmaps should be generated or not.
  23708. *
  23709. * @type {boolean}
  23710. * @default {false}
  23711. */
  23712. this.generateMipmaps = generateMipmaps;
  23713. /**
  23714. * Whether reflectors can render other reflector nodes or not.
  23715. *
  23716. * @type {boolean}
  23717. * @default {true}
  23718. */
  23719. this.bounces = bounces;
  23720. /**
  23721. * Whether depth data should be generated or not.
  23722. *
  23723. * @type {boolean}
  23724. * @default {false}
  23725. */
  23726. this.depth = depth;
  23727. /**
  23728. * The number of anti-aliasing samples for the render-target
  23729. *
  23730. * @type {number}
  23731. * @default {0}
  23732. */
  23733. this.samples = samples;
  23734. /**
  23735. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  23736. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  23737. *
  23738. * @type {string}
  23739. * @default 'render'
  23740. */
  23741. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  23742. /**
  23743. * Weak map for managing virtual cameras.
  23744. *
  23745. * @type {WeakMap<Camera, Camera>}
  23746. */
  23747. this.virtualCameras = new WeakMap();
  23748. /**
  23749. * Weak map for managing render targets.
  23750. *
  23751. * @type {Map<Camera, RenderTarget>}
  23752. */
  23753. this.renderTargets = new Map();
  23754. /**
  23755. * Force render even if reflector is facing away from camera.
  23756. *
  23757. * @type {boolean}
  23758. * @default {false}
  23759. */
  23760. this.forceUpdate = false;
  23761. /**
  23762. * Whether the reflector has been rendered or not.
  23763. *
  23764. * When the reflector is facing away from the camera,
  23765. * this flag is set to `false` and the texture will be empty(black).
  23766. *
  23767. * @type {boolean}
  23768. * @default {false}
  23769. */
  23770. this.hasOutput = false;
  23771. }
  23772. /**
  23773. * Updates the resolution of the internal render target.
  23774. *
  23775. * @private
  23776. * @param {RenderTarget} renderTarget - The render target to resize.
  23777. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  23778. */
  23779. _updateResolution( renderTarget, renderer ) {
  23780. const resolution = this.resolutionScale;
  23781. renderer.getDrawingBufferSize( _size$2 );
  23782. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  23783. }
  23784. setup( builder ) {
  23785. this._updateResolution( _defaultRT, builder.renderer );
  23786. return super.setup( builder );
  23787. }
  23788. /**
  23789. * Frees internal resources. Should be called when the node is no longer in use.
  23790. */
  23791. dispose() {
  23792. super.dispose();
  23793. for ( const renderTarget of this.renderTargets.values() ) {
  23794. renderTarget.dispose();
  23795. }
  23796. }
  23797. /**
  23798. * Returns a virtual camera for the given camera. The virtual camera is used to
  23799. * render the scene from the reflector's view so correct reflections can be produced.
  23800. *
  23801. * @param {Camera} camera - The scene's camera.
  23802. * @return {Camera} The corresponding virtual camera.
  23803. */
  23804. getVirtualCamera( camera ) {
  23805. let virtualCamera = this.virtualCameras.get( camera );
  23806. if ( virtualCamera === undefined ) {
  23807. virtualCamera = camera.clone();
  23808. this.virtualCameras.set( camera, virtualCamera );
  23809. }
  23810. return virtualCamera;
  23811. }
  23812. /**
  23813. * Returns a render target for the given camera. The reflections are rendered
  23814. * into this render target.
  23815. *
  23816. * @param {Camera} camera - The scene's camera.
  23817. * @return {RenderTarget} The render target.
  23818. */
  23819. getRenderTarget( camera ) {
  23820. let renderTarget = this.renderTargets.get( camera );
  23821. if ( renderTarget === undefined ) {
  23822. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType, samples: this.samples } );
  23823. if ( this.generateMipmaps === true ) {
  23824. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  23825. renderTarget.texture.generateMipmaps = true;
  23826. }
  23827. if ( this.depth === true ) {
  23828. renderTarget.depthTexture = new DepthTexture();
  23829. }
  23830. this.renderTargets.set( camera, renderTarget );
  23831. }
  23832. return renderTarget;
  23833. }
  23834. updateBefore( frame ) {
  23835. if ( this.bounces === false && _inReflector ) return false;
  23836. _inReflector = true;
  23837. const { scene, camera, renderer, material } = frame;
  23838. const { target } = this;
  23839. const virtualCamera = this.getVirtualCamera( camera );
  23840. const renderTarget = this.getRenderTarget( virtualCamera );
  23841. renderer.getDrawingBufferSize( _size$2 );
  23842. this._updateResolution( renderTarget, renderer );
  23843. //
  23844. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  23845. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  23846. _rotationMatrix.extractRotation( target.matrixWorld );
  23847. _normal.set( 0, 0, 1 );
  23848. _normal.applyMatrix4( _rotationMatrix );
  23849. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  23850. // Avoid rendering when reflector is facing away unless forcing an update
  23851. const isFacingAway = _view.dot( _normal ) > 0;
  23852. let needsClear = false;
  23853. if ( isFacingAway === true && this.forceUpdate === false ) {
  23854. if ( this.hasOutput === false ) {
  23855. _inReflector = false;
  23856. return;
  23857. }
  23858. needsClear = true;
  23859. }
  23860. _view.reflect( _normal ).negate();
  23861. _view.add( _reflectorWorldPosition );
  23862. _rotationMatrix.extractRotation( camera.matrixWorld );
  23863. _lookAtPosition.set( 0, 0, -1 );
  23864. _lookAtPosition.applyMatrix4( _rotationMatrix );
  23865. _lookAtPosition.add( _cameraWorldPosition );
  23866. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  23867. _target.reflect( _normal ).negate();
  23868. _target.add( _reflectorWorldPosition );
  23869. //
  23870. virtualCamera.coordinateSystem = camera.coordinateSystem;
  23871. virtualCamera.position.copy( _view );
  23872. virtualCamera.up.set( 0, 1, 0 );
  23873. virtualCamera.up.applyMatrix4( _rotationMatrix );
  23874. virtualCamera.up.reflect( _normal );
  23875. virtualCamera.lookAt( _target );
  23876. virtualCamera.near = camera.near;
  23877. virtualCamera.far = camera.far;
  23878. virtualCamera.updateMatrixWorld();
  23879. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  23880. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  23881. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  23882. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  23883. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  23884. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  23885. const projectionMatrix = virtualCamera.projectionMatrix;
  23886. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  23887. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  23888. _q.z = -1;
  23889. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  23890. // Calculate the scaled plane vector
  23891. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  23892. const clipBias = 0;
  23893. // Replacing the third row of the projection matrix
  23894. projectionMatrix.elements[ 2 ] = clipPlane.x;
  23895. projectionMatrix.elements[ 6 ] = clipPlane.y;
  23896. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  23897. projectionMatrix.elements[ 14 ] = clipPlane.w;
  23898. //
  23899. this.textureNode.value = renderTarget.texture;
  23900. if ( this.depth === true ) {
  23901. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  23902. }
  23903. material.visible = false;
  23904. const currentRenderTarget = renderer.getRenderTarget();
  23905. const currentMRT = renderer.getMRT();
  23906. const currentAutoClear = renderer.autoClear;
  23907. renderer.setMRT( null );
  23908. renderer.setRenderTarget( renderTarget );
  23909. renderer.autoClear = true;
  23910. if ( needsClear ) {
  23911. renderer.clear();
  23912. this.hasOutput = false;
  23913. } else {
  23914. renderer.render( scene, virtualCamera );
  23915. this.hasOutput = true;
  23916. }
  23917. renderer.setMRT( currentMRT );
  23918. renderer.setRenderTarget( currentRenderTarget );
  23919. renderer.autoClear = currentAutoClear;
  23920. material.visible = true;
  23921. _inReflector = false;
  23922. this.forceUpdate = false;
  23923. }
  23924. /**
  23925. * The resolution scale.
  23926. *
  23927. * @deprecated
  23928. * @type {number}
  23929. * @default {1}
  23930. */
  23931. get resolution() {
  23932. warnOnce( 'THREE.ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  23933. return this.resolutionScale;
  23934. }
  23935. set resolution( value ) {
  23936. warnOnce( 'THREE.ReflectorNode: The "resolution" property has been renamed to "resolutionScale".' ); // @deprecated r180
  23937. this.resolutionScale = value;
  23938. }
  23939. }
  23940. /**
  23941. * TSL function for creating a reflector node.
  23942. *
  23943. * @tsl
  23944. * @function
  23945. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23946. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23947. * @param {number} [parameters.resolution=1] - The resolution scale.
  23948. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23949. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23950. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23951. * @param {number} [parameters.samples] - Anti-Aliasing samples of the internal render-target.
  23952. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  23953. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  23954. * @returns {ReflectorNode}
  23955. */
  23956. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  23957. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  23958. /**
  23959. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  23960. *
  23961. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  23962. *
  23963. * @private
  23964. * @augments BufferGeometry
  23965. */
  23966. class QuadGeometry extends BufferGeometry {
  23967. /**
  23968. * Constructs a new quad geometry.
  23969. *
  23970. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  23971. */
  23972. constructor( flipY = false ) {
  23973. super();
  23974. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  23975. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  23976. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  23977. }
  23978. }
  23979. const _geometry = /*@__PURE__*/ new QuadGeometry();
  23980. /**
  23981. * This module is a helper for passes which need to render a full
  23982. * screen effect which is quite common in context of post processing.
  23983. *
  23984. * The intended usage is to reuse a single quad mesh for rendering
  23985. * subsequent passes by just reassigning the `material` reference.
  23986. *
  23987. * Note: This module can only be used with `WebGPURenderer`.
  23988. *
  23989. * @augments Mesh
  23990. */
  23991. class QuadMesh extends Mesh {
  23992. /**
  23993. * Constructs a new quad mesh.
  23994. *
  23995. * @param {?Material} [material=null] - The material to render the quad mesh with.
  23996. */
  23997. constructor( material = null ) {
  23998. super( _geometry, material );
  23999. /**
  24000. * The camera to render the quad mesh with.
  24001. *
  24002. * @type {OrthographicCamera}
  24003. * @readonly
  24004. */
  24005. this.camera = _camera;
  24006. /**
  24007. * This flag can be used for type testing.
  24008. *
  24009. * @type {boolean}
  24010. * @readonly
  24011. * @default true
  24012. */
  24013. this.isQuadMesh = true;
  24014. }
  24015. /**
  24016. * Async version of `render()`.
  24017. *
  24018. * @async
  24019. * @param {Renderer} renderer - The renderer.
  24020. * @return {Promise} A Promise that resolves when the render has been finished.
  24021. */
  24022. async renderAsync( renderer ) {
  24023. return renderer.renderAsync( this, _camera );
  24024. }
  24025. /**
  24026. * Renders the quad mesh
  24027. *
  24028. * @param {Renderer} renderer - The renderer.
  24029. */
  24030. render( renderer ) {
  24031. renderer.render( this, _camera );
  24032. }
  24033. }
  24034. const _size$1 = /*@__PURE__*/ new Vector2();
  24035. /**
  24036. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  24037. * This module is especially relevant in context of post processing where certain nodes require
  24038. * texture input for their effects. With the helper function `convertToTexture()` which is based
  24039. * on this module, the node system can automatically ensure texture input if required.
  24040. *
  24041. * @augments TextureNode
  24042. */
  24043. class RTTNode extends TextureNode {
  24044. static get type() {
  24045. return 'RTTNode';
  24046. }
  24047. /**
  24048. * Constructs a new RTT node.
  24049. *
  24050. * @param {Node} node - The node to render a texture with.
  24051. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24052. * @param {?number} [height=null] - The height of the internal render target.
  24053. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24054. */
  24055. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  24056. const renderTarget = new RenderTarget( width, height, options );
  24057. super( renderTarget.texture, uv$1() );
  24058. /**
  24059. * This flag can be used for type testing.
  24060. *
  24061. * @type {boolean}
  24062. * @readonly
  24063. * @default true
  24064. */
  24065. this.isRTTNode = true;
  24066. /**
  24067. * The node to render a texture with.
  24068. *
  24069. * @type {Node}
  24070. */
  24071. this.node = node;
  24072. /**
  24073. * The width of the internal render target.
  24074. * If not width is applied, the render target is automatically resized.
  24075. *
  24076. * @type {?number}
  24077. * @default null
  24078. */
  24079. this.width = width;
  24080. /**
  24081. * The height of the internal render target.
  24082. *
  24083. * @type {?number}
  24084. * @default null
  24085. */
  24086. this.height = height;
  24087. /**
  24088. * The pixel ratio
  24089. *
  24090. * @type {number}
  24091. * @default 1
  24092. */
  24093. this.pixelRatio = 1;
  24094. /**
  24095. * The render target
  24096. *
  24097. * @type {RenderTarget}
  24098. */
  24099. this.renderTarget = renderTarget;
  24100. /**
  24101. * Whether the texture requires an update or not.
  24102. *
  24103. * @type {boolean}
  24104. * @default true
  24105. */
  24106. this.textureNeedsUpdate = true;
  24107. /**
  24108. * Whether the texture should automatically be updated or not.
  24109. *
  24110. * @type {boolean}
  24111. * @default true
  24112. */
  24113. this.autoUpdate = true;
  24114. /**
  24115. * The node which is used with the quad mesh for RTT.
  24116. *
  24117. * @private
  24118. * @type {Node}
  24119. * @default null
  24120. */
  24121. this._rttNode = null;
  24122. /**
  24123. * The internal quad mesh for RTT.
  24124. *
  24125. * @private
  24126. * @type {QuadMesh}
  24127. */
  24128. this._quadMesh = new QuadMesh( new NodeMaterial() );
  24129. /**
  24130. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  24131. * the texture once per render in its {@link RTTNode#updateBefore} method.
  24132. *
  24133. * @type {string}
  24134. * @default 'render'
  24135. */
  24136. this.updateBeforeType = NodeUpdateType.RENDER;
  24137. }
  24138. /**
  24139. * Whether the internal render target should automatically be resized or not.
  24140. *
  24141. * @type {boolean}
  24142. * @readonly
  24143. * @default true
  24144. */
  24145. get autoResize() {
  24146. return this.width === null;
  24147. }
  24148. setup( builder ) {
  24149. this._rttNode = this.node.context( builder.getSharedContext() );
  24150. this._quadMesh.material.name = 'RTT';
  24151. this._quadMesh.material.needsUpdate = true;
  24152. return super.setup( builder );
  24153. }
  24154. /**
  24155. * Sets the size of the internal render target
  24156. *
  24157. * @param {number} width - The width to set.
  24158. * @param {number} height - The width to set.
  24159. */
  24160. setSize( width, height ) {
  24161. this.width = width;
  24162. this.height = height;
  24163. const effectiveWidth = width * this.pixelRatio;
  24164. const effectiveHeight = height * this.pixelRatio;
  24165. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24166. this.textureNeedsUpdate = true;
  24167. }
  24168. /**
  24169. * Sets the pixel ratio. This will also resize the render target.
  24170. *
  24171. * @param {number} pixelRatio - The pixel ratio to set.
  24172. */
  24173. setPixelRatio( pixelRatio ) {
  24174. this.pixelRatio = pixelRatio;
  24175. this.setSize( this.width, this.height );
  24176. }
  24177. updateBefore( { renderer } ) {
  24178. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  24179. this.textureNeedsUpdate = false;
  24180. //
  24181. if ( this.autoResize === true ) {
  24182. const pixelRatio = renderer.getPixelRatio();
  24183. const size = renderer.getSize( _size$1 );
  24184. const effectiveWidth = size.width * pixelRatio;
  24185. const effectiveHeight = size.height * pixelRatio;
  24186. if ( effectiveWidth !== this.renderTarget.width || effectiveHeight !== this.renderTarget.height ) {
  24187. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24188. this.textureNeedsUpdate = true;
  24189. }
  24190. }
  24191. //
  24192. this._quadMesh.material.fragmentNode = this._rttNode;
  24193. //
  24194. const currentRenderTarget = renderer.getRenderTarget();
  24195. renderer.setRenderTarget( this.renderTarget );
  24196. this._quadMesh.render( renderer );
  24197. renderer.setRenderTarget( currentRenderTarget );
  24198. }
  24199. clone() {
  24200. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  24201. newNode.sampler = this.sampler;
  24202. newNode.referenceNode = this;
  24203. return newNode;
  24204. }
  24205. }
  24206. /**
  24207. * TSL function for creating a RTT node.
  24208. *
  24209. * @tsl
  24210. * @function
  24211. * @param {Node} node - The node to render a texture with.
  24212. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24213. * @param {?number} [height=null] - The height of the internal render target.
  24214. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24215. * @returns {RTTNode}
  24216. */
  24217. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  24218. /**
  24219. * TSL function for converting nodes to textures nodes.
  24220. *
  24221. * @tsl
  24222. * @function
  24223. * @param {Node} node - The node to render a texture with.
  24224. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  24225. * @param {?number} [height=null] - The height of the internal render target.
  24226. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  24227. * @returns {RTTNode}
  24228. */
  24229. const convertToTexture = ( node, ...params ) => {
  24230. if ( node.isSampleNode || node.isTextureNode ) return node;
  24231. if ( node.isPassNode ) return node.getTextureNode();
  24232. return rtt( node, ...params );
  24233. };
  24234. /**
  24235. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  24236. * depth value and the camera's inverse projection matrix.
  24237. *
  24238. * @tsl
  24239. * @function
  24240. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  24241. * @param {Node<float>} depth - The fragment's depth value.
  24242. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  24243. * @return {Node<vec3>} The fragments position in view space.
  24244. */
  24245. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  24246. let clipSpacePosition;
  24247. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  24248. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  24249. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  24250. } else {
  24251. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  24252. }
  24253. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  24254. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  24255. } );
  24256. /**
  24257. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  24258. * and the camera's projection matrix
  24259. *
  24260. * @tsl
  24261. * @function
  24262. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  24263. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  24264. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  24265. */
  24266. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  24267. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  24268. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  24269. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  24270. } );
  24271. /**
  24272. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  24273. * target is available or if flat surface normals are required.
  24274. *
  24275. * @tsl
  24276. * @function
  24277. * @param {Node<vec2>} uv - The texture coordinate.
  24278. * @param {DepthTexture} depthTexture - The depth texture.
  24279. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  24280. * @return {Node<vec3>} The computed normal vector.
  24281. */
  24282. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  24283. const size = textureSize( textureLoad( depthTexture ) );
  24284. const p = ivec2( uv.mul( size ) ).toVar();
  24285. const c0 = textureLoad( depthTexture, p ).toVar();
  24286. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  24287. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  24288. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  24289. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  24290. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  24291. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  24292. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  24293. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  24294. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  24295. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  24296. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  24297. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  24298. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  24299. 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 ) ) );
  24300. 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 ) ) );
  24301. return normalize( cross( dpdx, dpdy ) );
  24302. } );
  24303. /**
  24304. * Class representing a node that samples a value using a provided callback function.
  24305. *
  24306. * @extends Node
  24307. */
  24308. class SampleNode extends Node {
  24309. /**
  24310. * Returns the type of the node.
  24311. *
  24312. * @type {string}
  24313. * @readonly
  24314. * @static
  24315. */
  24316. static get type() {
  24317. return 'SampleNode';
  24318. }
  24319. /**
  24320. * Creates an instance of SampleNode.
  24321. *
  24322. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24323. * @param {?Node<vec2>} [uvNode=null] - The UV node to be used in the texture sampling.
  24324. */
  24325. constructor( callback, uvNode = null ) {
  24326. super();
  24327. this.callback = callback;
  24328. /**
  24329. * Represents the texture coordinates.
  24330. *
  24331. * @type {?Node<vec2|vec3>}
  24332. * @default null
  24333. */
  24334. this.uvNode = uvNode;
  24335. /**
  24336. * This flag can be used for type testing.
  24337. *
  24338. * @type {boolean}
  24339. * @readonly
  24340. * @default true
  24341. */
  24342. this.isSampleNode = true;
  24343. }
  24344. /**
  24345. * Sets up the node by sampling with the default UV accessor.
  24346. *
  24347. * @returns {Node} The result of the callback function when called with the UV node.
  24348. */
  24349. setup() {
  24350. return this.sample( uv$1() );
  24351. }
  24352. /**
  24353. * Calls the callback function with the provided UV node.
  24354. *
  24355. * @param {Node<vec2>} uv - The UV node or value to be passed to the callback.
  24356. * @returns {Node} The result of the callback function.
  24357. */
  24358. sample( uv ) {
  24359. return this.callback( uv );
  24360. }
  24361. }
  24362. /**
  24363. * Helper function to create a SampleNode wrapped as a node object.
  24364. *
  24365. * @function
  24366. * @param {Function} callback - The function to be called when sampling. Should accept a UV node and return a value.
  24367. * @param {?Node<vec2>} [uv=null] - The UV node to be used in the texture sampling.
  24368. * @returns {SampleNode} The created SampleNode instance wrapped as a node object.
  24369. */
  24370. const sample = ( callback, uv = null ) => nodeObject( new SampleNode( callback, nodeObject( uv ) ) );
  24371. /**
  24372. * EventNode is a node that executes a callback during specific update phases.
  24373. *
  24374. * @augments Node
  24375. */
  24376. class EventNode extends Node {
  24377. static get type() {
  24378. return 'EventNode';
  24379. }
  24380. /**
  24381. * Creates an EventNode.
  24382. *
  24383. * @param {string} eventType - The type of event
  24384. * @param {Function} callback - The callback to execute on update.
  24385. */
  24386. constructor( eventType, callback ) {
  24387. super( 'void' );
  24388. this.eventType = eventType;
  24389. this.callback = callback;
  24390. if ( eventType === EventNode.OBJECT ) {
  24391. this.updateType = NodeUpdateType.OBJECT;
  24392. } else if ( eventType === EventNode.MATERIAL ) {
  24393. this.updateType = NodeUpdateType.RENDER;
  24394. }
  24395. }
  24396. update( frame ) {
  24397. this.callback( frame );
  24398. }
  24399. }
  24400. EventNode.OBJECT = 'object';
  24401. EventNode.MATERIAL = 'material';
  24402. /**
  24403. * Helper to create an EventNode and add it to the stack.
  24404. *
  24405. * @param {string} type - The event type.
  24406. * @param {Function} callback - The callback function.
  24407. * @returns {EventNode}
  24408. */
  24409. const createEvent = ( type, callback ) => nodeObject( new EventNode( type, callback ) ).toStack();
  24410. /**
  24411. * Creates an event that triggers a function every time an object (Mesh|Sprite) is rendered.
  24412. *
  24413. * 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.
  24414. *
  24415. * @param {Function} callback - The callback function.
  24416. * @returns {EventNode}
  24417. */
  24418. const OnObjectUpdate = ( callback ) => createEvent( EventNode.OBJECT, callback );
  24419. /**
  24420. * Creates an event that triggers a function when the first object that uses the material is rendered.
  24421. *
  24422. * 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.
  24423. *
  24424. * @param {Function} callback - The callback function.
  24425. * @returns {EventNode}
  24426. */
  24427. const OnMaterialUpdate = ( callback ) => createEvent( EventNode.MATERIAL, callback );
  24428. /**
  24429. * This special type of instanced buffer attribute is intended for compute shaders.
  24430. * In earlier three.js versions it was only possible to update attribute data
  24431. * on the CPU via JavaScript and then upload the data to the GPU. With the
  24432. * new material system and renderer it is now possible to use compute shaders
  24433. * to compute the data for an attribute more efficiently on the GPU.
  24434. *
  24435. * The idea is to create an instance of this class and provide it as an input
  24436. * to {@link StorageBufferNode}.
  24437. *
  24438. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  24439. *
  24440. * @augments InstancedBufferAttribute
  24441. */
  24442. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  24443. /**
  24444. * Constructs a new storage instanced buffer attribute.
  24445. *
  24446. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  24447. * The subsequent parameters are then obsolete.
  24448. * @param {number} itemSize - The item size.
  24449. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  24450. */
  24451. constructor( count, itemSize, typeClass = Float32Array ) {
  24452. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  24453. super( array, itemSize );
  24454. /**
  24455. * This flag can be used for type testing.
  24456. *
  24457. * @type {boolean}
  24458. * @readonly
  24459. * @default true
  24460. */
  24461. this.isStorageInstancedBufferAttribute = true;
  24462. }
  24463. }
  24464. /**
  24465. * This special type of buffer attribute is intended for compute shaders.
  24466. * In earlier three.js versions it was only possible to update attribute data
  24467. * on the CPU via JavaScript and then upload the data to the GPU. With the
  24468. * new material system and renderer it is now possible to use compute shaders
  24469. * to compute the data for an attribute more efficiently on the GPU.
  24470. *
  24471. * The idea is to create an instance of this class and provide it as an input
  24472. * to {@link StorageBufferNode}.
  24473. *
  24474. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  24475. *
  24476. * @augments BufferAttribute
  24477. */
  24478. class StorageBufferAttribute extends BufferAttribute {
  24479. /**
  24480. * Constructs a new storage buffer attribute.
  24481. *
  24482. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  24483. * The subsequent parameters are then obsolete.
  24484. * @param {number} itemSize - The item size.
  24485. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  24486. */
  24487. constructor( count, itemSize, typeClass = Float32Array ) {
  24488. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  24489. super( array, itemSize );
  24490. /**
  24491. * This flag can be used for type testing.
  24492. *
  24493. * @type {boolean}
  24494. * @readonly
  24495. * @default true
  24496. */
  24497. this.isStorageBufferAttribute = true;
  24498. }
  24499. }
  24500. /**
  24501. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  24502. *
  24503. * @tsl
  24504. * @function
  24505. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24506. * @param {string|Struct} [type='float'] - The data type.
  24507. * @returns {StorageBufferNode}
  24508. */
  24509. const attributeArray = ( count, type = 'float' ) => {
  24510. let itemSize, typedArray;
  24511. if ( type.isStruct === true ) {
  24512. itemSize = type.layout.getLength();
  24513. typedArray = getTypedArrayFromType( 'float' );
  24514. } else {
  24515. itemSize = getLengthFromType( type );
  24516. typedArray = getTypedArrayFromType( type );
  24517. }
  24518. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  24519. const node = storage( buffer, type, count );
  24520. return node;
  24521. };
  24522. /**
  24523. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  24524. *
  24525. * @tsl
  24526. * @function
  24527. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  24528. * @param {string|Struct} [type='float'] - The data type.
  24529. * @returns {StorageBufferNode}
  24530. */
  24531. const instancedArray = ( count, type = 'float' ) => {
  24532. let itemSize, typedArray;
  24533. if ( type.isStruct === true ) {
  24534. itemSize = type.layout.getLength();
  24535. typedArray = getTypedArrayFromType( 'float' );
  24536. } else {
  24537. itemSize = getLengthFromType( type );
  24538. typedArray = getTypedArrayFromType( type );
  24539. }
  24540. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  24541. const node = storage( buffer, type, count );
  24542. return node;
  24543. };
  24544. /**
  24545. * A node for representing the uv coordinates of points.
  24546. *
  24547. * Can only be used with a WebGL backend. In WebGPU, point
  24548. * primitives always have the size of one pixel and can thus
  24549. * can't be used as sprite-like objects that display textures.
  24550. *
  24551. * @augments Node
  24552. */
  24553. class PointUVNode extends Node {
  24554. static get type() {
  24555. return 'PointUVNode';
  24556. }
  24557. /**
  24558. * Constructs a new point uv node.
  24559. */
  24560. constructor() {
  24561. super( 'vec2' );
  24562. /**
  24563. * This flag can be used for type testing.
  24564. *
  24565. * @type {boolean}
  24566. * @readonly
  24567. * @default true
  24568. */
  24569. this.isPointUVNode = true;
  24570. }
  24571. generate( /*builder*/ ) {
  24572. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  24573. }
  24574. }
  24575. /**
  24576. * TSL object that represents the uv coordinates of points.
  24577. *
  24578. * @tsl
  24579. * @type {PointUVNode}
  24580. */
  24581. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  24582. const _e1 = /*@__PURE__*/ new Euler();
  24583. const _m1 = /*@__PURE__*/ new Matrix4();
  24584. /**
  24585. * This module allows access to a collection of scene properties. The following predefined TSL objects
  24586. * are available for easier use:
  24587. *
  24588. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  24589. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  24590. * - `backgroundRotation`: A node that represents the scene's background rotation.
  24591. *
  24592. * @augments Node
  24593. */
  24594. class SceneNode extends Node {
  24595. static get type() {
  24596. return 'SceneNode';
  24597. }
  24598. /**
  24599. * Constructs a new scene node.
  24600. *
  24601. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  24602. * @param {?Scene} [scene=null] - A reference to the scene.
  24603. */
  24604. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  24605. super();
  24606. /**
  24607. * The scope defines the type of scene property that is accessed.
  24608. *
  24609. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  24610. */
  24611. this.scope = scope;
  24612. /**
  24613. * A reference to the scene that is going to be accessed.
  24614. *
  24615. * @type {?Scene}
  24616. * @default null
  24617. */
  24618. this.scene = scene;
  24619. }
  24620. /**
  24621. * Depending on the scope, the method returns a different type of node that represents
  24622. * the respective scene property.
  24623. *
  24624. * @param {NodeBuilder} builder - The current node builder.
  24625. * @return {Node} The output node.
  24626. */
  24627. setup( builder ) {
  24628. const scope = this.scope;
  24629. const scene = this.scene !== null ? this.scene : builder.scene;
  24630. let output;
  24631. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  24632. output = reference( 'backgroundBlurriness', 'float', scene );
  24633. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  24634. output = reference( 'backgroundIntensity', 'float', scene );
  24635. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  24636. output = uniform( 'mat4' ).setName( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  24637. const background = scene.background;
  24638. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  24639. _e1.copy( scene.backgroundRotation );
  24640. // accommodate left-handed frame
  24641. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  24642. _m1.makeRotationFromEuler( _e1 );
  24643. } else {
  24644. _m1.identity();
  24645. }
  24646. return _m1;
  24647. } );
  24648. } else {
  24649. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  24650. }
  24651. return output;
  24652. }
  24653. }
  24654. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  24655. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  24656. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  24657. /**
  24658. * TSL object that represents the scene's background blurriness.
  24659. *
  24660. * @tsl
  24661. * @type {SceneNode}
  24662. */
  24663. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  24664. /**
  24665. * TSL object that represents the scene's background intensity.
  24666. *
  24667. * @tsl
  24668. * @type {SceneNode}
  24669. */
  24670. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  24671. /**
  24672. * TSL object that represents the scene's background rotation.
  24673. *
  24674. * @tsl
  24675. * @type {SceneNode}
  24676. */
  24677. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  24678. /**
  24679. * This special version of a texture node can be used to
  24680. * write data into a storage texture with a compute shader.
  24681. *
  24682. * ```js
  24683. * const storageTexture = new THREE.StorageTexture( width, height );
  24684. *
  24685. * const computeTexture = Fn( ( { storageTexture } ) => {
  24686. *
  24687. * const posX = instanceIndex.mod( width );
  24688. * const posY = instanceIndex.div( width );
  24689. * const indexUV = uvec2( posX, posY );
  24690. *
  24691. * // generate RGB values
  24692. *
  24693. * const r = 1;
  24694. * const g = 1;
  24695. * const b = 1;
  24696. *
  24697. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  24698. *
  24699. * } );
  24700. *
  24701. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  24702. * renderer.computeAsync( computeNode );
  24703. * ```
  24704. *
  24705. * This node can only be used with a WebGPU backend.
  24706. *
  24707. * @augments TextureNode
  24708. */
  24709. class StorageTextureNode extends TextureNode {
  24710. static get type() {
  24711. return 'StorageTextureNode';
  24712. }
  24713. /**
  24714. * Constructs a new storage texture node.
  24715. *
  24716. * @param {StorageTexture} value - The storage texture.
  24717. * @param {Node<vec2|vec3>} uvNode - The uv node.
  24718. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24719. */
  24720. constructor( value, uvNode, storeNode = null ) {
  24721. super( value, uvNode );
  24722. /**
  24723. * The value node that should be stored in the texture.
  24724. *
  24725. * @type {?Node}
  24726. * @default null
  24727. */
  24728. this.storeNode = storeNode;
  24729. /**
  24730. * This flag can be used for type testing.
  24731. *
  24732. * @type {boolean}
  24733. * @readonly
  24734. * @default true
  24735. */
  24736. this.isStorageTextureNode = true;
  24737. /**
  24738. * The access type of the texture node.
  24739. *
  24740. * @type {string}
  24741. * @default 'writeOnly'
  24742. */
  24743. this.access = NodeAccess.WRITE_ONLY;
  24744. }
  24745. /**
  24746. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  24747. *
  24748. * @param {NodeBuilder} builder - The current node builder.
  24749. * @return {string} The input type.
  24750. */
  24751. getInputType( /*builder*/ ) {
  24752. return 'storageTexture';
  24753. }
  24754. setup( builder ) {
  24755. super.setup( builder );
  24756. const properties = builder.getNodeProperties( this );
  24757. properties.storeNode = this.storeNode;
  24758. return properties;
  24759. }
  24760. /**
  24761. * Defines the node access.
  24762. *
  24763. * @param {string} value - The node access.
  24764. * @return {StorageTextureNode} A reference to this node.
  24765. */
  24766. setAccess( value ) {
  24767. this.access = value;
  24768. return this;
  24769. }
  24770. /**
  24771. * Generates the code snippet of the storage node. If no `storeNode`
  24772. * is defined, the texture node is generated as normal texture.
  24773. *
  24774. * @param {NodeBuilder} builder - The current node builder.
  24775. * @param {string} output - The current output.
  24776. * @return {string} The generated code snippet.
  24777. */
  24778. generate( builder, output ) {
  24779. let snippet;
  24780. if ( this.storeNode !== null ) {
  24781. snippet = this.generateStore( builder );
  24782. } else {
  24783. snippet = super.generate( builder, output );
  24784. }
  24785. return snippet;
  24786. }
  24787. /**
  24788. * Convenience method for configuring a read/write node access.
  24789. *
  24790. * @return {StorageTextureNode} A reference to this node.
  24791. */
  24792. toReadWrite() {
  24793. return this.setAccess( NodeAccess.READ_WRITE );
  24794. }
  24795. /**
  24796. * Convenience method for configuring a read-only node access.
  24797. *
  24798. * @return {StorageTextureNode} A reference to this node.
  24799. */
  24800. toReadOnly() {
  24801. return this.setAccess( NodeAccess.READ_ONLY );
  24802. }
  24803. /**
  24804. * Convenience method for configuring a write-only node access.
  24805. *
  24806. * @return {StorageTextureNode} A reference to this node.
  24807. */
  24808. toWriteOnly() {
  24809. return this.setAccess( NodeAccess.WRITE_ONLY );
  24810. }
  24811. /**
  24812. * Generates the code snippet of the storage texture node.
  24813. *
  24814. * @param {NodeBuilder} builder - The current node builder.
  24815. */
  24816. generateStore( builder ) {
  24817. const properties = builder.getNodeProperties( this );
  24818. const { uvNode, storeNode, depthNode } = properties;
  24819. const textureProperty = super.generate( builder, 'property' );
  24820. const uvSnippet = uvNode.build( builder, this.value.is3DTexture === true ? 'uvec3' : 'uvec2' );
  24821. const storeSnippet = storeNode.build( builder, 'vec4' );
  24822. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  24823. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  24824. builder.addLineFlowCode( snippet, this );
  24825. }
  24826. clone() {
  24827. const newNode = super.clone();
  24828. newNode.storeNode = this.storeNode;
  24829. return newNode;
  24830. }
  24831. }
  24832. /**
  24833. * TSL function for creating a storage texture node.
  24834. *
  24835. * @tsl
  24836. * @function
  24837. * @param {StorageTexture} value - The storage texture.
  24838. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  24839. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24840. * @returns {StorageTextureNode}
  24841. */
  24842. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  24843. /**
  24844. * TODO: Explain difference to `storageTexture()`.
  24845. *
  24846. * @tsl
  24847. * @function
  24848. * @param {StorageTexture} value - The storage texture.
  24849. * @param {Node<vec2|vec3>} uvNode - The uv node.
  24850. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  24851. * @returns {StorageTextureNode}
  24852. */
  24853. const textureStore = ( value, uvNode, storeNode ) => {
  24854. const node = storageTexture( value, uvNode, storeNode );
  24855. if ( storeNode !== null ) node.toStack();
  24856. return node;
  24857. };
  24858. const normal = Fn( ( { texture, uv } ) => {
  24859. const epsilon = 0.0001;
  24860. const ret = vec3().toVar();
  24861. If( uv.x.lessThan( epsilon ), () => {
  24862. ret.assign( vec3( 1, 0, 0 ) );
  24863. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  24864. ret.assign( vec3( 0, 1, 0 ) );
  24865. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  24866. ret.assign( vec3( 0, 0, 1 ) );
  24867. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  24868. ret.assign( vec3( -1, 0, 0 ) );
  24869. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  24870. ret.assign( vec3( 0, -1, 0 ) );
  24871. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  24872. ret.assign( vec3( 0, 0, -1 ) );
  24873. } ).Else( () => {
  24874. const step = 0.01;
  24875. 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 );
  24876. 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 );
  24877. 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 );
  24878. ret.assign( vec3( x, y, z ) );
  24879. } );
  24880. return ret.normalize();
  24881. } );
  24882. /**
  24883. * This type of uniform node represents a 3D texture.
  24884. *
  24885. * @augments TextureNode
  24886. */
  24887. class Texture3DNode extends TextureNode {
  24888. static get type() {
  24889. return 'Texture3DNode';
  24890. }
  24891. /**
  24892. * Constructs a new 3D texture node.
  24893. *
  24894. * @param {Data3DTexture} value - The 3D texture.
  24895. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  24896. * @param {?Node<int>} [levelNode=null] - The level node.
  24897. */
  24898. constructor( value, uvNode = null, levelNode = null ) {
  24899. super( value, uvNode, levelNode );
  24900. /**
  24901. * This flag can be used for type testing.
  24902. *
  24903. * @type {boolean}
  24904. * @readonly
  24905. * @default true
  24906. */
  24907. this.isTexture3DNode = true;
  24908. }
  24909. /**
  24910. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  24911. *
  24912. * @param {NodeBuilder} builder - The current node builder.
  24913. * @return {string} The input type.
  24914. */
  24915. getInputType( /*builder*/ ) {
  24916. return 'texture3D';
  24917. }
  24918. /**
  24919. * Returns a default uv node which is in context of 3D textures a three-dimensional
  24920. * uv node.
  24921. *
  24922. * @return {Node<vec3>} The default uv node.
  24923. */
  24924. getDefaultUV() {
  24925. return vec3( 0.5, 0.5, 0.5 );
  24926. }
  24927. /**
  24928. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  24929. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  24930. *
  24931. * @param {boolean} value - The update toggle.
  24932. */
  24933. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  24934. /**
  24935. * Overwrites the default implementation to return the unmodified uv node.
  24936. *
  24937. * @param {NodeBuilder} builder - The current node builder.
  24938. * @param {Node} uvNode - The uv node to setup.
  24939. * @return {Node} The unmodified uv node.
  24940. */
  24941. setupUV( builder, uvNode ) {
  24942. const texture = this.value;
  24943. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  24944. if ( this.sampler ) {
  24945. uvNode = uvNode.flipY();
  24946. } else {
  24947. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  24948. }
  24949. }
  24950. return uvNode;
  24951. }
  24952. /**
  24953. * Generates the uv code snippet.
  24954. *
  24955. * @param {NodeBuilder} builder - The current node builder.
  24956. * @param {Node} uvNode - The uv node to generate code for.
  24957. * @return {string} The generated code snippet.
  24958. */
  24959. generateUV( builder, uvNode ) {
  24960. return uvNode.build( builder, 'vec3' );
  24961. }
  24962. /**
  24963. * Generates the offset code snippet.
  24964. *
  24965. * @param {NodeBuilder} builder - The current node builder.
  24966. * @param {Node} offsetNode - The offset node to generate code for.
  24967. * @return {string} The generated code snippet.
  24968. */
  24969. generateOffset( builder, offsetNode ) {
  24970. return offsetNode.build( builder, 'ivec3' );
  24971. }
  24972. /**
  24973. * TODO.
  24974. *
  24975. * @param {Node<vec3>} uvNode - The uv node .
  24976. * @return {Node<vec3>} TODO.
  24977. */
  24978. normal( uvNode ) {
  24979. return normal( { texture: this, uv: uvNode } );
  24980. }
  24981. }
  24982. /**
  24983. * TSL function for creating a 3D texture node.
  24984. *
  24985. * @tsl
  24986. * @function
  24987. * @param {Data3DTexture} value - The 3D texture.
  24988. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  24989. * @param {?Node<int>} [levelNode=null] - The level node.
  24990. * @returns {Texture3DNode}
  24991. */
  24992. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  24993. /**
  24994. * A special type of reference node that allows to link values in
  24995. * `userData` fields to node objects.
  24996. * ```js
  24997. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  24998. *
  24999. * const material = new THREE.SpriteNodeMaterial();
  25000. * material.rotationNode = userData( 'rotation', 'float' );
  25001. * ```
  25002. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  25003. * will automatically be updated when the `rotation` user data field changes.
  25004. *
  25005. * @augments ReferenceNode
  25006. */
  25007. class UserDataNode extends ReferenceNode {
  25008. static get type() {
  25009. return 'UserDataNode';
  25010. }
  25011. /**
  25012. * Constructs a new user data node.
  25013. *
  25014. * @param {string} property - The property name that should be referenced by the node.
  25015. * @param {string} inputType - The node data type of the reference.
  25016. * @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.
  25017. */
  25018. constructor( property, inputType, userData = null ) {
  25019. super( property, inputType, userData );
  25020. /**
  25021. * A reference to the `userData` object. If not provided, the `userData`
  25022. * property of the 3D object that uses the node material is evaluated.
  25023. *
  25024. * @type {?Object}
  25025. * @default null
  25026. */
  25027. this.userData = userData;
  25028. }
  25029. /**
  25030. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  25031. * `userData` field.
  25032. *
  25033. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  25034. * @return {Object} A reference to the `userData` field.
  25035. */
  25036. updateReference( state ) {
  25037. this.reference = this.userData !== null ? this.userData : state.object.userData;
  25038. return this.reference;
  25039. }
  25040. }
  25041. /**
  25042. * TSL function for creating a user data node.
  25043. *
  25044. * @tsl
  25045. * @function
  25046. * @param {string} name - The property name that should be referenced by the node.
  25047. * @param {string} inputType - The node data type of the reference.
  25048. * @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.
  25049. * @returns {UserDataNode}
  25050. */
  25051. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  25052. const _objectData = new WeakMap();
  25053. /**
  25054. * A node for representing motion or velocity vectors. Foundation
  25055. * for advanced post processing effects like motion blur or TRAA.
  25056. *
  25057. * The node keeps track of the model, view and projection matrices
  25058. * of the previous frame and uses them to compute offsets in NDC space.
  25059. * These offsets represent the final velocity.
  25060. *
  25061. * @augments TempNode
  25062. */
  25063. class VelocityNode extends TempNode {
  25064. static get type() {
  25065. return 'VelocityNode';
  25066. }
  25067. /**
  25068. * Constructs a new vertex color node.
  25069. */
  25070. constructor() {
  25071. super( 'vec2' );
  25072. /**
  25073. * The current projection matrix.
  25074. *
  25075. * @type {?Matrix4}
  25076. * @default null
  25077. */
  25078. this.projectionMatrix = null;
  25079. /**
  25080. * Overwritten since velocity nodes are updated per object.
  25081. *
  25082. * @type {string}
  25083. * @default 'object'
  25084. */
  25085. this.updateType = NodeUpdateType.OBJECT;
  25086. /**
  25087. * Overwritten since velocity nodes save data after the update.
  25088. *
  25089. * @type {string}
  25090. * @default 'object'
  25091. */
  25092. this.updateAfterType = NodeUpdateType.OBJECT;
  25093. /**
  25094. * Uniform node representing the previous model matrix in world space.
  25095. *
  25096. * @type {UniformNode<mat4>}
  25097. * @default null
  25098. */
  25099. this.previousModelWorldMatrix = uniform( new Matrix4() );
  25100. /**
  25101. * Uniform node representing the previous projection matrix.
  25102. *
  25103. * @type {UniformNode<mat4>}
  25104. * @default null
  25105. */
  25106. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  25107. /**
  25108. * Uniform node representing the previous view matrix.
  25109. *
  25110. * @type {UniformNode<mat4>}
  25111. * @default null
  25112. */
  25113. this.previousCameraViewMatrix = uniform( new Matrix4() );
  25114. }
  25115. /**
  25116. * Sets the given projection matrix.
  25117. *
  25118. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  25119. */
  25120. setProjectionMatrix( projectionMatrix ) {
  25121. this.projectionMatrix = projectionMatrix;
  25122. }
  25123. /**
  25124. * Updates velocity specific uniforms.
  25125. *
  25126. * @param {NodeFrame} frame - A reference to the current node frame.
  25127. */
  25128. update( { frameId, camera, object } ) {
  25129. const previousModelMatrix = getPreviousMatrix( object );
  25130. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  25131. //
  25132. const cameraData = getData( camera );
  25133. if ( cameraData.frameId !== frameId ) {
  25134. cameraData.frameId = frameId;
  25135. if ( cameraData.previousProjectionMatrix === undefined ) {
  25136. cameraData.previousProjectionMatrix = new Matrix4();
  25137. cameraData.previousCameraViewMatrix = new Matrix4();
  25138. cameraData.currentProjectionMatrix = new Matrix4();
  25139. cameraData.currentCameraViewMatrix = new Matrix4();
  25140. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  25141. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  25142. } else {
  25143. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  25144. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  25145. }
  25146. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  25147. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  25148. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  25149. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  25150. }
  25151. }
  25152. /**
  25153. * Overwritten to updated velocity specific uniforms.
  25154. *
  25155. * @param {NodeFrame} frame - A reference to the current node frame.
  25156. */
  25157. updateAfter( { object } ) {
  25158. getPreviousMatrix( object ).copy( object.matrixWorld );
  25159. }
  25160. /**
  25161. * Implements the velocity computation based on the previous and current vertex data.
  25162. *
  25163. * @param {NodeBuilder} builder - A reference to the current node builder.
  25164. * @return {Node<vec2>} The motion vector.
  25165. */
  25166. setup( /*builder*/ ) {
  25167. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  25168. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  25169. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  25170. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  25171. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  25172. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  25173. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  25174. return velocity;
  25175. }
  25176. }
  25177. function getData( object ) {
  25178. let objectData = _objectData.get( object );
  25179. if ( objectData === undefined ) {
  25180. objectData = {};
  25181. _objectData.set( object, objectData );
  25182. }
  25183. return objectData;
  25184. }
  25185. function getPreviousMatrix( object, index = 0 ) {
  25186. const objectData = getData( object );
  25187. let matrix = objectData[ index ];
  25188. if ( matrix === undefined ) {
  25189. objectData[ index ] = matrix = new Matrix4();
  25190. objectData[ index ].copy( object.matrixWorld );
  25191. }
  25192. return matrix;
  25193. }
  25194. /**
  25195. * TSL object that represents the velocity of a render pass.
  25196. *
  25197. * @tsl
  25198. * @type {VelocityNode}
  25199. */
  25200. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  25201. /**
  25202. * Computes a grayscale value for the given RGB color value.
  25203. *
  25204. * @tsl
  25205. * @function
  25206. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  25207. * @return {Node<vec3>} The grayscale color.
  25208. */
  25209. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  25210. return luminance( color.rgb );
  25211. } );
  25212. /**
  25213. * Super-saturates or desaturates the given RGB color.
  25214. *
  25215. * @tsl
  25216. * @function
  25217. * @param {Node<vec3>} color - The input color.
  25218. * @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.
  25219. * @return {Node<vec3>} The saturated color.
  25220. */
  25221. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25222. return adjustment.mix( luminance( color.rgb ), color.rgb );
  25223. } );
  25224. /**
  25225. * Selectively enhance the intensity of less saturated RGB colors. Can result
  25226. * in a more natural and visually appealing image with enhanced color depth
  25227. * compared to {@link ColorAdjustment#saturation}.
  25228. *
  25229. * @tsl
  25230. * @function
  25231. * @param {Node<vec3>} color - The input color.
  25232. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  25233. * @return {Node<vec3>} The updated color.
  25234. */
  25235. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25236. const average = add( color.r, color.g, color.b ).div( 3.0 );
  25237. const mx = color.r.max( color.g.max( color.b ) );
  25238. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  25239. return mix( color.rgb, mx, amt );
  25240. } );
  25241. /**
  25242. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  25243. *
  25244. * @tsl
  25245. * @function
  25246. * @param {Node<vec3>} color - The input color.
  25247. * @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.
  25248. * @return {Node<vec3>} The updated color.
  25249. */
  25250. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  25251. const k = vec3( 0.57735, 0.57735, 0.57735 );
  25252. const cosAngle = adjustment.cos();
  25253. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  25254. } );
  25255. /**
  25256. * Computes the luminance for the given RGB color value.
  25257. *
  25258. * @tsl
  25259. * @function
  25260. * @param {Node<vec3>} color - The color value to compute the luminance for.
  25261. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  25262. * @return {Node<vec3>} The luminance.
  25263. */
  25264. const luminance = (
  25265. color,
  25266. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  25267. ) => dot( color, luminanceCoefficients );
  25268. /**
  25269. * Color Decision List (CDL) v1.2
  25270. *
  25271. * Compact representation of color grading information, defined by slope, offset, power, and
  25272. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  25273. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  25274. *
  25275. * @tsl
  25276. * @function
  25277. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  25278. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  25279. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  25280. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  25281. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  25282. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  25283. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  25284. *
  25285. * References:
  25286. * - ASC CDL v1.2
  25287. * - {@link https://blender.stackexchange.com/a/55239/43930}
  25288. * - {@link https://docs.acescentral.com/specifications/acescc/}
  25289. */
  25290. const cdl = /*@__PURE__*/ Fn( ( [
  25291. color,
  25292. slope = vec3( 1 ),
  25293. offset = vec3( 0 ),
  25294. power = vec3( 1 ),
  25295. saturation = float( 1 ),
  25296. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  25297. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  25298. ] ) => {
  25299. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  25300. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  25301. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  25302. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  25303. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  25304. const pv = v.pow( power ).toVar();
  25305. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  25306. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  25307. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  25308. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  25309. return vec4( v.rgb, color.a );
  25310. } );
  25311. /**
  25312. * Represents a posterize effect which reduces the number of colors
  25313. * in an image, resulting in a more blocky and stylized appearance.
  25314. *
  25315. * @augments TempNode
  25316. */
  25317. class PosterizeNode extends TempNode {
  25318. static get type() {
  25319. return 'PosterizeNode';
  25320. }
  25321. /**
  25322. * Constructs a new posterize node.
  25323. *
  25324. * @param {Node} sourceNode - The input color.
  25325. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25326. */
  25327. constructor( sourceNode, stepsNode ) {
  25328. super();
  25329. /**
  25330. * The input color.
  25331. *
  25332. * @type {Node}
  25333. */
  25334. this.sourceNode = sourceNode;
  25335. /**
  25336. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25337. *
  25338. * @type {Node}
  25339. */
  25340. this.stepsNode = stepsNode;
  25341. }
  25342. setup() {
  25343. const { sourceNode, stepsNode } = this;
  25344. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  25345. }
  25346. }
  25347. /**
  25348. * TSL function for creating a posterize node.
  25349. *
  25350. * @tsl
  25351. * @function
  25352. * @param {Node} sourceNode - The input color.
  25353. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  25354. * @returns {PosterizeNode}
  25355. */
  25356. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  25357. const _size = /*@__PURE__*/ new Vector2();
  25358. /**
  25359. * Represents the texture of a pass node.
  25360. *
  25361. * @augments TextureNode
  25362. */
  25363. class PassTextureNode extends TextureNode {
  25364. static get type() {
  25365. return 'PassTextureNode';
  25366. }
  25367. /**
  25368. * Constructs a new pass texture node.
  25369. *
  25370. * @param {PassNode} passNode - The pass node.
  25371. * @param {Texture} texture - The output texture.
  25372. */
  25373. constructor( passNode, texture ) {
  25374. super( texture );
  25375. /**
  25376. * A reference to the pass node.
  25377. *
  25378. * @type {PassNode}
  25379. */
  25380. this.passNode = passNode;
  25381. this.setUpdateMatrix( false );
  25382. }
  25383. setup( builder ) {
  25384. this.passNode.build( builder );
  25385. return super.setup( builder );
  25386. }
  25387. clone() {
  25388. return new this.constructor( this.passNode, this.value );
  25389. }
  25390. }
  25391. /**
  25392. * An extension of `PassTextureNode` which allows to manage more than one
  25393. * internal texture. Relevant for the `getPreviousTexture()` related API.
  25394. *
  25395. * @augments PassTextureNode
  25396. */
  25397. class PassMultipleTextureNode extends PassTextureNode {
  25398. static get type() {
  25399. return 'PassMultipleTextureNode';
  25400. }
  25401. /**
  25402. * Constructs a new pass texture node.
  25403. *
  25404. * @param {PassNode} passNode - The pass node.
  25405. * @param {string} textureName - The output texture name.
  25406. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  25407. */
  25408. constructor( passNode, textureName, previousTexture = false ) {
  25409. // null is passed to the super call since this class does not
  25410. // use an external texture for rendering pass data into. Instead
  25411. // the texture is managed by the pass node itself
  25412. super( passNode, null );
  25413. /**
  25414. * The output texture name.
  25415. *
  25416. * @type {string}
  25417. */
  25418. this.textureName = textureName;
  25419. /**
  25420. * Whether previous frame data should be used or not.
  25421. *
  25422. * @type {boolean}
  25423. */
  25424. this.previousTexture = previousTexture;
  25425. }
  25426. /**
  25427. * Updates the texture reference of this node.
  25428. */
  25429. updateTexture() {
  25430. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  25431. }
  25432. setup( builder ) {
  25433. this.updateTexture();
  25434. return super.setup( builder );
  25435. }
  25436. clone() {
  25437. const newNode = new this.constructor( this.passNode, this.textureName, this.previousTexture );
  25438. newNode.uvNode = this.uvNode;
  25439. newNode.levelNode = this.levelNode;
  25440. newNode.biasNode = this.biasNode;
  25441. newNode.sampler = this.sampler;
  25442. newNode.depthNode = this.depthNode;
  25443. newNode.compareNode = this.compareNode;
  25444. newNode.gradNode = this.gradNode;
  25445. return newNode;
  25446. }
  25447. }
  25448. /**
  25449. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  25450. * This pass produces a render for the given scene and camera and can provide multiple outputs
  25451. * via MRT for further processing.
  25452. *
  25453. * ```js
  25454. * const postProcessing = new PostProcessing( renderer );
  25455. *
  25456. * const scenePass = pass( scene, camera );
  25457. *
  25458. * postProcessing.outputNode = scenePass;
  25459. * ```
  25460. *
  25461. * @augments TempNode
  25462. */
  25463. class PassNode extends TempNode {
  25464. static get type() {
  25465. return 'PassNode';
  25466. }
  25467. /**
  25468. * Constructs a new pass node.
  25469. *
  25470. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  25471. * @param {Scene} scene - A reference to the scene.
  25472. * @param {Camera} camera - A reference to the camera.
  25473. * @param {Object} options - Options for the internal render target.
  25474. */
  25475. constructor( scope, scene, camera, options = {} ) {
  25476. super( 'vec4' );
  25477. /**
  25478. * The scope of the pass. The scope determines whether the node outputs color or depth.
  25479. *
  25480. * @type {('color'|'depth')}
  25481. */
  25482. this.scope = scope;
  25483. /**
  25484. * A reference to the scene.
  25485. *
  25486. * @type {Scene}
  25487. */
  25488. this.scene = scene;
  25489. /**
  25490. * A reference to the camera.
  25491. *
  25492. * @type {Camera}
  25493. */
  25494. this.camera = camera;
  25495. /**
  25496. * Options for the internal render target.
  25497. *
  25498. * @type {Object}
  25499. */
  25500. this.options = options;
  25501. /**
  25502. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  25503. *
  25504. * @private
  25505. * @type {number}
  25506. * @default 1
  25507. */
  25508. this._pixelRatio = 1;
  25509. /**
  25510. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  25511. * @private
  25512. * @type {number}
  25513. * @default 1
  25514. */
  25515. this._width = 1;
  25516. /**
  25517. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  25518. * @private
  25519. * @type {number}
  25520. * @default 1
  25521. */
  25522. this._height = 1;
  25523. const depthTexture = new DepthTexture();
  25524. depthTexture.isRenderTargetTexture = true;
  25525. //depthTexture.type = FloatType;
  25526. depthTexture.name = 'depth';
  25527. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  25528. renderTarget.texture.name = 'output';
  25529. renderTarget.depthTexture = depthTexture;
  25530. /**
  25531. * The pass's render target.
  25532. *
  25533. * @type {RenderTarget}
  25534. */
  25535. this.renderTarget = renderTarget;
  25536. /**
  25537. * A dictionary holding the internal result textures.
  25538. *
  25539. * @private
  25540. * @type {Object<string, Texture>}
  25541. */
  25542. this._textures = {
  25543. output: renderTarget.texture,
  25544. depth: depthTexture
  25545. };
  25546. /**
  25547. * A dictionary holding the internal texture nodes.
  25548. *
  25549. * @private
  25550. * @type {Object<string, TextureNode>}
  25551. */
  25552. this._textureNodes = {};
  25553. /**
  25554. * A dictionary holding the internal depth nodes.
  25555. *
  25556. * @private
  25557. * @type {Object}
  25558. */
  25559. this._linearDepthNodes = {};
  25560. /**
  25561. * A dictionary holding the internal viewZ nodes.
  25562. *
  25563. * @private
  25564. * @type {Object}
  25565. */
  25566. this._viewZNodes = {};
  25567. /**
  25568. * A dictionary holding the texture data of the previous frame.
  25569. * Used for computing velocity/motion vectors.
  25570. *
  25571. * @private
  25572. * @type {Object<string, Texture>}
  25573. */
  25574. this._previousTextures = {};
  25575. /**
  25576. * A dictionary holding the texture nodes of the previous frame.
  25577. * Used for computing velocity/motion vectors.
  25578. *
  25579. * @private
  25580. * @type {Object<string, TextureNode>}
  25581. */
  25582. this._previousTextureNodes = {};
  25583. /**
  25584. * The `near` property of the camera as a uniform.
  25585. *
  25586. * @private
  25587. * @type {UniformNode}
  25588. */
  25589. this._cameraNear = uniform( 0 );
  25590. /**
  25591. * The `far` property of the camera as a uniform.
  25592. *
  25593. * @private
  25594. * @type {UniformNode}
  25595. */
  25596. this._cameraFar = uniform( 0 );
  25597. /**
  25598. * A MRT node configuring the MRT settings.
  25599. *
  25600. * @private
  25601. * @type {?MRTNode}
  25602. * @default null
  25603. */
  25604. this._mrt = null;
  25605. /**
  25606. * Layer object for configuring the camera that is used
  25607. * to produce the pass.
  25608. *
  25609. * @private
  25610. * @type {?Layers}
  25611. * @default null
  25612. */
  25613. this._layers = null;
  25614. /**
  25615. * Scales the resolution of the internal render target.
  25616. *
  25617. * @private
  25618. * @type {number}
  25619. * @default 1
  25620. */
  25621. this._resolution = 1;
  25622. /**
  25623. * Custom viewport definition.
  25624. *
  25625. * @private
  25626. * @type {?Vector4}
  25627. * @default null
  25628. */
  25629. this._viewport = null;
  25630. /**
  25631. * Custom scissor definition.
  25632. *
  25633. * @private
  25634. * @type {?Vector4}
  25635. * @default null
  25636. */
  25637. this._scissor = null;
  25638. /**
  25639. * This flag can be used for type testing.
  25640. *
  25641. * @type {boolean}
  25642. * @readonly
  25643. * @default true
  25644. */
  25645. this.isPassNode = true;
  25646. /**
  25647. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  25648. * scene once per frame in its {@link PassNode#updateBefore} method.
  25649. *
  25650. * @type {string}
  25651. * @default 'frame'
  25652. */
  25653. this.updateBeforeType = NodeUpdateType.FRAME;
  25654. /**
  25655. * This flag is used for global cache.
  25656. *
  25657. * @type {boolean}
  25658. * @default true
  25659. */
  25660. this.global = true;
  25661. }
  25662. /**
  25663. * Sets the resolution for the pass.
  25664. * The resolution is a factor that is multiplied with the renderer's width and height.
  25665. *
  25666. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  25667. * @return {PassNode} A reference to this pass.
  25668. */
  25669. setResolution( resolution ) {
  25670. this._resolution = resolution;
  25671. return this;
  25672. }
  25673. /**
  25674. * Gets the current resolution of the pass.
  25675. *
  25676. * @return {number} The current resolution. A value of `1` means full resolution.
  25677. */
  25678. getResolution() {
  25679. return this._resolution;
  25680. }
  25681. /**
  25682. * Sets the layer configuration that should be used when rendering the pass.
  25683. *
  25684. * @param {Layers} layers - The layers object to set.
  25685. * @return {PassNode} A reference to this pass.
  25686. */
  25687. setLayers( layers ) {
  25688. this._layers = layers;
  25689. return this;
  25690. }
  25691. /**
  25692. * Gets the current layer configuration of the pass.
  25693. *
  25694. * @return {?Layers} .
  25695. */
  25696. getLayers() {
  25697. return this._layers;
  25698. }
  25699. /**
  25700. * Sets the given MRT node to setup MRT for this pass.
  25701. *
  25702. * @param {MRTNode} mrt - The MRT object.
  25703. * @return {PassNode} A reference to this pass.
  25704. */
  25705. setMRT( mrt ) {
  25706. this._mrt = mrt;
  25707. return this;
  25708. }
  25709. /**
  25710. * Returns the current MRT node.
  25711. *
  25712. * @return {MRTNode} The current MRT node.
  25713. */
  25714. getMRT() {
  25715. return this._mrt;
  25716. }
  25717. /**
  25718. * Returns the texture for the given output name.
  25719. *
  25720. * @param {string} name - The output name to get the texture for.
  25721. * @return {Texture} The texture.
  25722. */
  25723. getTexture( name ) {
  25724. let texture = this._textures[ name ];
  25725. if ( texture === undefined ) {
  25726. const refTexture = this.renderTarget.texture;
  25727. texture = refTexture.clone();
  25728. texture.name = name;
  25729. this._textures[ name ] = texture;
  25730. this.renderTarget.textures.push( texture );
  25731. }
  25732. return texture;
  25733. }
  25734. /**
  25735. * Returns the texture holding the data of the previous frame for the given output name.
  25736. *
  25737. * @param {string} name - The output name to get the texture for.
  25738. * @return {Texture} The texture holding the data of the previous frame.
  25739. */
  25740. getPreviousTexture( name ) {
  25741. let texture = this._previousTextures[ name ];
  25742. if ( texture === undefined ) {
  25743. texture = this.getTexture( name ).clone();
  25744. this._previousTextures[ name ] = texture;
  25745. }
  25746. return texture;
  25747. }
  25748. /**
  25749. * Switches current and previous textures for the given output name.
  25750. *
  25751. * @param {string} name - The output name.
  25752. */
  25753. toggleTexture( name ) {
  25754. const prevTexture = this._previousTextures[ name ];
  25755. if ( prevTexture !== undefined ) {
  25756. const texture = this._textures[ name ];
  25757. const index = this.renderTarget.textures.indexOf( texture );
  25758. this.renderTarget.textures[ index ] = prevTexture;
  25759. this._textures[ name ] = prevTexture;
  25760. this._previousTextures[ name ] = texture;
  25761. this._textureNodes[ name ].updateTexture();
  25762. this._previousTextureNodes[ name ].updateTexture();
  25763. }
  25764. }
  25765. /**
  25766. * Returns the texture node for the given output name.
  25767. *
  25768. * @param {string} [name='output'] - The output name to get the texture node for.
  25769. * @return {TextureNode} The texture node.
  25770. */
  25771. getTextureNode( name = 'output' ) {
  25772. let textureNode = this._textureNodes[ name ];
  25773. if ( textureNode === undefined ) {
  25774. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  25775. textureNode.updateTexture();
  25776. this._textureNodes[ name ] = textureNode;
  25777. }
  25778. return textureNode;
  25779. }
  25780. /**
  25781. * Returns the previous texture node for the given output name.
  25782. *
  25783. * @param {string} [name='output'] - The output name to get the previous texture node for.
  25784. * @return {TextureNode} The previous texture node.
  25785. */
  25786. getPreviousTextureNode( name = 'output' ) {
  25787. let textureNode = this._previousTextureNodes[ name ];
  25788. if ( textureNode === undefined ) {
  25789. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  25790. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  25791. textureNode.updateTexture();
  25792. this._previousTextureNodes[ name ] = textureNode;
  25793. }
  25794. return textureNode;
  25795. }
  25796. /**
  25797. * Returns a viewZ node of this pass.
  25798. *
  25799. * @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.
  25800. * @return {Node} The viewZ node.
  25801. */
  25802. getViewZNode( name = 'depth' ) {
  25803. let viewZNode = this._viewZNodes[ name ];
  25804. if ( viewZNode === undefined ) {
  25805. const cameraNear = this._cameraNear;
  25806. const cameraFar = this._cameraFar;
  25807. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  25808. }
  25809. return viewZNode;
  25810. }
  25811. /**
  25812. * Returns a linear depth node of this pass.
  25813. *
  25814. * @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.
  25815. * @return {Node} The linear depth node.
  25816. */
  25817. getLinearDepthNode( name = 'depth' ) {
  25818. let linearDepthNode = this._linearDepthNodes[ name ];
  25819. if ( linearDepthNode === undefined ) {
  25820. const cameraNear = this._cameraNear;
  25821. const cameraFar = this._cameraFar;
  25822. const viewZNode = this.getViewZNode( name );
  25823. // TODO: just if ( builder.camera.isPerspectiveCamera )
  25824. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  25825. }
  25826. return linearDepthNode;
  25827. }
  25828. /**
  25829. * Precompiles the pass.
  25830. *
  25831. * Note that this method must be called after the pass configuration is complete.
  25832. * So calls like `setMRT()` and `getTextureNode()` must proceed the precompilation.
  25833. *
  25834. * @async
  25835. * @param {Renderer} renderer - The renderer.
  25836. * @return {Promise} A Promise that resolves when the compile has been finished.
  25837. * @see {@link Renderer#compileAsync}
  25838. */
  25839. async compileAsync( renderer ) {
  25840. const currentRenderTarget = renderer.getRenderTarget();
  25841. const currentMRT = renderer.getMRT();
  25842. renderer.setRenderTarget( this.renderTarget );
  25843. renderer.setMRT( this._mrt );
  25844. await renderer.compileAsync( this.scene, this.camera );
  25845. renderer.setRenderTarget( currentRenderTarget );
  25846. renderer.setMRT( currentMRT );
  25847. }
  25848. setup( { renderer } ) {
  25849. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  25850. this.renderTarget.texture.type = renderer.getColorBufferType();
  25851. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  25852. }
  25853. updateBefore( frame ) {
  25854. const { renderer } = frame;
  25855. const { scene } = this;
  25856. let camera;
  25857. let pixelRatio;
  25858. const outputRenderTarget = renderer.getOutputRenderTarget();
  25859. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  25860. pixelRatio = 1;
  25861. camera = renderer.xr.getCamera();
  25862. renderer.xr.updateCamera( camera );
  25863. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  25864. } else {
  25865. camera = this.camera;
  25866. pixelRatio = renderer.getPixelRatio();
  25867. renderer.getSize( _size );
  25868. }
  25869. this._pixelRatio = pixelRatio;
  25870. this.setSize( _size.width, _size.height );
  25871. const currentRenderTarget = renderer.getRenderTarget();
  25872. const currentMRT = renderer.getMRT();
  25873. const currentMask = camera.layers.mask;
  25874. this._cameraNear.value = camera.near;
  25875. this._cameraFar.value = camera.far;
  25876. if ( this._layers !== null ) {
  25877. camera.layers.mask = this._layers.mask;
  25878. }
  25879. for ( const name in this._previousTextures ) {
  25880. this.toggleTexture( name );
  25881. }
  25882. renderer.setRenderTarget( this.renderTarget );
  25883. renderer.setMRT( this._mrt );
  25884. renderer.render( scene, camera );
  25885. renderer.setRenderTarget( currentRenderTarget );
  25886. renderer.setMRT( currentMRT );
  25887. camera.layers.mask = currentMask;
  25888. }
  25889. /**
  25890. * Sets the size of the pass's render target. Honors the pixel ratio.
  25891. *
  25892. * @param {number} width - The width to set.
  25893. * @param {number} height - The height to set.
  25894. */
  25895. setSize( width, height ) {
  25896. this._width = width;
  25897. this._height = height;
  25898. const effectiveWidth = this._width * this._pixelRatio * this._resolution;
  25899. const effectiveHeight = this._height * this._pixelRatio * this._resolution;
  25900. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  25901. if ( this._scissor !== null ) this.renderTarget.scissor.copy( this._scissor );
  25902. if ( this._viewport !== null ) this.renderTarget.viewport.copy( this._viewport );
  25903. }
  25904. /**
  25905. * This method allows to define the pass's scissor rectangle. By default, the scissor rectangle is kept
  25906. * in sync with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  25907. * with `null` as the single argument.
  25908. *
  25909. * @param {?(number | Vector4)} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  25910. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  25911. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  25912. * @param {number} width - The width of the scissor box in logical pixel unit.
  25913. * @param {number} height - The height of the scissor box in logical pixel unit.
  25914. */
  25915. setScissor( x, y, width, height ) {
  25916. if ( x === null ) {
  25917. this._scissor = null;
  25918. } else {
  25919. if ( this._scissor === null ) this._scissor = new Vector4();
  25920. if ( x.isVector4 ) {
  25921. this._scissor.copy( x );
  25922. } else {
  25923. this._scissor.set( x, y, width, height );
  25924. }
  25925. this._scissor.multiplyScalar( this._pixelRatio * this._resolution ).floor();
  25926. }
  25927. }
  25928. /**
  25929. * This method allows to define the pass's viewport. By default, the viewport is kept in sync
  25930. * with the pass's dimensions. To reverse the process and use auto-sizing again, call the method
  25931. * with `null` as the single argument.
  25932. *
  25933. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  25934. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  25935. * @param {number} width - The width of the viewport in logical pixel unit.
  25936. * @param {number} height - The height of the viewport in logical pixel unit.
  25937. */
  25938. setViewport( x, y, width, height ) {
  25939. if ( x === null ) {
  25940. this._viewport = null;
  25941. } else {
  25942. if ( this._viewport === null ) this._viewport = new Vector4();
  25943. if ( x.isVector4 ) {
  25944. this._viewport.copy( x );
  25945. } else {
  25946. this._viewport.set( x, y, width, height );
  25947. }
  25948. this._viewport.multiplyScalar( this._pixelRatio * this._resolution ).floor();
  25949. }
  25950. }
  25951. /**
  25952. * Sets the pixel ratio the pass's render target and updates the size.
  25953. *
  25954. * @param {number} pixelRatio - The pixel ratio to set.
  25955. */
  25956. setPixelRatio( pixelRatio ) {
  25957. this._pixelRatio = pixelRatio;
  25958. this.setSize( this._width, this._height );
  25959. }
  25960. /**
  25961. * Frees internal resources. Should be called when the node is no longer in use.
  25962. */
  25963. dispose() {
  25964. this.renderTarget.dispose();
  25965. }
  25966. }
  25967. /**
  25968. * @static
  25969. * @type {'color'}
  25970. * @default 'color'
  25971. */
  25972. PassNode.COLOR = 'color';
  25973. /**
  25974. * @static
  25975. * @type {'depth'}
  25976. * @default 'depth'
  25977. */
  25978. PassNode.DEPTH = 'depth';
  25979. /**
  25980. * TSL function for creating a pass node.
  25981. *
  25982. * @tsl
  25983. * @function
  25984. * @param {Scene} scene - A reference to the scene.
  25985. * @param {Camera} camera - A reference to the camera.
  25986. * @param {Object} options - Options for the internal render target.
  25987. * @returns {PassNode}
  25988. */
  25989. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  25990. /**
  25991. * TSL function for creating a pass texture node.
  25992. *
  25993. * @tsl
  25994. * @function
  25995. * @param {PassNode} pass - The pass node.
  25996. * @param {Texture} texture - The output texture.
  25997. * @returns {PassTextureNode}
  25998. */
  25999. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  26000. /**
  26001. * TSL function for creating a depth pass node.
  26002. *
  26003. * @tsl
  26004. * @function
  26005. * @param {Scene} scene - A reference to the scene.
  26006. * @param {Camera} camera - A reference to the camera.
  26007. * @param {Object} options - Options for the internal render target.
  26008. * @returns {PassNode}
  26009. */
  26010. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  26011. /**
  26012. * Represents a render pass for producing a toon outline effect on compatible objects.
  26013. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  26014. * will receive the outline.
  26015. *
  26016. * ```js
  26017. * const postProcessing = new PostProcessing( renderer );
  26018. *
  26019. * const scenePass = toonOutlinePass( scene, camera );
  26020. *
  26021. * postProcessing.outputNode = scenePass;
  26022. * ```
  26023. * @augments PassNode
  26024. */
  26025. class ToonOutlinePassNode extends PassNode {
  26026. static get type() {
  26027. return 'ToonOutlinePassNode';
  26028. }
  26029. /**
  26030. * Constructs a new outline pass node.
  26031. *
  26032. * @param {Scene} scene - A reference to the scene.
  26033. * @param {Camera} camera - A reference to the camera.
  26034. * @param {Node} colorNode - Defines the outline's color.
  26035. * @param {Node} thicknessNode - Defines the outline's thickness.
  26036. * @param {Node} alphaNode - Defines the outline's alpha.
  26037. */
  26038. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  26039. super( PassNode.COLOR, scene, camera );
  26040. /**
  26041. * Defines the outline's color.
  26042. *
  26043. * @type {Node}
  26044. */
  26045. this.colorNode = colorNode;
  26046. /**
  26047. * Defines the outline's thickness.
  26048. *
  26049. * @type {Node}
  26050. */
  26051. this.thicknessNode = thicknessNode;
  26052. /**
  26053. * Defines the outline's alpha.
  26054. *
  26055. * @type {Node}
  26056. */
  26057. this.alphaNode = alphaNode;
  26058. /**
  26059. * An internal material cache.
  26060. *
  26061. * @private
  26062. * @type {WeakMap<Material, NodeMaterial>}
  26063. */
  26064. this._materialCache = new WeakMap();
  26065. }
  26066. updateBefore( frame ) {
  26067. const { renderer } = frame;
  26068. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  26069. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  26070. // only render outline for supported materials
  26071. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  26072. if ( material.wireframe === false ) {
  26073. const outlineMaterial = this._getOutlineMaterial( material );
  26074. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  26075. }
  26076. }
  26077. // default
  26078. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  26079. } );
  26080. super.updateBefore( frame );
  26081. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  26082. }
  26083. /**
  26084. * Creates the material used for outline rendering.
  26085. *
  26086. * @private
  26087. * @return {NodeMaterial} The outline material.
  26088. */
  26089. _createMaterial() {
  26090. const material = new NodeMaterial();
  26091. material.isMeshToonOutlineMaterial = true;
  26092. material.name = 'Toon_Outline';
  26093. material.side = BackSide;
  26094. // vertex node
  26095. const outlineNormal = normalLocal.negate();
  26096. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  26097. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  26098. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  26099. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  26100. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  26101. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  26102. // color node
  26103. material.colorNode = vec4( this.colorNode, this.alphaNode );
  26104. return material;
  26105. }
  26106. /**
  26107. * For the given toon material, this method returns a corresponding
  26108. * outline material.
  26109. *
  26110. * @private
  26111. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  26112. * @return {NodeMaterial} The outline material.
  26113. */
  26114. _getOutlineMaterial( originalMaterial ) {
  26115. let outlineMaterial = this._materialCache.get( originalMaterial );
  26116. if ( outlineMaterial === undefined ) {
  26117. outlineMaterial = this._createMaterial();
  26118. this._materialCache.set( originalMaterial, outlineMaterial );
  26119. }
  26120. return outlineMaterial;
  26121. }
  26122. }
  26123. /**
  26124. * TSL function for creating a toon outline pass node.
  26125. *
  26126. * @tsl
  26127. * @function
  26128. * @param {Scene} scene - A reference to the scene.
  26129. * @param {Camera} camera - A reference to the camera.
  26130. * @param {Color} color - Defines the outline's color.
  26131. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  26132. * @param {number} [alpha=1] - Defines the outline's alpha.
  26133. * @returns {ToonOutlinePassNode}
  26134. */
  26135. 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 ) ) );
  26136. /**
  26137. * Linear tone mapping, exposure only.
  26138. *
  26139. * @tsl
  26140. * @function
  26141. * @param {Node<vec3>} color - The color that should be tone mapped.
  26142. * @param {Node<float>} exposure - The exposure.
  26143. * @return {Node<vec3>} The tone mapped color.
  26144. */
  26145. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26146. return color.mul( exposure ).clamp();
  26147. } ).setLayout( {
  26148. name: 'linearToneMapping',
  26149. type: 'vec3',
  26150. inputs: [
  26151. { name: 'color', type: 'vec3' },
  26152. { name: 'exposure', type: 'float' }
  26153. ]
  26154. } );
  26155. /**
  26156. * Reinhard tone mapping.
  26157. *
  26158. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  26159. *
  26160. * @tsl
  26161. * @function
  26162. * @param {Node<vec3>} color - The color that should be tone mapped.
  26163. * @param {Node<float>} exposure - The exposure.
  26164. * @return {Node<vec3>} The tone mapped color.
  26165. */
  26166. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26167. color = color.mul( exposure );
  26168. return color.div( color.add( 1.0 ) ).clamp();
  26169. } ).setLayout( {
  26170. name: 'reinhardToneMapping',
  26171. type: 'vec3',
  26172. inputs: [
  26173. { name: 'color', type: 'vec3' },
  26174. { name: 'exposure', type: 'float' }
  26175. ]
  26176. } );
  26177. /**
  26178. * Cineon tone mapping.
  26179. *
  26180. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  26181. *
  26182. * @tsl
  26183. * @function
  26184. * @param {Node<vec3>} color - The color that should be tone mapped.
  26185. * @param {Node<float>} exposure - The exposure.
  26186. * @return {Node<vec3>} The tone mapped color.
  26187. */
  26188. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26189. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  26190. color = color.mul( exposure );
  26191. color = color.sub( 0.004 ).max( 0.0 );
  26192. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  26193. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  26194. return a.div( b ).pow( 2.2 );
  26195. } ).setLayout( {
  26196. name: 'cineonToneMapping',
  26197. type: 'vec3',
  26198. inputs: [
  26199. { name: 'color', type: 'vec3' },
  26200. { name: 'exposure', type: 'float' }
  26201. ]
  26202. } );
  26203. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  26204. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  26205. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  26206. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  26207. return a.div( b );
  26208. } );
  26209. /**
  26210. * ACESFilmic tone mapping.
  26211. *
  26212. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  26213. *
  26214. * @tsl
  26215. * @function
  26216. * @param {Node<vec3>} color - The color that should be tone mapped.
  26217. * @param {Node<float>} exposure - The exposure.
  26218. * @return {Node<vec3>} The tone mapped color.
  26219. */
  26220. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26221. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  26222. const ACESInputMat = mat3(
  26223. 0.59719, 0.35458, 0.04823,
  26224. 0.07600, 0.90834, 0.01566,
  26225. 0.02840, 0.13383, 0.83777
  26226. );
  26227. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  26228. const ACESOutputMat = mat3(
  26229. 1.60475, -0.53108, -0.07367,
  26230. -0.10208, 1.10813, -605e-5,
  26231. -327e-5, -0.07276, 1.07602
  26232. );
  26233. color = color.mul( exposure ).div( 0.6 );
  26234. color = ACESInputMat.mul( color );
  26235. // Apply RRT and ODT
  26236. color = RRTAndODTFit( color );
  26237. color = ACESOutputMat.mul( color );
  26238. // Clamp to [0, 1]
  26239. return color.clamp();
  26240. } ).setLayout( {
  26241. name: 'acesFilmicToneMapping',
  26242. type: 'vec3',
  26243. inputs: [
  26244. { name: 'color', type: 'vec3' },
  26245. { name: 'exposure', type: 'float' }
  26246. ]
  26247. } );
  26248. 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 ) );
  26249. 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 ) );
  26250. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  26251. const x = vec3( x_immutable ).toVar();
  26252. const x2 = vec3( x.mul( x ) ).toVar();
  26253. const x4 = vec3( x2.mul( x2 ) ).toVar();
  26254. 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 ) ) ) );
  26255. } );
  26256. /**
  26257. * AgX tone mapping.
  26258. *
  26259. * @tsl
  26260. * @function
  26261. * @param {Node<vec3>} color - The color that should be tone mapped.
  26262. * @param {Node<float>} exposure - The exposure.
  26263. * @return {Node<vec3>} The tone mapped color.
  26264. */
  26265. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26266. const colortone = vec3( color ).toVar();
  26267. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  26268. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  26269. const AgxMinEv = float( -12.47393 );
  26270. const AgxMaxEv = float( 4.026069 );
  26271. colortone.mulAssign( exposure );
  26272. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  26273. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  26274. colortone.assign( max$1( colortone, 1e-10 ) );
  26275. colortone.assign( log2( colortone ) );
  26276. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  26277. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  26278. colortone.assign( agxDefaultContrastApprox( colortone ) );
  26279. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  26280. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  26281. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  26282. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  26283. return colortone;
  26284. } ).setLayout( {
  26285. name: 'agxToneMapping',
  26286. type: 'vec3',
  26287. inputs: [
  26288. { name: 'color', type: 'vec3' },
  26289. { name: 'exposure', type: 'float' }
  26290. ]
  26291. } );
  26292. /**
  26293. * Neutral tone mapping.
  26294. *
  26295. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  26296. *
  26297. * @tsl
  26298. * @function
  26299. * @param {Node<vec3>} color - The color that should be tone mapped.
  26300. * @param {Node<float>} exposure - The exposure.
  26301. * @return {Node<vec3>} The tone mapped color.
  26302. */
  26303. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  26304. const StartCompression = float( 0.8 - 0.04 );
  26305. const Desaturation = float( 0.15 );
  26306. color = color.mul( exposure );
  26307. const x = min$1( color.r, min$1( color.g, color.b ) );
  26308. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  26309. color.subAssign( offset );
  26310. const peak = max$1( color.r, max$1( color.g, color.b ) );
  26311. If( peak.lessThan( StartCompression ), () => {
  26312. return color;
  26313. } );
  26314. const d = sub( 1, StartCompression );
  26315. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  26316. color.mulAssign( newPeak.div( peak ) );
  26317. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  26318. return mix( color, vec3( newPeak ), g );
  26319. } ).setLayout( {
  26320. name: 'neutralToneMapping',
  26321. type: 'vec3',
  26322. inputs: [
  26323. { name: 'color', type: 'vec3' },
  26324. { name: 'exposure', type: 'float' }
  26325. ]
  26326. } );
  26327. /**
  26328. * This class represents native code sections. It is the base
  26329. * class for modules like {@link FunctionNode} which allows to implement
  26330. * functions with native shader languages.
  26331. *
  26332. * @augments Node
  26333. */
  26334. class CodeNode extends Node {
  26335. static get type() {
  26336. return 'CodeNode';
  26337. }
  26338. /**
  26339. * Constructs a new code node.
  26340. *
  26341. * @param {string} [code=''] - The native code.
  26342. * @param {Array<Node>} [includes=[]] - An array of includes.
  26343. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26344. */
  26345. constructor( code = '', includes = [], language = '' ) {
  26346. super( 'code' );
  26347. /**
  26348. * This flag can be used for type testing.
  26349. *
  26350. * @type {boolean}
  26351. * @readonly
  26352. * @default true
  26353. */
  26354. this.isCodeNode = true;
  26355. /**
  26356. * This flag is used for global cache.
  26357. *
  26358. * @type {boolean}
  26359. * @default true
  26360. */
  26361. this.global = true;
  26362. /**
  26363. * The native code.
  26364. *
  26365. * @type {string}
  26366. * @default ''
  26367. */
  26368. this.code = code;
  26369. /**
  26370. * An array of includes
  26371. *
  26372. * @type {Array<Node>}
  26373. * @default []
  26374. */
  26375. this.includes = includes;
  26376. /**
  26377. * The used language.
  26378. *
  26379. * @type {('js'|'wgsl'|'glsl')}
  26380. * @default ''
  26381. */
  26382. this.language = language;
  26383. }
  26384. /**
  26385. * Sets the includes of this code node.
  26386. *
  26387. * @param {Array<Node>} includes - The includes to set.
  26388. * @return {CodeNode} A reference to this node.
  26389. */
  26390. setIncludes( includes ) {
  26391. this.includes = includes;
  26392. return this;
  26393. }
  26394. /**
  26395. * Returns the includes of this code node.
  26396. *
  26397. * @param {NodeBuilder} builder - The current node builder.
  26398. * @return {Array<Node>} The includes.
  26399. */
  26400. getIncludes( /*builder*/ ) {
  26401. return this.includes;
  26402. }
  26403. generate( builder ) {
  26404. const includes = this.getIncludes( builder );
  26405. for ( const include of includes ) {
  26406. include.build( builder );
  26407. }
  26408. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  26409. nodeCode.code = this.code;
  26410. return nodeCode.code;
  26411. }
  26412. serialize( data ) {
  26413. super.serialize( data );
  26414. data.code = this.code;
  26415. data.language = this.language;
  26416. }
  26417. deserialize( data ) {
  26418. super.deserialize( data );
  26419. this.code = data.code;
  26420. this.language = data.language;
  26421. }
  26422. }
  26423. /**
  26424. * TSL function for creating a code node.
  26425. *
  26426. * @tsl
  26427. * @function
  26428. * @param {string} [code] - The native code.
  26429. * @param {?Array<Node>} [includes=[]] - An array of includes.
  26430. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26431. * @returns {CodeNode}
  26432. */
  26433. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  26434. /**
  26435. * TSL function for creating a JS code node.
  26436. *
  26437. * @tsl
  26438. * @function
  26439. * @param {string} src - The native code.
  26440. * @param {Array<Node>} includes - An array of includes.
  26441. * @returns {CodeNode}
  26442. */
  26443. const js = ( src, includes ) => code( src, includes, 'js' );
  26444. /**
  26445. * TSL function for creating a WGSL code node.
  26446. *
  26447. * @tsl
  26448. * @function
  26449. * @param {string} src - The native code.
  26450. * @param {Array<Node>} includes - An array of includes.
  26451. * @returns {CodeNode}
  26452. */
  26453. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  26454. /**
  26455. * TSL function for creating a GLSL code node.
  26456. *
  26457. * @tsl
  26458. * @function
  26459. * @param {string} src - The native code.
  26460. * @param {Array<Node>} includes - An array of includes.
  26461. * @returns {CodeNode}
  26462. */
  26463. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  26464. /**
  26465. * This class represents a native shader function. It can be used to implement
  26466. * certain aspects of a node material with native shader code. There are two predefined
  26467. * TSL functions for easier usage.
  26468. *
  26469. * - `wgslFn`: Creates a WGSL function node.
  26470. * - `glslFn`: Creates a GLSL function node.
  26471. *
  26472. * A basic example with one include looks like so:
  26473. *
  26474. * ```js
  26475. * const desaturateWGSLFn = wgslFn( `
  26476. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  26477. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  26478. * return vec3<f32>( dot( lum, color ) );
  26479. * }`
  26480. *);
  26481. * const someWGSLFn = wgslFn( `
  26482. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  26483. * return desaturate( color );
  26484. * }
  26485. * `, [ desaturateWGSLFn ] );
  26486. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  26487. *```
  26488. * @augments CodeNode
  26489. */
  26490. class FunctionNode extends CodeNode {
  26491. static get type() {
  26492. return 'FunctionNode';
  26493. }
  26494. /**
  26495. * Constructs a new function node.
  26496. *
  26497. * @param {string} [code=''] - The native code.
  26498. * @param {Array<Node>} [includes=[]] - An array of includes.
  26499. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  26500. */
  26501. constructor( code = '', includes = [], language = '' ) {
  26502. super( code, includes, language );
  26503. }
  26504. /**
  26505. * Returns the type of this function node.
  26506. *
  26507. * @param {NodeBuilder} builder - The current node builder.
  26508. * @return {string} The type.
  26509. */
  26510. getNodeType( builder ) {
  26511. return this.getNodeFunction( builder ).type;
  26512. }
  26513. /**
  26514. * Returns the type of a member of this function node.
  26515. *
  26516. * @param {NodeBuilder} builder - The current node builder.
  26517. * @param {string} name - The name of the member.
  26518. * @return {string} The type of the member.
  26519. */
  26520. getMemberType( builder, name ) {
  26521. const type = this.getNodeType( builder );
  26522. const structType = builder.getStructTypeNode( type );
  26523. return structType.getMemberType( builder, name );
  26524. }
  26525. /**
  26526. * Returns the inputs of this function node.
  26527. *
  26528. * @param {NodeBuilder} builder - The current node builder.
  26529. * @return {Array<NodeFunctionInput>} The inputs.
  26530. */
  26531. getInputs( builder ) {
  26532. return this.getNodeFunction( builder ).inputs;
  26533. }
  26534. /**
  26535. * Returns the node function for this function node.
  26536. *
  26537. * @param {NodeBuilder} builder - The current node builder.
  26538. * @return {NodeFunction} The node function.
  26539. */
  26540. getNodeFunction( builder ) {
  26541. const nodeData = builder.getDataFromNode( this );
  26542. let nodeFunction = nodeData.nodeFunction;
  26543. if ( nodeFunction === undefined ) {
  26544. nodeFunction = builder.parser.parseFunction( this.code );
  26545. nodeData.nodeFunction = nodeFunction;
  26546. }
  26547. return nodeFunction;
  26548. }
  26549. generate( builder, output ) {
  26550. super.generate( builder );
  26551. const nodeFunction = this.getNodeFunction( builder );
  26552. const name = nodeFunction.name;
  26553. const type = nodeFunction.type;
  26554. const nodeCode = builder.getCodeFromNode( this, type );
  26555. if ( name !== '' ) {
  26556. // use a custom property name
  26557. nodeCode.name = name;
  26558. }
  26559. const propertyName = builder.getPropertyName( nodeCode );
  26560. const code = this.getNodeFunction( builder ).getCode( propertyName );
  26561. nodeCode.code = code + '\n';
  26562. if ( output === 'property' ) {
  26563. return propertyName;
  26564. } else {
  26565. return builder.format( `${ propertyName }()`, type, output );
  26566. }
  26567. }
  26568. }
  26569. const nativeFn = ( code, includes = [], language = '' ) => {
  26570. for ( let i = 0; i < includes.length; i ++ ) {
  26571. const include = includes[ i ];
  26572. // TSL Function: glslFn, wgslFn
  26573. if ( typeof include === 'function' ) {
  26574. includes[ i ] = include.functionNode;
  26575. }
  26576. }
  26577. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  26578. const fn = ( ...params ) => functionNode.call( ...params );
  26579. fn.functionNode = functionNode;
  26580. return fn;
  26581. };
  26582. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  26583. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  26584. /**
  26585. * `ScriptableNode` uses this class to manage script inputs and outputs.
  26586. *
  26587. * @augments Node
  26588. */
  26589. class ScriptableValueNode extends Node {
  26590. static get type() {
  26591. return 'ScriptableValueNode';
  26592. }
  26593. /**
  26594. * Constructs a new scriptable node.
  26595. *
  26596. * @param {any} [value=null] - The value.
  26597. */
  26598. constructor( value = null ) {
  26599. super();
  26600. /**
  26601. * A reference to the value.
  26602. *
  26603. * @private
  26604. * @default null
  26605. */
  26606. this._value = value;
  26607. /**
  26608. * Depending on the type of `_value`, this property might cache parsed data.
  26609. *
  26610. * @private
  26611. * @default null
  26612. */
  26613. this._cache = null;
  26614. /**
  26615. * If this node represents an input, this property represents the input type.
  26616. *
  26617. * @type {?string}
  26618. * @default null
  26619. */
  26620. this.inputType = null;
  26621. /**
  26622. * If this node represents an output, this property represents the output type.
  26623. *
  26624. * @type {?string}
  26625. * @default null
  26626. */
  26627. this.outputType = null;
  26628. /**
  26629. * An event dispatcher for managing events.
  26630. *
  26631. * @type {EventDispatcher}
  26632. */
  26633. this.events = new EventDispatcher();
  26634. /**
  26635. * This flag can be used for type testing.
  26636. *
  26637. * @type {boolean}
  26638. * @readonly
  26639. * @default true
  26640. */
  26641. this.isScriptableValueNode = true;
  26642. }
  26643. /**
  26644. * Whether this node represents an output or not.
  26645. *
  26646. * @type {boolean}
  26647. * @readonly
  26648. * @default true
  26649. */
  26650. get isScriptableOutputNode() {
  26651. return this.outputType !== null;
  26652. }
  26653. set value( val ) {
  26654. if ( this._value === val ) return;
  26655. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  26656. URL.revokeObjectURL( this._cache );
  26657. this._cache = null;
  26658. }
  26659. this._value = val;
  26660. this.events.dispatchEvent( { type: 'change' } );
  26661. this.refresh();
  26662. }
  26663. /**
  26664. * The node's value.
  26665. *
  26666. * @type {any}
  26667. */
  26668. get value() {
  26669. return this._value;
  26670. }
  26671. /**
  26672. * Dispatches the `refresh` event.
  26673. */
  26674. refresh() {
  26675. this.events.dispatchEvent( { type: 'refresh' } );
  26676. }
  26677. /**
  26678. * The `value` property usually represents a node or even binary data in form of array buffers.
  26679. * In this case, this method tries to return the actual value behind the complex type.
  26680. *
  26681. * @return {any} The value.
  26682. */
  26683. getValue() {
  26684. const value = this.value;
  26685. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  26686. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  26687. } else if ( value && value.value !== null && value.value !== undefined && (
  26688. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  26689. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  26690. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  26691. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  26692. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  26693. ( this.inputType === 'Color' && value.value.isColor ) ||
  26694. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  26695. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  26696. ) ) {
  26697. return value.value;
  26698. }
  26699. return this._cache || value;
  26700. }
  26701. /**
  26702. * Overwritten since the node type is inferred from the value.
  26703. *
  26704. * @param {NodeBuilder} builder - The current node builder.
  26705. * @return {string} The node type.
  26706. */
  26707. getNodeType( builder ) {
  26708. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  26709. }
  26710. setup() {
  26711. return this.value && this.value.isNode ? this.value : float();
  26712. }
  26713. serialize( data ) {
  26714. super.serialize( data );
  26715. if ( this.value !== null ) {
  26716. if ( this.inputType === 'ArrayBuffer' ) {
  26717. data.value = arrayBufferToBase64( this.value );
  26718. } else {
  26719. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  26720. }
  26721. } else {
  26722. data.value = null;
  26723. }
  26724. data.inputType = this.inputType;
  26725. data.outputType = this.outputType;
  26726. }
  26727. deserialize( data ) {
  26728. super.deserialize( data );
  26729. let value = null;
  26730. if ( data.value !== null ) {
  26731. if ( data.inputType === 'ArrayBuffer' ) {
  26732. value = base64ToArrayBuffer( data.value );
  26733. } else if ( data.inputType === 'Texture' ) {
  26734. value = data.meta.textures[ data.value ];
  26735. } else {
  26736. value = data.meta.nodes[ data.value ] || null;
  26737. }
  26738. }
  26739. this.value = value;
  26740. this.inputType = data.inputType;
  26741. this.outputType = data.outputType;
  26742. }
  26743. }
  26744. /**
  26745. * TSL function for creating a scriptable value node.
  26746. *
  26747. * @tsl
  26748. * @function
  26749. * @param {any} [value] - The value.
  26750. * @returns {ScriptableValueNode}
  26751. */
  26752. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  26753. /**
  26754. * A Map-like data structure for managing resources of scriptable nodes.
  26755. *
  26756. * @augments Map
  26757. */
  26758. class Resources extends Map {
  26759. get( key, callback = null, ...params ) {
  26760. if ( this.has( key ) ) return super.get( key );
  26761. if ( callback !== null ) {
  26762. const value = callback( ...params );
  26763. this.set( key, value );
  26764. return value;
  26765. }
  26766. }
  26767. }
  26768. class Parameters {
  26769. constructor( scriptableNode ) {
  26770. this.scriptableNode = scriptableNode;
  26771. }
  26772. get parameters() {
  26773. return this.scriptableNode.parameters;
  26774. }
  26775. get layout() {
  26776. return this.scriptableNode.getLayout();
  26777. }
  26778. getInputLayout( id ) {
  26779. return this.scriptableNode.getInputLayout( id );
  26780. }
  26781. get( name ) {
  26782. const param = this.parameters[ name ];
  26783. const value = param ? param.getValue() : null;
  26784. return value;
  26785. }
  26786. }
  26787. /**
  26788. * Defines the resources (e.g. namespaces) of scriptable nodes.
  26789. *
  26790. * @type {Resources}
  26791. */
  26792. const ScriptableNodeResources = new Resources();
  26793. /**
  26794. * This type of node allows to implement nodes with custom scripts. The script
  26795. * section is represented as an instance of `CodeNode` written with JavaScript.
  26796. * The script itself must adhere to a specific structure.
  26797. *
  26798. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  26799. * - layout: The layout object defines the script's interface (inputs and outputs).
  26800. *
  26801. * ```js
  26802. * ScriptableNodeResources.set( 'TSL', TSL );
  26803. *
  26804. * const scriptableNode = scriptable( js( `
  26805. * layout = {
  26806. * outputType: 'node',
  26807. * elements: [
  26808. * { name: 'source', inputType: 'node' },
  26809. * ]
  26810. * };
  26811. *
  26812. * const { mul, oscSine } = TSL;
  26813. *
  26814. * function main() {
  26815. * const source = parameters.get( 'source' ) || float();
  26816. * return mul( source, oscSine() ) );
  26817. * }
  26818. *
  26819. * ` ) );
  26820. *
  26821. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  26822. *
  26823. * const material = new THREE.MeshBasicNodeMaterial();
  26824. * material.colorNode = scriptableNode;
  26825. * ```
  26826. *
  26827. * @augments Node
  26828. */
  26829. class ScriptableNode extends Node {
  26830. static get type() {
  26831. return 'ScriptableNode';
  26832. }
  26833. /**
  26834. * Constructs a new scriptable node.
  26835. *
  26836. * @param {?CodeNode} [codeNode=null] - The code node.
  26837. * @param {Object} [parameters={}] - The parameters definition.
  26838. */
  26839. constructor( codeNode = null, parameters = {} ) {
  26840. super();
  26841. /**
  26842. * The code node.
  26843. *
  26844. * @type {?CodeNode}
  26845. * @default null
  26846. */
  26847. this.codeNode = codeNode;
  26848. /**
  26849. * The parameters definition.
  26850. *
  26851. * @type {Object}
  26852. * @default {}
  26853. */
  26854. this.parameters = parameters;
  26855. this._local = new Resources();
  26856. this._output = scriptableValue( null );
  26857. this._outputs = {};
  26858. this._source = this.source;
  26859. this._method = null;
  26860. this._object = null;
  26861. this._value = null;
  26862. this._needsOutputUpdate = true;
  26863. this.onRefresh = this.onRefresh.bind( this );
  26864. /**
  26865. * This flag can be used for type testing.
  26866. *
  26867. * @type {boolean}
  26868. * @readonly
  26869. * @default true
  26870. */
  26871. this.isScriptableNode = true;
  26872. }
  26873. /**
  26874. * The source code of the scriptable node.
  26875. *
  26876. * @type {string}
  26877. */
  26878. get source() {
  26879. return this.codeNode ? this.codeNode.code : '';
  26880. }
  26881. /**
  26882. * Sets the reference of a local script variable.
  26883. *
  26884. * @param {string} name - The variable name.
  26885. * @param {Object} value - The reference to set.
  26886. * @return {Resources} The resource map
  26887. */
  26888. setLocal( name, value ) {
  26889. return this._local.set( name, value );
  26890. }
  26891. /**
  26892. * Gets the value of a local script variable.
  26893. *
  26894. * @param {string} name - The variable name.
  26895. * @return {Object} The value.
  26896. */
  26897. getLocal( name ) {
  26898. return this._local.get( name );
  26899. }
  26900. /**
  26901. * Event listener for the `refresh` event.
  26902. */
  26903. onRefresh() {
  26904. this._refresh();
  26905. }
  26906. /**
  26907. * Returns an input from the layout with the given id/name.
  26908. *
  26909. * @param {string} id - The id/name of the input.
  26910. * @return {Object} The element entry.
  26911. */
  26912. getInputLayout( id ) {
  26913. for ( const element of this.getLayout() ) {
  26914. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  26915. return element;
  26916. }
  26917. }
  26918. }
  26919. /**
  26920. * Returns an output from the layout with the given id/name.
  26921. *
  26922. * @param {string} id - The id/name of the output.
  26923. * @return {Object} The element entry.
  26924. */
  26925. getOutputLayout( id ) {
  26926. for ( const element of this.getLayout() ) {
  26927. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  26928. return element;
  26929. }
  26930. }
  26931. }
  26932. /**
  26933. * Defines a script output for the given name and value.
  26934. *
  26935. * @param {string} name - The name of the output.
  26936. * @param {Node} value - The node value.
  26937. * @return {ScriptableNode} A reference to this node.
  26938. */
  26939. setOutput( name, value ) {
  26940. const outputs = this._outputs;
  26941. if ( outputs[ name ] === undefined ) {
  26942. outputs[ name ] = scriptableValue( value );
  26943. } else {
  26944. outputs[ name ].value = value;
  26945. }
  26946. return this;
  26947. }
  26948. /**
  26949. * Returns a script output for the given name.
  26950. *
  26951. * @param {string} name - The name of the output.
  26952. * @return {ScriptableValueNode} The node value.
  26953. */
  26954. getOutput( name ) {
  26955. return this._outputs[ name ];
  26956. }
  26957. /**
  26958. * Returns a parameter for the given name
  26959. *
  26960. * @param {string} name - The name of the parameter.
  26961. * @return {ScriptableValueNode} The node value.
  26962. */
  26963. getParameter( name ) {
  26964. return this.parameters[ name ];
  26965. }
  26966. /**
  26967. * Sets a value for the given parameter name.
  26968. *
  26969. * @param {string} name - The parameter name.
  26970. * @param {any} value - The parameter value.
  26971. * @return {ScriptableNode} A reference to this node.
  26972. */
  26973. setParameter( name, value ) {
  26974. const parameters = this.parameters;
  26975. if ( value && value.isScriptableNode ) {
  26976. this.deleteParameter( name );
  26977. parameters[ name ] = value;
  26978. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  26979. } else if ( value && value.isScriptableValueNode ) {
  26980. this.deleteParameter( name );
  26981. parameters[ name ] = value;
  26982. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  26983. } else if ( parameters[ name ] === undefined ) {
  26984. parameters[ name ] = scriptableValue( value );
  26985. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  26986. } else {
  26987. parameters[ name ].value = value;
  26988. }
  26989. return this;
  26990. }
  26991. /**
  26992. * Returns the value of this node which is the value of
  26993. * the default output.
  26994. *
  26995. * @return {Node} The value.
  26996. */
  26997. getValue() {
  26998. return this.getDefaultOutput().getValue();
  26999. }
  27000. /**
  27001. * Deletes a parameter from the script.
  27002. *
  27003. * @param {string} name - The parameter to remove.
  27004. * @return {ScriptableNode} A reference to this node.
  27005. */
  27006. deleteParameter( name ) {
  27007. let valueNode = this.parameters[ name ];
  27008. if ( valueNode ) {
  27009. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  27010. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  27011. }
  27012. return this;
  27013. }
  27014. /**
  27015. * Deletes all parameters from the script.
  27016. *
  27017. * @return {ScriptableNode} A reference to this node.
  27018. */
  27019. clearParameters() {
  27020. for ( const name of Object.keys( this.parameters ) ) {
  27021. this.deleteParameter( name );
  27022. }
  27023. this.needsUpdate = true;
  27024. return this;
  27025. }
  27026. /**
  27027. * Calls a function from the script.
  27028. *
  27029. * @param {string} name - The function name.
  27030. * @param {...any} params - A list of parameters.
  27031. * @return {any} The result of the function call.
  27032. */
  27033. call( name, ...params ) {
  27034. const object = this.getObject();
  27035. const method = object[ name ];
  27036. if ( typeof method === 'function' ) {
  27037. return method( ...params );
  27038. }
  27039. }
  27040. /**
  27041. * Asynchronously calls a function from the script.
  27042. *
  27043. * @param {string} name - The function name.
  27044. * @param {...any} params - A list of parameters.
  27045. * @return {Promise<any>} The result of the function call.
  27046. */
  27047. async callAsync( name, ...params ) {
  27048. const object = this.getObject();
  27049. const method = object[ name ];
  27050. if ( typeof method === 'function' ) {
  27051. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  27052. }
  27053. }
  27054. /**
  27055. * Overwritten since the node types is inferred from the script's output.
  27056. *
  27057. * @param {NodeBuilder} builder - The current node builder
  27058. * @return {string} The node type.
  27059. */
  27060. getNodeType( builder ) {
  27061. return this.getDefaultOutputNode().getNodeType( builder );
  27062. }
  27063. /**
  27064. * Refreshes the script node.
  27065. *
  27066. * @param {?string} [output=null] - An optional output.
  27067. */
  27068. refresh( output = null ) {
  27069. if ( output !== null ) {
  27070. this.getOutput( output ).refresh();
  27071. } else {
  27072. this._refresh();
  27073. }
  27074. }
  27075. /**
  27076. * Returns an object representation of the script.
  27077. *
  27078. * @return {Object} The result object.
  27079. */
  27080. getObject() {
  27081. if ( this.needsUpdate ) this.dispose();
  27082. if ( this._object !== null ) return this._object;
  27083. //
  27084. const refresh = () => this.refresh();
  27085. const setOutput = ( id, value ) => this.setOutput( id, value );
  27086. const parameters = new Parameters( this );
  27087. const THREE = ScriptableNodeResources.get( 'THREE' );
  27088. const TSL = ScriptableNodeResources.get( 'TSL' );
  27089. const method = this.getMethod();
  27090. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  27091. this._object = method( ...params );
  27092. const layout = this._object.layout;
  27093. if ( layout ) {
  27094. if ( layout.cache === false ) {
  27095. this._local.clear();
  27096. }
  27097. // default output
  27098. this._output.outputType = layout.outputType || null;
  27099. if ( Array.isArray( layout.elements ) ) {
  27100. for ( const element of layout.elements ) {
  27101. const id = element.id || element.name;
  27102. if ( element.inputType ) {
  27103. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  27104. this.getParameter( id ).inputType = element.inputType;
  27105. }
  27106. if ( element.outputType ) {
  27107. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  27108. this.getOutput( id ).outputType = element.outputType;
  27109. }
  27110. }
  27111. }
  27112. }
  27113. return this._object;
  27114. }
  27115. deserialize( data ) {
  27116. super.deserialize( data );
  27117. for ( const name in this.parameters ) {
  27118. let valueNode = this.parameters[ name ];
  27119. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  27120. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  27121. }
  27122. }
  27123. /**
  27124. * Returns the layout of the script.
  27125. *
  27126. * @return {Object} The script's layout.
  27127. */
  27128. getLayout() {
  27129. return this.getObject().layout;
  27130. }
  27131. /**
  27132. * Returns default node output of the script.
  27133. *
  27134. * @return {Node} The default node output.
  27135. */
  27136. getDefaultOutputNode() {
  27137. const output = this.getDefaultOutput().value;
  27138. if ( output && output.isNode ) {
  27139. return output;
  27140. }
  27141. return float();
  27142. }
  27143. /**
  27144. * Returns default output of the script.
  27145. *
  27146. * @return {ScriptableValueNode} The default output.
  27147. */
  27148. getDefaultOutput() {
  27149. return this._exec()._output;
  27150. }
  27151. /**
  27152. * Returns a function created from the node's script.
  27153. *
  27154. * @return {Function} The function representing the node's code.
  27155. */
  27156. getMethod() {
  27157. if ( this.needsUpdate ) this.dispose();
  27158. if ( this._method !== null ) return this._method;
  27159. //
  27160. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  27161. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  27162. const properties = interfaceProps.join( ', ' );
  27163. const declarations = 'var ' + properties + '; var output = {};\n';
  27164. const returns = '\nreturn { ...output, ' + properties + ' };';
  27165. const code = declarations + this.codeNode.code + returns;
  27166. //
  27167. this._method = new Function( ...parametersProps, code );
  27168. return this._method;
  27169. }
  27170. /**
  27171. * Frees all internal resources.
  27172. */
  27173. dispose() {
  27174. if ( this._method === null ) return;
  27175. if ( this._object && typeof this._object.dispose === 'function' ) {
  27176. this._object.dispose();
  27177. }
  27178. this._method = null;
  27179. this._object = null;
  27180. this._source = null;
  27181. this._value = null;
  27182. this._needsOutputUpdate = true;
  27183. this._output.value = null;
  27184. this._outputs = {};
  27185. }
  27186. setup() {
  27187. return this.getDefaultOutputNode();
  27188. }
  27189. getCacheKey( force ) {
  27190. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  27191. for ( const param in this.parameters ) {
  27192. values.push( this.parameters[ param ].getCacheKey( force ) );
  27193. }
  27194. return hashArray( values );
  27195. }
  27196. set needsUpdate( value ) {
  27197. if ( value === true ) this.dispose();
  27198. }
  27199. get needsUpdate() {
  27200. return this.source !== this._source;
  27201. }
  27202. /**
  27203. * Executes the `main` function of the script.
  27204. *
  27205. * @private
  27206. * @return {ScriptableNode} A reference to this node.
  27207. */
  27208. _exec() {
  27209. if ( this.codeNode === null ) return this;
  27210. if ( this._needsOutputUpdate === true ) {
  27211. this._value = this.call( 'main' );
  27212. this._needsOutputUpdate = false;
  27213. }
  27214. this._output.value = this._value;
  27215. return this;
  27216. }
  27217. /**
  27218. * Executes the refresh.
  27219. *
  27220. * @private
  27221. */
  27222. _refresh() {
  27223. this.needsUpdate = true;
  27224. this._exec();
  27225. this._output.refresh();
  27226. }
  27227. }
  27228. /**
  27229. * TSL function for creating a scriptable node.
  27230. *
  27231. * @tsl
  27232. * @function
  27233. * @param {CodeNode} [codeNode] - The code node.
  27234. * @param {?Object} [parameters={}] - The parameters definition.
  27235. * @returns {ScriptableNode}
  27236. */
  27237. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  27238. /**
  27239. * Returns a node that represents the `z` coordinate in view space
  27240. * for the current fragment. It's a different representation of the
  27241. * default depth value.
  27242. *
  27243. * This value can be part of a computation that defines how the fog
  27244. * density increases when moving away from the camera.
  27245. *
  27246. * @param {NodeBuilder} builder - The current node builder.
  27247. * @return {Node} The viewZ node.
  27248. */
  27249. function getViewZNode( builder ) {
  27250. let viewZ;
  27251. const getViewZ = builder.context.getViewZ;
  27252. if ( getViewZ !== undefined ) {
  27253. viewZ = getViewZ( this );
  27254. }
  27255. return ( viewZ || positionView.z ).negate();
  27256. }
  27257. /**
  27258. * Constructs a new range factor node.
  27259. *
  27260. * @tsl
  27261. * @function
  27262. * @param {Node} near - Defines the near value.
  27263. * @param {Node} far - Defines the far value.
  27264. */
  27265. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  27266. const viewZ = getViewZNode( builder );
  27267. return smoothstep( near, far, viewZ );
  27268. } );
  27269. /**
  27270. * Represents an exponential squared fog. This type of fog gives
  27271. * a clear view near the camera and a faster than exponentially
  27272. * densening fog farther from the camera.
  27273. *
  27274. * @tsl
  27275. * @function
  27276. * @param {Node} density - Defines the fog density.
  27277. */
  27278. const densityFogFactor = Fn( ( [ density ], builder ) => {
  27279. const viewZ = getViewZNode( builder );
  27280. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  27281. } );
  27282. /**
  27283. * This class can be used to configure a fog for the scene.
  27284. * Nodes of this type are assigned to `Scene.fogNode`.
  27285. *
  27286. * @tsl
  27287. * @function
  27288. * @param {Node} color - Defines the color of the fog.
  27289. * @param {Node} factor - Defines how the fog is factored in the scene.
  27290. */
  27291. const fog = Fn( ( [ color, factor ] ) => {
  27292. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  27293. } );
  27294. // Deprecated
  27295. /**
  27296. * @tsl
  27297. * @function
  27298. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  27299. *
  27300. * @param {Node} color
  27301. * @param {Node} near
  27302. * @param {Node} far
  27303. * @returns {Function}
  27304. */
  27305. function rangeFog( color, near, far ) { // @deprecated, r171
  27306. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  27307. return fog( color, rangeFogFactor( near, far ) );
  27308. }
  27309. /**
  27310. * @tsl
  27311. * @function
  27312. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  27313. *
  27314. * @param {Node} color
  27315. * @param {Node} density
  27316. * @returns {Function}
  27317. */
  27318. function densityFog( color, density ) { // @deprecated, r171
  27319. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  27320. return fog( color, densityFogFactor( density ) );
  27321. }
  27322. let min = null;
  27323. let max = null;
  27324. /**
  27325. * `RangeNode` generates random instanced attribute data in a defined range.
  27326. * An exemplary use case for this utility node is to generate random per-instance
  27327. * colors:
  27328. * ```js
  27329. * const material = new MeshBasicNodeMaterial();
  27330. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  27331. * const mesh = new InstancedMesh( geometry, material, count );
  27332. * ```
  27333. * @augments Node
  27334. */
  27335. class RangeNode extends Node {
  27336. static get type() {
  27337. return 'RangeNode';
  27338. }
  27339. /**
  27340. * Constructs a new range node.
  27341. *
  27342. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  27343. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  27344. */
  27345. constructor( minNode = float(), maxNode = float() ) {
  27346. super();
  27347. /**
  27348. * A node defining the lower bound of the range.
  27349. *
  27350. * @type {Node<any>}
  27351. * @default float()
  27352. */
  27353. this.minNode = minNode;
  27354. /**
  27355. * A node defining the upper bound of the range.
  27356. *
  27357. * @type {Node<any>}
  27358. * @default float()
  27359. */
  27360. this.maxNode = maxNode;
  27361. }
  27362. /**
  27363. * Returns the vector length which is computed based on the range definition.
  27364. *
  27365. * @param {NodeBuilder} builder - The current node builder.
  27366. * @return {number} The vector length.
  27367. */
  27368. getVectorLength( builder ) {
  27369. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  27370. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  27371. return minLength > maxLength ? minLength : maxLength;
  27372. }
  27373. /**
  27374. * This method is overwritten since the node type is inferred from range definition.
  27375. *
  27376. * @param {NodeBuilder} builder - The current node builder.
  27377. * @return {string} The node type.
  27378. */
  27379. getNodeType( builder ) {
  27380. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  27381. }
  27382. setup( builder ) {
  27383. const object = builder.object;
  27384. let output = null;
  27385. if ( object.count > 1 ) {
  27386. const minValue = this.minNode.value;
  27387. const maxValue = this.maxNode.value;
  27388. const minLength = builder.getTypeLength( getValueType( minValue ) );
  27389. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  27390. min = min || new Vector4();
  27391. max = max || new Vector4();
  27392. min.setScalar( 0 );
  27393. max.setScalar( 0 );
  27394. if ( minLength === 1 ) min.setScalar( minValue );
  27395. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  27396. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  27397. if ( maxLength === 1 ) max.setScalar( maxValue );
  27398. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  27399. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  27400. const stride = 4;
  27401. const length = stride * object.count;
  27402. const array = new Float32Array( length );
  27403. for ( let i = 0; i < length; i ++ ) {
  27404. const index = i % stride;
  27405. const minElementValue = min.getComponent( index );
  27406. const maxElementValue = max.getComponent( index );
  27407. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  27408. }
  27409. const nodeType = this.getNodeType( builder );
  27410. if ( object.count <= 4096 ) {
  27411. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  27412. } else {
  27413. // TODO: Improve anonymous buffer attribute creation removing this part
  27414. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  27415. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  27416. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  27417. }
  27418. } else {
  27419. output = float( 0 );
  27420. }
  27421. return output;
  27422. }
  27423. }
  27424. /**
  27425. * TSL function for creating a range node.
  27426. *
  27427. * @tsl
  27428. * @function
  27429. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  27430. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  27431. * @returns {RangeNode}
  27432. */
  27433. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  27434. /**
  27435. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  27436. * about the currently running dispatch and/or the device it is running on.
  27437. *
  27438. * This node can only be used with a WebGPU backend.
  27439. *
  27440. * @augments Node
  27441. */
  27442. class ComputeBuiltinNode extends Node {
  27443. static get type() {
  27444. return 'ComputeBuiltinNode';
  27445. }
  27446. /**
  27447. * Constructs a new compute builtin node.
  27448. *
  27449. * @param {string} builtinName - The built-in name.
  27450. * @param {string} nodeType - The node type.
  27451. */
  27452. constructor( builtinName, nodeType ) {
  27453. super( nodeType );
  27454. /**
  27455. * The built-in name.
  27456. *
  27457. * @private
  27458. * @type {string}
  27459. */
  27460. this._builtinName = builtinName;
  27461. }
  27462. /**
  27463. * This method is overwritten since hash is derived from the built-in name.
  27464. *
  27465. * @param {NodeBuilder} builder - The current node builder.
  27466. * @return {string} The hash.
  27467. */
  27468. getHash( builder ) {
  27469. return this.getBuiltinName( builder );
  27470. }
  27471. /**
  27472. * This method is overwritten since the node type is simply derived from `nodeType`..
  27473. *
  27474. * @param {NodeBuilder} builder - The current node builder.
  27475. * @return {string} The node type.
  27476. */
  27477. getNodeType( /*builder*/ ) {
  27478. return this.nodeType;
  27479. }
  27480. /**
  27481. * Sets the builtin name.
  27482. *
  27483. * @param {string} builtinName - The built-in name.
  27484. * @return {ComputeBuiltinNode} A reference to this node.
  27485. */
  27486. setBuiltinName( builtinName ) {
  27487. this._builtinName = builtinName;
  27488. return this;
  27489. }
  27490. /**
  27491. * Returns the builtin name.
  27492. *
  27493. * @param {NodeBuilder} builder - The current node builder.
  27494. * @return {string} The builtin name.
  27495. */
  27496. getBuiltinName( /*builder*/ ) {
  27497. return this._builtinName;
  27498. }
  27499. /**
  27500. * Whether the current node builder has the builtin or not.
  27501. *
  27502. * @param {NodeBuilder} builder - The current node builder.
  27503. * @return {boolean} Whether the builder has the builtin or not.
  27504. */
  27505. hasBuiltin( builder ) {
  27506. return builder.hasBuiltin( this._builtinName );
  27507. }
  27508. generate( builder, output ) {
  27509. const builtinName = this.getBuiltinName( builder );
  27510. const nodeType = this.getNodeType( builder );
  27511. if ( builder.shaderStage === 'compute' ) {
  27512. return builder.format( builtinName, nodeType, output );
  27513. } else {
  27514. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  27515. return builder.generateConst( nodeType );
  27516. }
  27517. }
  27518. serialize( data ) {
  27519. super.serialize( data );
  27520. data.global = this.global;
  27521. data._builtinName = this._builtinName;
  27522. }
  27523. deserialize( data ) {
  27524. super.deserialize( data );
  27525. this.global = data.global;
  27526. this._builtinName = data._builtinName;
  27527. }
  27528. }
  27529. /**
  27530. * TSL function for creating a compute builtin node.
  27531. *
  27532. * @tsl
  27533. * @function
  27534. * @param {string} name - The built-in name.
  27535. * @param {string} nodeType - The node type.
  27536. * @returns {ComputeBuiltinNode}
  27537. */
  27538. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  27539. /**
  27540. * Represents the number of workgroups dispatched by the compute shader.
  27541. * ```js
  27542. * // Run 512 invocations/threads with a workgroup size of 128.
  27543. * const computeFn = Fn(() => {
  27544. *
  27545. * // numWorkgroups.x = 4
  27546. * storageBuffer.element(0).assign(numWorkgroups.x)
  27547. *
  27548. * })().compute(512, [128]);
  27549. *
  27550. * // Run 512 invocations/threads with the default workgroup size of 64.
  27551. * const computeFn = Fn(() => {
  27552. *
  27553. * // numWorkgroups.x = 8
  27554. * storageBuffer.element(0).assign(numWorkgroups.x)
  27555. *
  27556. * })().compute(512);
  27557. * ```
  27558. *
  27559. * @tsl
  27560. * @type {ComputeBuiltinNode<uvec3>}
  27561. */
  27562. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  27563. /**
  27564. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  27565. * ```js
  27566. * // Execute 12 compute threads with a workgroup size of 3.
  27567. * const computeFn = Fn( () => {
  27568. *
  27569. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  27570. *
  27571. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  27572. *
  27573. * } ).Else( () => {
  27574. *
  27575. * storageBuffer.element( instanceIndex ).assign( 0 );
  27576. *
  27577. * } );
  27578. *
  27579. * } )().compute( 12, [ 3 ] );
  27580. *
  27581. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  27582. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  27583. * ```
  27584. *
  27585. * @tsl
  27586. * @type {ComputeBuiltinNode<uvec3>}
  27587. */
  27588. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  27589. /**
  27590. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  27591. *
  27592. * @tsl
  27593. * @type {ComputeBuiltinNode<uvec3>}
  27594. */
  27595. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  27596. /**
  27597. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  27598. *
  27599. * @tsl
  27600. * @type {ComputeBuiltinNode<uvec3>}
  27601. */
  27602. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  27603. /**
  27604. * A device dependent variable that exposes the size of the current invocation's subgroup.
  27605. *
  27606. * @tsl
  27607. * @type {ComputeBuiltinNode<uint>}
  27608. */
  27609. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  27610. /**
  27611. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  27612. *
  27613. * This node can only be used with a WebGPU backend.
  27614. *
  27615. * @augments Node
  27616. */
  27617. class BarrierNode extends Node {
  27618. /**
  27619. * Constructs a new barrier node.
  27620. *
  27621. * @param {string} scope - The scope defines the behavior of the node.
  27622. */
  27623. constructor( scope ) {
  27624. super();
  27625. this.scope = scope;
  27626. }
  27627. generate( builder ) {
  27628. const { scope } = this;
  27629. const { renderer } = builder;
  27630. if ( renderer.backend.isWebGLBackend === true ) {
  27631. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  27632. } else {
  27633. builder.addLineFlowCode( `${scope}Barrier()`, this );
  27634. }
  27635. }
  27636. }
  27637. /**
  27638. * TSL function for creating a barrier node.
  27639. *
  27640. * @tsl
  27641. * @function
  27642. * @param {string} scope - The scope defines the behavior of the node..
  27643. * @returns {BarrierNode}
  27644. */
  27645. const barrier = nodeProxy( BarrierNode );
  27646. /**
  27647. * TSL function for creating a workgroup barrier. All compute shader
  27648. * invocations must wait for each invocation within a workgroup to
  27649. * complete before the barrier can be surpassed.
  27650. *
  27651. * @tsl
  27652. * @function
  27653. * @returns {BarrierNode}
  27654. */
  27655. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  27656. /**
  27657. * TSL function for creating a storage barrier. All invocations must
  27658. * wait for each access to variables within the 'storage' address space
  27659. * to complete before the barrier can be passed.
  27660. *
  27661. * @tsl
  27662. * @function
  27663. * @returns {BarrierNode}
  27664. */
  27665. const storageBarrier = () => barrier( 'storage' ).toStack();
  27666. /**
  27667. * TSL function for creating a texture barrier. All invocations must
  27668. * wait for each access to variables within the 'texture' address space
  27669. * to complete before the barrier can be passed.
  27670. *
  27671. * @tsl
  27672. * @function
  27673. * @returns {BarrierNode}
  27674. */
  27675. const textureBarrier = () => barrier( 'texture' ).toStack();
  27676. /**
  27677. * Represents an element of a 'workgroup' scoped buffer.
  27678. *
  27679. * @augments ArrayElementNode
  27680. */
  27681. class WorkgroupInfoElementNode extends ArrayElementNode {
  27682. /**
  27683. * Constructs a new workgroup info element node.
  27684. *
  27685. * @param {Node} workgroupInfoNode - The workgroup info node.
  27686. * @param {Node} indexNode - The index node that defines the element access.
  27687. */
  27688. constructor( workgroupInfoNode, indexNode ) {
  27689. super( workgroupInfoNode, indexNode );
  27690. /**
  27691. * This flag can be used for type testing.
  27692. *
  27693. * @type {boolean}
  27694. * @readonly
  27695. * @default true
  27696. */
  27697. this.isWorkgroupInfoElementNode = true;
  27698. }
  27699. generate( builder, output ) {
  27700. let snippet;
  27701. const isAssignContext = builder.context.assign;
  27702. snippet = super.generate( builder );
  27703. if ( isAssignContext !== true ) {
  27704. const type = this.getNodeType( builder );
  27705. snippet = builder.format( snippet, type, output );
  27706. }
  27707. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  27708. return snippet;
  27709. }
  27710. }
  27711. /**
  27712. * A node allowing the user to create a 'workgroup' scoped buffer within the
  27713. * context of a compute shader. Typically, workgroup scoped buffers are
  27714. * created to hold data that is transferred from a global storage scope into
  27715. * a local workgroup scope. For invocations within a workgroup, data
  27716. * access speeds on 'workgroup' scoped buffers can be significantly faster
  27717. * than similar access operations on globally accessible storage buffers.
  27718. *
  27719. * This node can only be used with a WebGPU backend.
  27720. *
  27721. * @augments Node
  27722. */
  27723. class WorkgroupInfoNode extends Node {
  27724. /**
  27725. * Constructs a new buffer scoped to type scope.
  27726. *
  27727. * @param {string} scope - TODO.
  27728. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  27729. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  27730. */
  27731. constructor( scope, bufferType, bufferCount = 0 ) {
  27732. super( bufferType );
  27733. /**
  27734. * The buffer type.
  27735. *
  27736. * @type {string}
  27737. */
  27738. this.bufferType = bufferType;
  27739. /**
  27740. * The buffer count.
  27741. *
  27742. * @type {number}
  27743. * @default 0
  27744. */
  27745. this.bufferCount = bufferCount;
  27746. /**
  27747. * This flag can be used for type testing.
  27748. *
  27749. * @type {boolean}
  27750. * @readonly
  27751. * @default true
  27752. */
  27753. this.isWorkgroupInfoNode = true;
  27754. /**
  27755. * The data type of the array buffer.
  27756. *
  27757. * @type {string}
  27758. */
  27759. this.elementType = bufferType;
  27760. /**
  27761. * TODO.
  27762. *
  27763. * @type {string}
  27764. */
  27765. this.scope = scope;
  27766. /**
  27767. * The name of the workgroup scoped buffer.
  27768. *
  27769. * @type {string}
  27770. * @default ''
  27771. */
  27772. this.name = '';
  27773. }
  27774. /**
  27775. * Sets the name of this node.
  27776. *
  27777. * @param {string} name - The name to set.
  27778. * @return {WorkgroupInfoNode} A reference to this node.
  27779. */
  27780. setName( name ) {
  27781. this.name = name;
  27782. return this;
  27783. }
  27784. /**
  27785. * Sets the name/label of this node.
  27786. *
  27787. * @deprecated
  27788. * @param {string} name - The name to set.
  27789. * @return {WorkgroupInfoNode} A reference to this node.
  27790. */
  27791. label( name ) {
  27792. console.warn( 'THREE.TSL: "label()" has been deprecated. Use "setName()" instead.' ); // @deprecated r179
  27793. return this.setName( name );
  27794. }
  27795. /**
  27796. * Sets the scope of this node.
  27797. *
  27798. * @param {string} scope - The scope to set.
  27799. * @return {WorkgroupInfoNode} A reference to this node.
  27800. */
  27801. setScope( scope ) {
  27802. this.scope = scope;
  27803. return this;
  27804. }
  27805. /**
  27806. * The data type of the array buffer.
  27807. *
  27808. * @return {string} The element type.
  27809. */
  27810. getElementType() {
  27811. return this.elementType;
  27812. }
  27813. /**
  27814. * Overwrites the default implementation since the input type
  27815. * is inferred from the scope.
  27816. *
  27817. * @param {NodeBuilder} builder - The current node builder.
  27818. * @return {string} The input type.
  27819. */
  27820. getInputType( /*builder*/ ) {
  27821. return `${this.scope}Array`;
  27822. }
  27823. /**
  27824. * This method can be used to access elements via an index node.
  27825. *
  27826. * @param {IndexNode} indexNode - indexNode.
  27827. * @return {WorkgroupInfoElementNode} A reference to an element.
  27828. */
  27829. element( indexNode ) {
  27830. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  27831. }
  27832. generate( builder ) {
  27833. const name = ( this.name !== '' ) ? this.name : `${this.scope}Array_${this.id}`;
  27834. return builder.getScopedArray( name, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  27835. }
  27836. }
  27837. /**
  27838. * TSL function for creating a workgroup info node.
  27839. * Creates a new 'workgroup' scoped array buffer.
  27840. *
  27841. * @tsl
  27842. * @function
  27843. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  27844. * @param {number} [count=0] - The number of elements in the buffer.
  27845. * @returns {WorkgroupInfoNode}
  27846. */
  27847. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  27848. /**
  27849. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  27850. * within a shader. In an atomic function, any modification to an atomic variable will
  27851. * occur as an indivisible step with a defined order relative to other modifications.
  27852. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  27853. * atomic operations will not interfere with each other.
  27854. *
  27855. * This node can only be used with a WebGPU backend.
  27856. *
  27857. * @augments Node
  27858. */
  27859. class AtomicFunctionNode extends Node {
  27860. static get type() {
  27861. return 'AtomicFunctionNode';
  27862. }
  27863. /**
  27864. * Constructs a new atomic function node.
  27865. *
  27866. * @param {string} method - The signature of the atomic function to construct.
  27867. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27868. * @param {Node} valueNode - The value that mutates the atomic variable.
  27869. */
  27870. constructor( method, pointerNode, valueNode ) {
  27871. super( 'uint' );
  27872. /**
  27873. * The signature of the atomic function to construct.
  27874. *
  27875. * @type {string}
  27876. */
  27877. this.method = method;
  27878. /**
  27879. * An atomic variable or element of an atomic buffer.
  27880. *
  27881. * @type {Node}
  27882. */
  27883. this.pointerNode = pointerNode;
  27884. /**
  27885. * A value that modifies the atomic variable.
  27886. *
  27887. * @type {Node}
  27888. */
  27889. this.valueNode = valueNode;
  27890. /**
  27891. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  27892. *
  27893. * @type {boolean}
  27894. * @default true
  27895. */
  27896. this.parents = true;
  27897. }
  27898. /**
  27899. * Overwrites the default implementation to return the type of
  27900. * the pointer node.
  27901. *
  27902. * @param {NodeBuilder} builder - The current node builder.
  27903. * @return {string} The input type.
  27904. */
  27905. getInputType( builder ) {
  27906. return this.pointerNode.getNodeType( builder );
  27907. }
  27908. /**
  27909. * Overwritten since the node type is inferred from the input type.
  27910. *
  27911. * @param {NodeBuilder} builder - The current node builder.
  27912. * @return {string} The node type.
  27913. */
  27914. getNodeType( builder ) {
  27915. return this.getInputType( builder );
  27916. }
  27917. generate( builder ) {
  27918. const properties = builder.getNodeProperties( this );
  27919. const parents = properties.parents;
  27920. const method = this.method;
  27921. const type = this.getNodeType( builder );
  27922. const inputType = this.getInputType( builder );
  27923. const a = this.pointerNode;
  27924. const b = this.valueNode;
  27925. const params = [];
  27926. params.push( `&${ a.build( builder, inputType ) }` );
  27927. if ( b !== null ) {
  27928. params.push( b.build( builder, inputType ) );
  27929. }
  27930. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  27931. const isVoid = parents ? ( parents.length === 1 && parents[ 0 ].isStackNode === true ) : false;
  27932. if ( isVoid ) {
  27933. builder.addLineFlowCode( methodSnippet, this );
  27934. } else {
  27935. if ( properties.constNode === undefined ) {
  27936. properties.constNode = expression( methodSnippet, type ).toConst();
  27937. }
  27938. return properties.constNode.build( builder );
  27939. }
  27940. }
  27941. }
  27942. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  27943. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  27944. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  27945. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  27946. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  27947. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  27948. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  27949. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  27950. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  27951. /**
  27952. * TSL function for creating an atomic function node.
  27953. *
  27954. * @tsl
  27955. * @function
  27956. * @param {string} method - The signature of the atomic function to construct.
  27957. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27958. * @param {Node} valueNode - The value that mutates the atomic variable.
  27959. * @returns {AtomicFunctionNode}
  27960. */
  27961. const atomicNode = nodeProxy( AtomicFunctionNode );
  27962. /**
  27963. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  27964. *
  27965. * @tsl
  27966. * @function
  27967. * @param {string} method - The signature of the atomic function to construct.
  27968. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27969. * @param {Node} valueNode - The value that mutates the atomic variable.
  27970. * @returns {AtomicFunctionNode}
  27971. */
  27972. const atomicFunc = ( method, pointerNode, valueNode ) => {
  27973. return atomicNode( method, pointerNode, valueNode ).toStack();
  27974. };
  27975. /**
  27976. * Loads the value stored in the atomic variable.
  27977. *
  27978. * @tsl
  27979. * @function
  27980. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27981. * @returns {AtomicFunctionNode}
  27982. */
  27983. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  27984. /**
  27985. * Stores a value in the atomic variable.
  27986. *
  27987. * @tsl
  27988. * @function
  27989. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  27990. * @param {Node} valueNode - The value that mutates the atomic variable.
  27991. * @returns {AtomicFunctionNode}
  27992. */
  27993. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  27994. /**
  27995. * Increments the value stored in the atomic variable.
  27996. *
  27997. * @tsl
  27998. * @function
  27999. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28000. * @param {Node} valueNode - The value that mutates the atomic variable.
  28001. * @returns {AtomicFunctionNode}
  28002. */
  28003. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  28004. /**
  28005. * Decrements the value stored in the atomic variable.
  28006. *
  28007. * @tsl
  28008. * @function
  28009. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28010. * @param {Node} valueNode - The value that mutates the atomic variable.
  28011. * @returns {AtomicFunctionNode}
  28012. */
  28013. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  28014. /**
  28015. * Stores in an atomic variable the maximum between its current value and a parameter.
  28016. *
  28017. * @tsl
  28018. * @function
  28019. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28020. * @param {Node} valueNode - The value that mutates the atomic variable.
  28021. * @returns {AtomicFunctionNode}
  28022. */
  28023. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  28024. /**
  28025. * Stores in an atomic variable the minimum between its current value and a parameter.
  28026. *
  28027. * @tsl
  28028. * @function
  28029. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28030. * @param {Node} valueNode - The value that mutates the atomic variable.
  28031. * @returns {AtomicFunctionNode}
  28032. */
  28033. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  28034. /**
  28035. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  28036. *
  28037. * @tsl
  28038. * @function
  28039. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28040. * @param {Node} valueNode - The value that mutates the atomic variable.
  28041. * @returns {AtomicFunctionNode}
  28042. */
  28043. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  28044. /**
  28045. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  28046. *
  28047. * @tsl
  28048. * @function
  28049. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28050. * @param {Node} valueNode - The value that mutates the atomic variable.
  28051. * @returns {AtomicFunctionNode}
  28052. */
  28053. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  28054. /**
  28055. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  28056. *
  28057. * @tsl
  28058. * @function
  28059. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  28060. * @param {Node} valueNode - The value that mutates the atomic variable.
  28061. * @returns {AtomicFunctionNode}
  28062. */
  28063. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  28064. /**
  28065. * This class represents a set of built in WGSL shader functions that sync
  28066. * synchronously execute an operation across a subgroup, or 'warp', of compute
  28067. * or fragment shader invocations within a workgroup. Typically, these functions
  28068. * will synchronously execute an operation using data from all active invocations
  28069. * within the subgroup, then broadcast that result to all active invocations. In
  28070. * other graphics APIs, subgroup functions are also referred to as wave intrinsics
  28071. * (DirectX/HLSL) or warp intrinsics (CUDA).
  28072. *
  28073. * @augments TempNode
  28074. */
  28075. class SubgroupFunctionNode extends TempNode {
  28076. static get type() {
  28077. return 'SubgroupFunctionNode';
  28078. }
  28079. /**
  28080. * Constructs a new function node.
  28081. *
  28082. * @param {string} method - The subgroup/wave intrinsic method to construct.
  28083. * @param {Node} [aNode=null] - The method's first argument.
  28084. * @param {Node} [bNode=null] - The method's second argument.
  28085. */
  28086. constructor( method, aNode = null, bNode = null ) {
  28087. super();
  28088. /**
  28089. * The subgroup/wave intrinsic method to construct.
  28090. *
  28091. * @type {String}
  28092. */
  28093. this.method = method;
  28094. /**
  28095. * The method's first argument.
  28096. *
  28097. * @type {Node}
  28098. */
  28099. this.aNode = aNode;
  28100. /**
  28101. * The method's second argument.
  28102. *
  28103. * @type {Node}
  28104. */
  28105. this.bNode = bNode;
  28106. }
  28107. getInputType( builder ) {
  28108. const aType = this.aNode ? this.aNode.getNodeType( builder ) : null;
  28109. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  28110. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  28111. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  28112. if ( aLen > bLen ) {
  28113. return aType;
  28114. } else {
  28115. return bType;
  28116. }
  28117. }
  28118. getNodeType( builder ) {
  28119. const method = this.method;
  28120. if ( method === SubgroupFunctionNode.SUBGROUP_ELECT ) {
  28121. return 'bool';
  28122. } else if ( method === SubgroupFunctionNode.SUBGROUP_BALLOT ) {
  28123. return 'uvec4';
  28124. } else {
  28125. return this.getInputType( builder );
  28126. }
  28127. }
  28128. generate( builder, output ) {
  28129. const method = this.method;
  28130. const type = this.getNodeType( builder );
  28131. const inputType = this.getInputType( builder );
  28132. const a = this.aNode;
  28133. const b = this.bNode;
  28134. const params = [];
  28135. if (
  28136. method === SubgroupFunctionNode.SUBGROUP_BROADCAST ||
  28137. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE ||
  28138. method === SubgroupFunctionNode.QUAD_BROADCAST
  28139. ) {
  28140. const bType = b.getNodeType( builder );
  28141. params.push(
  28142. a.build( builder, type ),
  28143. b.build( builder, bType === 'float' ? 'int' : type )
  28144. );
  28145. } else if (
  28146. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ||
  28147. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ||
  28148. method === SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP
  28149. ) {
  28150. params.push(
  28151. a.build( builder, type ),
  28152. b.build( builder, 'uint' )
  28153. );
  28154. } else {
  28155. if ( a !== null ) params.push( a.build( builder, inputType ) );
  28156. if ( b !== null ) params.push( b.build( builder, inputType ) );
  28157. }
  28158. const paramsString = params.length === 0 ? '()' : `( ${params.join( ', ' )} )`;
  28159. return builder.format( `${ builder.getMethod( method, type ) }${paramsString}`, type, output );
  28160. }
  28161. serialize( data ) {
  28162. super.serialize( data );
  28163. data.method = this.method;
  28164. }
  28165. deserialize( data ) {
  28166. super.deserialize( data );
  28167. this.method = data.method;
  28168. }
  28169. }
  28170. // 0 inputs
  28171. SubgroupFunctionNode.SUBGROUP_ELECT = 'subgroupElect';
  28172. // 1 input
  28173. SubgroupFunctionNode.SUBGROUP_BALLOT = 'subgroupBallot';
  28174. SubgroupFunctionNode.SUBGROUP_ADD = 'subgroupAdd';
  28175. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD = 'subgroupInclusiveAdd';
  28176. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND = 'subgroupExclusiveAdd';
  28177. SubgroupFunctionNode.SUBGROUP_MUL = 'subgroupMul';
  28178. SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL = 'subgroupInclusiveMul';
  28179. SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL = 'subgroupExclusiveMul';
  28180. SubgroupFunctionNode.SUBGROUP_AND = 'subgroupAnd';
  28181. SubgroupFunctionNode.SUBGROUP_OR = 'subgroupOr';
  28182. SubgroupFunctionNode.SUBGROUP_XOR = 'subgroupXor';
  28183. SubgroupFunctionNode.SUBGROUP_MIN = 'subgroupMin';
  28184. SubgroupFunctionNode.SUBGROUP_MAX = 'subgroupMax';
  28185. SubgroupFunctionNode.SUBGROUP_ALL = 'subgroupAll';
  28186. SubgroupFunctionNode.SUBGROUP_ANY = 'subgroupAny';
  28187. SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST = 'subgroupBroadcastFirst';
  28188. SubgroupFunctionNode.QUAD_SWAP_X = 'quadSwapX';
  28189. SubgroupFunctionNode.QUAD_SWAP_Y = 'quadSwapY';
  28190. SubgroupFunctionNode.QUAD_SWAP_DIAGONAL = 'quadSwapDiagonal';
  28191. // 2 inputs
  28192. SubgroupFunctionNode.SUBGROUP_BROADCAST = 'subgroupBroadcast';
  28193. SubgroupFunctionNode.SUBGROUP_SHUFFLE = 'subgroupShuffle';
  28194. SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR = 'subgroupShuffleXor';
  28195. SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP = 'subgroupShuffleUp';
  28196. SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN = 'subgroupShuffleDown';
  28197. SubgroupFunctionNode.QUAD_BROADCAST = 'quadBroadcast';
  28198. /**
  28199. * Returns true if this invocation has the lowest subgroup_invocation_id
  28200. * among active invocations in the subgroup.
  28201. *
  28202. * @method
  28203. * @return {bool} The result of the computation.
  28204. */
  28205. const subgroupElect = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ELECT ).setParameterLength( 0 );
  28206. /**
  28207. * Returns a set of bitfields where the bit corresponding to subgroup_invocation_id
  28208. * is 1 if pred is true for that active invocation and 0 otherwise.
  28209. *
  28210. * @method
  28211. * @param {bool} pred - A boolean that sets the bit corresponding to the invocations subgroup invocation id.
  28212. * @return {vec4<u32>}- A bitfield corresponding to the pred value of each subgroup invocation.
  28213. */
  28214. const subgroupBallot = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BALLOT ).setParameterLength( 1 );
  28215. /**
  28216. * A reduction that adds e among all active invocations and returns that result.
  28217. *
  28218. * @method
  28219. * @param {number} e - The value provided to the reduction by the current invocation.
  28220. * @return {number} The accumulated result of the reduction operation.
  28221. */
  28222. const subgroupAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ADD ).setParameterLength( 1 );
  28223. /**
  28224. * An inclusive scan returning the sum of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  28225. *
  28226. * @method
  28227. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  28228. * @return {number} The accumulated result of the inclusive scan operation.
  28229. */
  28230. const subgroupInclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_ADD ).setParameterLength( 1 );
  28231. /**
  28232. * An exclusive scan that returns the sum of e for all active invocations with subgroup_invocation_id less than this invocation.
  28233. *
  28234. * @method
  28235. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  28236. * @return {number} The accumulated result of the exclusive scan operation.
  28237. */
  28238. const subgroupExclusiveAdd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_AND ).setParameterLength( 1 );
  28239. /**
  28240. * A reduction that multiplies e among all active invocations and returns that result.
  28241. *
  28242. * @method
  28243. * @param {number} e - The value provided to the reduction by the current invocation.
  28244. * @return {number} The accumulated result of the reduction operation.
  28245. */
  28246. const subgroupMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MUL ).setParameterLength( 1 );
  28247. /**
  28248. * An inclusive scan returning the product of e for all active invocations with subgroup_invocation_id less than or equal to this invocation.
  28249. *
  28250. * @method
  28251. * @param {number} e - The value provided to the inclusive scan by the current invocation.
  28252. * @return {number} The accumulated result of the inclusive scan operation.
  28253. */
  28254. const subgroupInclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_INCLUSIVE_MUL ).setParameterLength( 1 );
  28255. /**
  28256. * An exclusive scan that returns the product of e for all active invocations with subgroup_invocation_id less than this invocation.
  28257. *
  28258. * @method
  28259. * @param {number} e - The value provided to the exclusive scan by the current invocation.
  28260. * @return {number} The accumulated result of the exclusive scan operation.
  28261. */
  28262. const subgroupExclusiveMul = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_EXCLUSIVE_MUL ).setParameterLength( 1 );
  28263. /**
  28264. * A reduction that performs a bitwise and of e among all active invocations and returns that result.
  28265. *
  28266. * @method
  28267. * @param {number} e - The value provided to the reduction by the current invocation.
  28268. * @return {number} The result of the reduction operation.
  28269. */
  28270. const subgroupAnd = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_AND ).setParameterLength( 1 );
  28271. /**
  28272. * A reduction that performs a bitwise or of e among all active invocations and returns that result.
  28273. *
  28274. * @method
  28275. * @param {number} e - The value provided to the reduction by the current invocation.
  28276. * @return {number} The result of the reduction operation.
  28277. */
  28278. const subgroupOr = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_OR ).setParameterLength( 1 );
  28279. /**
  28280. * A reduction that performs a bitwise xor of e among all active invocations and returns that result.
  28281. *
  28282. * @method
  28283. * @param {number} e - The value provided to the reduction by the current invocation.
  28284. * @return {number} The result of the reduction operation.
  28285. */
  28286. const subgroupXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_XOR ).setParameterLength( 1 );
  28287. /**
  28288. * A reduction that performs a min of e among all active invocations and returns that result.
  28289. *
  28290. * @method
  28291. * @param {number} e - The value provided to the reduction by the current invocation.
  28292. * @return {number} The result of the reduction operation.
  28293. */
  28294. const subgroupMin = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MIN ).setParameterLength( 1 );
  28295. /**
  28296. * A reduction that performs a max of e among all active invocations and returns that result.
  28297. *
  28298. * @method
  28299. * @param {number} e - The value provided to the reduction by the current invocation.
  28300. * @return {number} The result of the reduction operation.
  28301. */
  28302. const subgroupMax = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_MAX ).setParameterLength( 1 );
  28303. /**
  28304. * Returns true if e is true for all active invocations in the subgroup.
  28305. *
  28306. * @method
  28307. * @return {bool} The result of the computation.
  28308. */
  28309. const subgroupAll = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ALL ).setParameterLength( 0 );
  28310. /**
  28311. * Returns true if e is true for any active invocation in the subgroup
  28312. *
  28313. * @method
  28314. * @return {bool} The result of the computation.
  28315. */
  28316. const subgroupAny = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_ANY ).setParameterLength( 0 );
  28317. /**
  28318. * Broadcasts e from the active invocation with the lowest subgroup_invocation_id in the subgroup to all other active invocations.
  28319. *
  28320. * @method
  28321. * @param {number} e - The value to broadcast from the lowest subgroup invocation.
  28322. * @param {number} id - The subgroup invocation to broadcast from.
  28323. * @return {number} The broadcast value.
  28324. */
  28325. const subgroupBroadcastFirst = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST_FIRST ).setParameterLength( 2 );
  28326. /**
  28327. * Swaps e between invocations in the quad in the X direction.
  28328. *
  28329. * @method
  28330. * @param {number} e - The value to swap from the current invocation.
  28331. * @return {number} The value received from the swap operation.
  28332. */
  28333. const quadSwapX = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_X ).setParameterLength( 1 );
  28334. /**
  28335. * Swaps e between invocations in the quad in the Y direction.
  28336. *
  28337. * @method
  28338. * @param {number} e - The value to swap from the current invocation.
  28339. * @return {number} The value received from the swap operation.
  28340. */
  28341. const quadSwapY = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_Y ).setParameterLength( 1 );
  28342. /**
  28343. * Swaps e between invocations in the quad diagonally.
  28344. *
  28345. * @method
  28346. * @param {number} e - The value to swap from the current invocation.
  28347. * @return {number} The value received from the swap operation.
  28348. */
  28349. const quadSwapDiagonal = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_SWAP_DIAGONAL ).setParameterLength( 1 );
  28350. /**
  28351. * Broadcasts e from the invocation whose subgroup_invocation_id matches id, to all active invocations.
  28352. *
  28353. * @method
  28354. * @param {number} e - The value to broadcast from subgroup invocation 'id'.
  28355. * @param {number} id - The subgroup invocation to broadcast from.
  28356. * @return {number} The broadcast value.
  28357. */
  28358. const subgroupBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_BROADCAST ).setParameterLength( 2 );
  28359. /**
  28360. * Returns v from the active invocation whose subgroup_invocation_id matches id
  28361. *
  28362. * @method
  28363. * @param {number} v - The value to return from subgroup invocation id^mask.
  28364. * @param {number} id - The subgroup invocation which returns the value v.
  28365. * @return {number} The broadcast value.
  28366. */
  28367. const subgroupShuffle = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE ).setParameterLength( 2 );
  28368. /**
  28369. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id ^ mask.
  28370. *
  28371. * @method
  28372. * @param {number} v - The value to return from subgroup invocation id^mask.
  28373. * @param {number} mask - A bitmask that determines the target invocation via a XOR operation.
  28374. * @return {number} The broadcast value.
  28375. */
  28376. const subgroupShuffleXor = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_XOR ).setParameterLength( 2 );
  28377. /**
  28378. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id - delta
  28379. *
  28380. * @method
  28381. * @param {number} v - The value to return from subgroup invocation id^mask.
  28382. * @param {number} delta - A value that offsets the current in.
  28383. * @return {number} The broadcast value.
  28384. */
  28385. const subgroupShuffleUp = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_UP ).setParameterLength( 2 );
  28386. /**
  28387. * Returns v from the active invocation whose subgroup_invocation_id matches subgroup_invocation_id + delta
  28388. *
  28389. * @method
  28390. * @param {number} v - The value to return from subgroup invocation id^mask.
  28391. * @param {number} delta - A value that offsets the current subgroup invocation.
  28392. * @return {number} The broadcast value.
  28393. */
  28394. const subgroupShuffleDown = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.SUBGROUP_SHUFFLE_DOWN ).setParameterLength( 2 );
  28395. /**
  28396. * Broadcasts e from the quad invocation with id equal to id.
  28397. *
  28398. * @method
  28399. * @param {number} e - The value to broadcast.
  28400. * @return {number} The broadcast value.
  28401. */
  28402. const quadBroadcast = /*@__PURE__*/ nodeProxyIntent( SubgroupFunctionNode, SubgroupFunctionNode.QUAD_BROADCAST ).setParameterLength( 1 );
  28403. let uniformsLib;
  28404. function getLightData( light ) {
  28405. uniformsLib = uniformsLib || new WeakMap();
  28406. let uniforms = uniformsLib.get( light );
  28407. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  28408. return uniforms;
  28409. }
  28410. /**
  28411. * TSL function for getting a shadow matrix uniform node for the given light.
  28412. *
  28413. * @tsl
  28414. * @function
  28415. * @param {Light} light -The light source.
  28416. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  28417. */
  28418. function lightShadowMatrix( light ) {
  28419. const data = getLightData( light );
  28420. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  28421. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  28422. light.shadow.updateMatrices( light );
  28423. }
  28424. return light.shadow.matrix;
  28425. } ) );
  28426. }
  28427. /**
  28428. * TSL function for getting projected uv coordinates for the given light.
  28429. * Relevant when using maps with spot lights.
  28430. *
  28431. * @tsl
  28432. * @function
  28433. * @param {Light} light -The light source.
  28434. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  28435. * @returns {Node<vec3>} The projected uvs.
  28436. */
  28437. function lightProjectionUV( light, position = positionWorld ) {
  28438. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  28439. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  28440. return projectionUV;
  28441. }
  28442. /**
  28443. * TSL function for getting the position in world space for the given light.
  28444. *
  28445. * @tsl
  28446. * @function
  28447. * @param {Light} light -The light source.
  28448. * @returns {UniformNode<vec3>} The light's position in world space.
  28449. */
  28450. function lightPosition( light ) {
  28451. const data = getLightData( light );
  28452. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  28453. }
  28454. /**
  28455. * TSL function for getting the light target position in world space for the given light.
  28456. *
  28457. * @tsl
  28458. * @function
  28459. * @param {Light} light -The light source.
  28460. * @returns {UniformNode<vec3>} The light target position in world space.
  28461. */
  28462. function lightTargetPosition( light ) {
  28463. const data = getLightData( light );
  28464. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  28465. }
  28466. /**
  28467. * TSL function for getting the position in view space for the given light.
  28468. *
  28469. * @tsl
  28470. * @function
  28471. * @param {Light} light - The light source.
  28472. * @returns {UniformNode<vec3>} The light's position in view space.
  28473. */
  28474. function lightViewPosition( light ) {
  28475. const data = getLightData( light );
  28476. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  28477. self.value = self.value || new Vector3();
  28478. self.value.setFromMatrixPosition( light.matrixWorld );
  28479. self.value.applyMatrix4( camera.matrixWorldInverse );
  28480. } ) );
  28481. }
  28482. /**
  28483. * TSL function for getting the light target direction for the given light.
  28484. *
  28485. * @tsl
  28486. * @function
  28487. * @param {Light} light -The light source.
  28488. * @returns {Node<vec3>} The light's target direction.
  28489. */
  28490. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  28491. const sortLights = ( lights ) => {
  28492. return lights.sort( ( a, b ) => a.id - b.id );
  28493. };
  28494. const getLightNodeById = ( id, lightNodes ) => {
  28495. for ( const lightNode of lightNodes ) {
  28496. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  28497. return lightNode;
  28498. }
  28499. }
  28500. return null;
  28501. };
  28502. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  28503. const _hashData = [];
  28504. /**
  28505. * This node represents the scene's lighting and manages the lighting model's life cycle
  28506. * for the current build 3D object. It is responsible for computing the total outgoing
  28507. * light in a given lighting context.
  28508. *
  28509. * @augments Node
  28510. */
  28511. class LightsNode extends Node {
  28512. static get type() {
  28513. return 'LightsNode';
  28514. }
  28515. /**
  28516. * Constructs a new lights node.
  28517. */
  28518. constructor() {
  28519. super( 'vec3' );
  28520. /**
  28521. * A node representing the total diffuse light.
  28522. *
  28523. * @type {Node<vec3>}
  28524. */
  28525. this.totalDiffuseNode = property( 'vec3', 'totalDiffuse' );
  28526. /**
  28527. * A node representing the total specular light.
  28528. *
  28529. * @type {Node<vec3>}
  28530. */
  28531. this.totalSpecularNode = property( 'vec3', 'totalSpecular' );
  28532. /**
  28533. * A node representing the outgoing light.
  28534. *
  28535. * @type {Node<vec3>}
  28536. */
  28537. this.outgoingLightNode = property( 'vec3', 'outgoingLight' );
  28538. /**
  28539. * An array representing the lights in the scene.
  28540. *
  28541. * @private
  28542. * @type {Array<Light>}
  28543. */
  28544. this._lights = [];
  28545. /**
  28546. * For each light in the scene, this node will create a
  28547. * corresponding light node.
  28548. *
  28549. * @private
  28550. * @type {?Array<LightingNode>}
  28551. * @default null
  28552. */
  28553. this._lightNodes = null;
  28554. /**
  28555. * A hash for identifying the current light nodes setup.
  28556. *
  28557. * @private
  28558. * @type {?string}
  28559. * @default null
  28560. */
  28561. this._lightNodesHash = null;
  28562. /**
  28563. * `LightsNode` sets this property to `true` by default.
  28564. *
  28565. * @type {boolean}
  28566. * @default true
  28567. */
  28568. this.global = true;
  28569. }
  28570. /**
  28571. * Overwrites the default {@link Node#customCacheKey} implementation by including
  28572. * light data into the cache key.
  28573. *
  28574. * @return {number} The custom cache key.
  28575. */
  28576. customCacheKey() {
  28577. const lights = this._lights;
  28578. for ( let i = 0; i < lights.length; i ++ ) {
  28579. const light = lights[ i ];
  28580. _hashData.push( light.id );
  28581. _hashData.push( light.castShadow ? 1 : 0 );
  28582. if ( light.isSpotLight === true ) {
  28583. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  28584. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  28585. _hashData.push( hashMap, hashColorNode );
  28586. }
  28587. }
  28588. const cacheKey = hashArray( _hashData );
  28589. _hashData.length = 0;
  28590. return cacheKey;
  28591. }
  28592. /**
  28593. * Computes a hash value for identifying the current light nodes setup.
  28594. *
  28595. * @param {NodeBuilder} builder - A reference to the current node builder.
  28596. * @return {string} The computed hash.
  28597. */
  28598. getHash( builder ) {
  28599. if ( this._lightNodesHash === null ) {
  28600. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  28601. const hash = [];
  28602. for ( const lightNode of this._lightNodes ) {
  28603. hash.push( lightNode.getHash() );
  28604. }
  28605. this._lightNodesHash = 'lights-' + hash.join( ',' );
  28606. }
  28607. return this._lightNodesHash;
  28608. }
  28609. analyze( builder ) {
  28610. const properties = builder.getNodeProperties( this );
  28611. for ( const node of properties.nodes ) {
  28612. node.build( builder );
  28613. }
  28614. properties.outputNode.build( builder );
  28615. }
  28616. /**
  28617. * Creates lighting nodes for each scene light. This makes it possible to further
  28618. * process lights in the node system.
  28619. *
  28620. * @param {NodeBuilder} builder - A reference to the current node builder.
  28621. */
  28622. setupLightsNode( builder ) {
  28623. const lightNodes = [];
  28624. const previousLightNodes = this._lightNodes;
  28625. const lights = sortLights( this._lights );
  28626. const nodeLibrary = builder.renderer.library;
  28627. for ( const light of lights ) {
  28628. if ( light.isNode ) {
  28629. lightNodes.push( nodeObject( light ) );
  28630. } else {
  28631. let lightNode = null;
  28632. if ( previousLightNodes !== null ) {
  28633. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  28634. }
  28635. if ( lightNode === null ) {
  28636. // find the corresponding node type for a given light
  28637. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  28638. if ( lightNodeClass === null ) {
  28639. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  28640. continue;
  28641. }
  28642. let lightNode = null;
  28643. if ( ! _lightsNodeRef.has( light ) ) {
  28644. lightNode = nodeObject( new lightNodeClass( light ) );
  28645. _lightsNodeRef.set( light, lightNode );
  28646. } else {
  28647. lightNode = _lightsNodeRef.get( light );
  28648. }
  28649. lightNodes.push( lightNode );
  28650. }
  28651. }
  28652. }
  28653. this._lightNodes = lightNodes;
  28654. }
  28655. /**
  28656. * Sets up a direct light in the lighting model.
  28657. *
  28658. * @param {Object} builder - The builder object containing the context and stack.
  28659. * @param {Object} lightNode - The light node.
  28660. * @param {Object} lightData - The light object containing color and direction properties.
  28661. */
  28662. setupDirectLight( builder, lightNode, lightData ) {
  28663. const { lightingModel, reflectedLight } = builder.context;
  28664. lightingModel.direct( {
  28665. ...lightData,
  28666. lightNode,
  28667. reflectedLight
  28668. }, builder );
  28669. }
  28670. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  28671. const { lightingModel, reflectedLight } = builder.context;
  28672. lightingModel.directRectArea( {
  28673. ...lightData,
  28674. lightNode,
  28675. reflectedLight
  28676. }, builder );
  28677. }
  28678. /**
  28679. * Setups the internal lights by building all respective
  28680. * light nodes.
  28681. *
  28682. * @param {NodeBuilder} builder - A reference to the current node builder.
  28683. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  28684. */
  28685. setupLights( builder, lightNodes ) {
  28686. for ( const lightNode of lightNodes ) {
  28687. lightNode.build( builder );
  28688. }
  28689. }
  28690. getLightNodes( builder ) {
  28691. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  28692. return this._lightNodes;
  28693. }
  28694. /**
  28695. * The implementation makes sure that for each light in the scene
  28696. * there is a corresponding light node. By building the light nodes
  28697. * and evaluating the lighting model the outgoing light is computed.
  28698. *
  28699. * @param {NodeBuilder} builder - A reference to the current node builder.
  28700. * @return {Node<vec3>} A node representing the outgoing light.
  28701. */
  28702. setup( builder ) {
  28703. const currentLightsNode = builder.lightsNode;
  28704. builder.lightsNode = this;
  28705. //
  28706. let outgoingLightNode = this.outgoingLightNode;
  28707. const context = builder.context;
  28708. const lightingModel = context.lightingModel;
  28709. const properties = builder.getNodeProperties( this );
  28710. if ( lightingModel ) {
  28711. const { totalDiffuseNode, totalSpecularNode } = this;
  28712. context.outgoingLight = outgoingLightNode;
  28713. const stack = builder.addStack();
  28714. //
  28715. properties.nodes = stack.nodes;
  28716. //
  28717. lightingModel.start( builder );
  28718. //
  28719. const { backdrop, backdropAlpha } = context;
  28720. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  28721. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  28722. if ( backdrop !== null ) {
  28723. if ( backdropAlpha !== null ) {
  28724. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  28725. } else {
  28726. totalDiffuse = vec3( backdrop );
  28727. }
  28728. context.material.transparent = true;
  28729. }
  28730. totalDiffuseNode.assign( totalDiffuse );
  28731. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  28732. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  28733. //
  28734. lightingModel.finish( builder );
  28735. //
  28736. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  28737. } else {
  28738. properties.nodes = [];
  28739. }
  28740. //
  28741. builder.lightsNode = currentLightsNode;
  28742. return outgoingLightNode;
  28743. }
  28744. /**
  28745. * Configures this node with an array of lights.
  28746. *
  28747. * @param {Array<Light>} lights - An array of lights.
  28748. * @return {LightsNode} A reference to this node.
  28749. */
  28750. setLights( lights ) {
  28751. this._lights = lights;
  28752. this._lightNodes = null;
  28753. this._lightNodesHash = null;
  28754. return this;
  28755. }
  28756. /**
  28757. * Returns an array of the scene's lights.
  28758. *
  28759. * @return {Array<Light>} The scene's lights.
  28760. */
  28761. getLights() {
  28762. return this._lights;
  28763. }
  28764. /**
  28765. * Whether the scene has lights or not.
  28766. *
  28767. * @type {boolean}
  28768. */
  28769. get hasLights() {
  28770. return this._lights.length > 0;
  28771. }
  28772. }
  28773. /**
  28774. * TSL function for creating an instance of `LightsNode` and configuring
  28775. * it with the given array of lights.
  28776. *
  28777. * @tsl
  28778. * @function
  28779. * @param {Array<Light>} lights - An array of lights.
  28780. * @return {LightsNode} The created lights node.
  28781. */
  28782. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  28783. /**
  28784. * Base class for all shadow nodes.
  28785. *
  28786. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  28787. * Lighting nodes might share the same shadow node type or use specific ones depending on
  28788. * their requirements.
  28789. *
  28790. * @augments Node
  28791. */
  28792. class ShadowBaseNode extends Node {
  28793. static get type() {
  28794. return 'ShadowBaseNode';
  28795. }
  28796. /**
  28797. * Constructs a new shadow base node.
  28798. *
  28799. * @param {Light} light - The shadow casting light.
  28800. */
  28801. constructor( light ) {
  28802. super();
  28803. /**
  28804. * The shadow casting light.
  28805. *
  28806. * @type {Light}
  28807. */
  28808. this.light = light;
  28809. /**
  28810. * Overwritten since shadows are updated by default per render.
  28811. *
  28812. * @type {string}
  28813. * @default 'render'
  28814. */
  28815. this.updateBeforeType = NodeUpdateType.RENDER;
  28816. /**
  28817. * This flag can be used for type testing.
  28818. *
  28819. * @type {boolean}
  28820. * @readonly
  28821. * @default true
  28822. */
  28823. this.isShadowBaseNode = true;
  28824. }
  28825. /**
  28826. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  28827. *
  28828. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  28829. */
  28830. setupShadowPosition( { context, material } ) {
  28831. // Use assign inside an Fn()
  28832. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  28833. }
  28834. }
  28835. /**
  28836. * TSL object that represents the vertex position in world space during the shadow pass.
  28837. *
  28838. * @tsl
  28839. * @type {Node<vec3>}
  28840. */
  28841. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  28842. /**
  28843. * Saves the state of the given renderer and stores it into the given state object.
  28844. *
  28845. * If not state object is provided, the function creates one.
  28846. *
  28847. * @function
  28848. * @param {Renderer} renderer - The renderer.
  28849. * @param {Object} [state={}] - The state.
  28850. * @return {Object} The state.
  28851. */
  28852. function saveRendererState( renderer, state = {} ) {
  28853. state.toneMapping = renderer.toneMapping;
  28854. state.toneMappingExposure = renderer.toneMappingExposure;
  28855. state.outputColorSpace = renderer.outputColorSpace;
  28856. state.renderTarget = renderer.getRenderTarget();
  28857. state.activeCubeFace = renderer.getActiveCubeFace();
  28858. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  28859. state.renderObjectFunction = renderer.getRenderObjectFunction();
  28860. state.pixelRatio = renderer.getPixelRatio();
  28861. state.mrt = renderer.getMRT();
  28862. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  28863. state.clearAlpha = renderer.getClearAlpha();
  28864. state.autoClear = renderer.autoClear;
  28865. state.scissorTest = renderer.getScissorTest();
  28866. return state;
  28867. }
  28868. /**
  28869. * Saves the state of the given renderer and stores it into the given state object.
  28870. * Besides, the function also resets the state of the renderer to its default values.
  28871. *
  28872. * If not state object is provided, the function creates one.
  28873. *
  28874. * @function
  28875. * @param {Renderer} renderer - The renderer.
  28876. * @param {Object} [state={}] - The state.
  28877. * @return {Object} The state.
  28878. */
  28879. function resetRendererState( renderer, state ) {
  28880. state = saveRendererState( renderer, state );
  28881. renderer.setMRT( null );
  28882. renderer.setRenderObjectFunction( null );
  28883. renderer.setClearColor( 0x000000, 1 );
  28884. renderer.autoClear = true;
  28885. return state;
  28886. }
  28887. /**
  28888. * Restores the state of the given renderer from the given state object.
  28889. *
  28890. * @function
  28891. * @param {Renderer} renderer - The renderer.
  28892. * @param {Object} state - The state to restore.
  28893. */
  28894. function restoreRendererState( renderer, state ) {
  28895. renderer.toneMapping = state.toneMapping;
  28896. renderer.toneMappingExposure = state.toneMappingExposure;
  28897. renderer.outputColorSpace = state.outputColorSpace;
  28898. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  28899. renderer.setRenderObjectFunction( state.renderObjectFunction );
  28900. renderer.setPixelRatio( state.pixelRatio );
  28901. renderer.setMRT( state.mrt );
  28902. renderer.setClearColor( state.clearColor, state.clearAlpha );
  28903. renderer.autoClear = state.autoClear;
  28904. renderer.setScissorTest( state.scissorTest );
  28905. }
  28906. /**
  28907. * Saves the state of the given scene and stores it into the given state object.
  28908. *
  28909. * If not state object is provided, the function creates one.
  28910. *
  28911. * @function
  28912. * @param {Scene} scene - The scene.
  28913. * @param {Object} [state={}] - The state.
  28914. * @return {Object} The state.
  28915. */
  28916. function saveSceneState( scene, state = {} ) {
  28917. state.background = scene.background;
  28918. state.backgroundNode = scene.backgroundNode;
  28919. state.overrideMaterial = scene.overrideMaterial;
  28920. return state;
  28921. }
  28922. /**
  28923. * Saves the state of the given scene and stores it into the given state object.
  28924. * Besides, the function also resets the state of the scene to its default values.
  28925. *
  28926. * If not state object is provided, the function creates one.
  28927. *
  28928. * @function
  28929. * @param {Scene} scene - The scene.
  28930. * @param {Object} [state={}] - The state.
  28931. * @return {Object} The state.
  28932. */
  28933. function resetSceneState( scene, state ) {
  28934. state = saveSceneState( scene, state );
  28935. scene.background = null;
  28936. scene.backgroundNode = null;
  28937. scene.overrideMaterial = null;
  28938. return state;
  28939. }
  28940. /**
  28941. * Restores the state of the given scene from the given state object.
  28942. *
  28943. * @function
  28944. * @param {Scene} scene - The scene.
  28945. * @param {Object} state - The state to restore.
  28946. */
  28947. function restoreSceneState( scene, state ) {
  28948. scene.background = state.background;
  28949. scene.backgroundNode = state.backgroundNode;
  28950. scene.overrideMaterial = state.overrideMaterial;
  28951. }
  28952. /**
  28953. * Saves the state of the given renderer and scene and stores it into the given state object.
  28954. *
  28955. * If not state object is provided, the function creates one.
  28956. *
  28957. * @function
  28958. * @param {Renderer} renderer - The renderer.
  28959. * @param {Scene} scene - The scene.
  28960. * @param {Object} [state={}] - The state.
  28961. * @return {Object} The state.
  28962. */
  28963. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  28964. state = saveRendererState( renderer, state );
  28965. state = saveSceneState( scene, state );
  28966. return state;
  28967. }
  28968. /**
  28969. * Saves the state of the given renderer and scene and stores it into the given state object.
  28970. * Besides, the function also resets the state of the renderer and scene to its default values.
  28971. *
  28972. * If not state object is provided, the function creates one.
  28973. *
  28974. * @function
  28975. * @param {Renderer} renderer - The renderer.
  28976. * @param {Scene} scene - The scene.
  28977. * @param {Object} [state={}] - The state.
  28978. * @return {Object} The state.
  28979. */
  28980. function resetRendererAndSceneState( renderer, scene, state ) {
  28981. state = resetRendererState( renderer, state );
  28982. state = resetSceneState( scene, state );
  28983. return state;
  28984. }
  28985. /**
  28986. * Restores the state of the given renderer and scene from the given state object.
  28987. *
  28988. * @function
  28989. * @param {Renderer} renderer - The renderer.
  28990. * @param {Scene} scene - The scene.
  28991. * @param {Object} state - The state to restore.
  28992. */
  28993. function restoreRendererAndSceneState( renderer, scene, state ) {
  28994. restoreRendererState( renderer, state );
  28995. restoreSceneState( scene, state );
  28996. }
  28997. var RendererUtils = /*#__PURE__*/Object.freeze({
  28998. __proto__: null,
  28999. resetRendererAndSceneState: resetRendererAndSceneState,
  29000. resetRendererState: resetRendererState,
  29001. resetSceneState: resetSceneState,
  29002. restoreRendererAndSceneState: restoreRendererAndSceneState,
  29003. restoreRendererState: restoreRendererState,
  29004. restoreSceneState: restoreSceneState,
  29005. saveRendererAndSceneState: saveRendererAndSceneState,
  29006. saveRendererState: saveRendererState,
  29007. saveSceneState: saveSceneState
  29008. });
  29009. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  29010. /**
  29011. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  29012. * with a binary `[0,1]` result.
  29013. *
  29014. * @method
  29015. * @param {Object} inputs - The input parameter object.
  29016. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29017. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29018. * @return {Node<float>} The filtering result.
  29019. */
  29020. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  29021. let basic = texture( depthTexture, shadowCoord.xy ).setName( 't_basic' );
  29022. if ( depthTexture.isArrayTexture ) {
  29023. basic = basic.depth( depthLayer );
  29024. }
  29025. return basic.compare( shadowCoord.z );
  29026. } );
  29027. /**
  29028. * A shadow filtering function performing PCF filtering.
  29029. *
  29030. * @method
  29031. * @param {Object} inputs - The input parameter object.
  29032. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29033. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29034. * @param {LightShadow} inputs.shadow - The light shadow.
  29035. * @return {Node<float>} The filtering result.
  29036. */
  29037. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  29038. const depthCompare = ( uv, compare ) => {
  29039. let depth = texture( depthTexture, uv );
  29040. if ( depthTexture.isArrayTexture ) {
  29041. depth = depth.depth( depthLayer );
  29042. }
  29043. return depth.compare( compare );
  29044. };
  29045. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29046. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  29047. const texelSize = vec2( 1 ).div( mapSize );
  29048. const dx0 = texelSize.x.negate().mul( radius );
  29049. const dy0 = texelSize.y.negate().mul( radius );
  29050. const dx1 = texelSize.x.mul( radius );
  29051. const dy1 = texelSize.y.mul( radius );
  29052. const dx2 = dx0.div( 2 );
  29053. const dy2 = dy0.div( 2 );
  29054. const dx3 = dx1.div( 2 );
  29055. const dy3 = dy1.div( 2 );
  29056. return add(
  29057. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  29058. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  29059. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  29060. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  29061. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  29062. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  29063. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  29064. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  29065. depthCompare( shadowCoord.xy, shadowCoord.z ),
  29066. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  29067. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  29068. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  29069. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  29070. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  29071. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  29072. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  29073. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  29074. ).mul( 1 / 17 );
  29075. } );
  29076. /**
  29077. * A shadow filtering function performing PCF soft filtering.
  29078. *
  29079. * @method
  29080. * @param {Object} inputs - The input parameter object.
  29081. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29082. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29083. * @param {LightShadow} inputs.shadow - The light shadow.
  29084. * @return {Node<float>} The filtering result.
  29085. */
  29086. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  29087. const depthCompare = ( uv, compare ) => {
  29088. let depth = texture( depthTexture, uv );
  29089. if ( depthTexture.isArrayTexture ) {
  29090. depth = depth.depth( depthLayer );
  29091. }
  29092. return depth.compare( compare );
  29093. };
  29094. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29095. const texelSize = vec2( 1 ).div( mapSize );
  29096. const dx = texelSize.x;
  29097. const dy = texelSize.y;
  29098. const uv = shadowCoord.xy;
  29099. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  29100. uv.subAssign( f.mul( texelSize ) );
  29101. return add(
  29102. depthCompare( uv, shadowCoord.z ),
  29103. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  29104. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  29105. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  29106. mix(
  29107. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  29108. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  29109. f.x
  29110. ),
  29111. mix(
  29112. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  29113. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  29114. f.x
  29115. ),
  29116. mix(
  29117. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  29118. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  29119. f.y
  29120. ),
  29121. mix(
  29122. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  29123. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  29124. f.y
  29125. ),
  29126. mix(
  29127. mix(
  29128. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  29129. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  29130. f.x
  29131. ),
  29132. mix(
  29133. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  29134. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  29135. f.x
  29136. ),
  29137. f.y
  29138. )
  29139. ).mul( 1 / 9 );
  29140. } );
  29141. /**
  29142. * A shadow filtering function performing VSM filtering.
  29143. *
  29144. * @method
  29145. * @param {Object} inputs - The input parameter object.
  29146. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29147. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  29148. * @return {Node<float>} The filtering result.
  29149. */
  29150. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  29151. const occlusion = float( 1 ).toVar();
  29152. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  29153. if ( depthTexture.isArrayTexture ) {
  29154. distribution = distribution.depth( depthLayer );
  29155. }
  29156. distribution = distribution.rg;
  29157. const hardShadow = step( shadowCoord.z, distribution.x );
  29158. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  29159. const distance = shadowCoord.z.sub( distribution.x );
  29160. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  29161. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  29162. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  29163. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  29164. } );
  29165. return occlusion;
  29166. } );
  29167. //
  29168. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  29169. let dist = positionWorld.sub( position ).length();
  29170. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  29171. dist = dist.saturate(); // clamp to [ 0, 1 ]
  29172. return dist;
  29173. } );
  29174. const linearShadowDistance = ( light ) => {
  29175. const camera = light.shadow.camera;
  29176. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  29177. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  29178. const referencePosition = objectPosition( light );
  29179. return linearDistance( referencePosition, nearDistance, farDistance );
  29180. };
  29181. /**
  29182. * Retrieves or creates a shadow material for the given light source.
  29183. *
  29184. * This function checks if a shadow material already exists for the provided light.
  29185. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  29186. * in the `shadowMaterialLib` for future use.
  29187. *
  29188. * @param {Light} light - The light source for which the shadow material is needed.
  29189. * If the light is a point light, a depth node is calculated
  29190. * using the linear shadow distance.
  29191. * @returns {NodeMaterial} The shadow material associated with the given light.
  29192. */
  29193. const getShadowMaterial = ( light ) => {
  29194. let material = shadowMaterialLib.get( light );
  29195. if ( material === undefined ) {
  29196. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  29197. material = new NodeMaterial();
  29198. material.colorNode = vec4( 0, 0, 0, 1 );
  29199. material.depthNode = depthNode;
  29200. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  29201. material.name = 'ShadowMaterial';
  29202. material.fog = false;
  29203. shadowMaterialLib.set( light, material );
  29204. }
  29205. return material;
  29206. };
  29207. //
  29208. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  29209. const _shadowRenderObjectKeys = [];
  29210. /**
  29211. * Creates a function to render shadow objects in a scene.
  29212. *
  29213. * @param {Renderer} renderer - The renderer.
  29214. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  29215. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  29216. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  29217. * @return {Function} A function that renders shadow objects.
  29218. *
  29219. * The returned function has the following parameters:
  29220. * @param {Object3D} object - The 3D object to render.
  29221. * @param {Scene} scene - The scene containing the object.
  29222. * @param {Camera} _camera - The camera used for rendering.
  29223. * @param {BufferGeometry} geometry - The geometry of the object.
  29224. * @param {Material} material - The material of the object.
  29225. * @param {Group} group - The group the object belongs to.
  29226. * @param {...any} params - Additional parameters for rendering.
  29227. */
  29228. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  29229. _shadowRenderObjectKeys[ 0 ] = renderer;
  29230. _shadowRenderObjectKeys[ 1 ] = shadow;
  29231. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  29232. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  29233. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  29234. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  29235. if ( useVelocity ) {
  29236. getDataFromObject( object ).useVelocity = true;
  29237. }
  29238. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  29239. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  29240. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  29241. }
  29242. };
  29243. renderObjectFunction.shadowType = shadowType;
  29244. renderObjectFunction.useVelocity = useVelocity;
  29245. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  29246. }
  29247. _shadowRenderObjectKeys[ 0 ] = null;
  29248. _shadowRenderObjectKeys[ 1 ] = null;
  29249. return renderObjectFunction;
  29250. };
  29251. /**
  29252. * Represents the shader code for the first VSM render pass.
  29253. *
  29254. * @method
  29255. * @param {Object} inputs - The input parameter object.
  29256. * @param {Node<float>} inputs.samples - The number of samples
  29257. * @param {Node<float>} inputs.radius - The radius.
  29258. * @param {Node<float>} inputs.size - The size.
  29259. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  29260. * @return {Node<vec2>} The VSM output.
  29261. */
  29262. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  29263. const mean = float( 0 ).toVar( 'meanVertical' );
  29264. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  29265. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  29266. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  29267. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  29268. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  29269. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  29270. if ( shadowPass.value.isArrayTexture ) {
  29271. depth = depth.depth( depthLayer );
  29272. }
  29273. depth = depth.x;
  29274. mean.addAssign( depth );
  29275. squaredMean.addAssign( depth.mul( depth ) );
  29276. } );
  29277. mean.divAssign( samples );
  29278. squaredMean.divAssign( samples );
  29279. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  29280. return vec2( mean, std_dev );
  29281. } );
  29282. /**
  29283. * Represents the shader code for the second VSM render pass.
  29284. *
  29285. * @method
  29286. * @param {Object} inputs - The input parameter object.
  29287. * @param {Node<float>} inputs.samples - The number of samples
  29288. * @param {Node<float>} inputs.radius - The radius.
  29289. * @param {Node<float>} inputs.size - The size.
  29290. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  29291. * @return {Node<vec2>} The VSM output.
  29292. */
  29293. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  29294. const mean = float( 0 ).toVar( 'meanHorizontal' );
  29295. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  29296. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  29297. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  29298. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  29299. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  29300. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  29301. if ( shadowPass.value.isArrayTexture ) {
  29302. distribution = distribution.depth( depthLayer );
  29303. }
  29304. mean.addAssign( distribution.x );
  29305. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  29306. } );
  29307. mean.divAssign( samples );
  29308. squaredMean.divAssign( samples );
  29309. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  29310. return vec2( mean, std_dev );
  29311. } );
  29312. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  29313. //
  29314. let _rendererState;
  29315. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  29316. /**
  29317. * Represents the default shadow implementation for lighting nodes.
  29318. *
  29319. * @augments ShadowBaseNode
  29320. */
  29321. class ShadowNode extends ShadowBaseNode {
  29322. static get type() {
  29323. return 'ShadowNode';
  29324. }
  29325. /**
  29326. * Constructs a new shadow node.
  29327. *
  29328. * @param {Light} light - The shadow casting light.
  29329. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  29330. */
  29331. constructor( light, shadow = null ) {
  29332. super( light );
  29333. /**
  29334. * The light shadow which defines the properties light's
  29335. * shadow.
  29336. *
  29337. * @type {?LightShadow}
  29338. * @default null
  29339. */
  29340. this.shadow = shadow || light.shadow;
  29341. /**
  29342. * A reference to the shadow map which is a render target.
  29343. *
  29344. * @type {?RenderTarget}
  29345. * @default null
  29346. */
  29347. this.shadowMap = null;
  29348. /**
  29349. * Only relevant for VSM shadows. Render target for the
  29350. * first VSM render pass.
  29351. *
  29352. * @type {?RenderTarget}
  29353. * @default null
  29354. */
  29355. this.vsmShadowMapVertical = null;
  29356. /**
  29357. * Only relevant for VSM shadows. Render target for the
  29358. * second VSM render pass.
  29359. *
  29360. * @type {?RenderTarget}
  29361. * @default null
  29362. */
  29363. this.vsmShadowMapHorizontal = null;
  29364. /**
  29365. * Only relevant for VSM shadows. Node material which
  29366. * is used to render the first VSM pass.
  29367. *
  29368. * @type {?NodeMaterial}
  29369. * @default null
  29370. */
  29371. this.vsmMaterialVertical = null;
  29372. /**
  29373. * Only relevant for VSM shadows. Node material which
  29374. * is used to render the second VSM pass.
  29375. *
  29376. * @type {?NodeMaterial}
  29377. * @default null
  29378. */
  29379. this.vsmMaterialHorizontal = null;
  29380. /**
  29381. * A reference to the output node which defines the
  29382. * final result of this shadow node.
  29383. *
  29384. * @type {?Node}
  29385. * @private
  29386. * @default null
  29387. */
  29388. this._node = null;
  29389. this._cameraFrameId = new WeakMap();
  29390. /**
  29391. * This flag can be used for type testing.
  29392. *
  29393. * @type {boolean}
  29394. * @readonly
  29395. * @default true
  29396. */
  29397. this.isShadowNode = true;
  29398. /**
  29399. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  29400. *
  29401. * @type {number}
  29402. * @readonly
  29403. * @default true
  29404. */
  29405. this.depthLayer = 0;
  29406. }
  29407. /**
  29408. * Setups the shadow filtering.
  29409. *
  29410. * @param {NodeBuilder} builder - A reference to the current node builder.
  29411. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  29412. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  29413. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29414. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  29415. * @param {LightShadow} inputs.shadow - The light shadow.
  29416. * @return {Node<float>} The result node of the shadow filtering.
  29417. */
  29418. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  29419. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  29420. .and( shadowCoord.x.lessThanEqual( 1 ) )
  29421. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  29422. .and( shadowCoord.y.lessThanEqual( 1 ) )
  29423. .and( shadowCoord.z.lessThanEqual( 1 ) );
  29424. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  29425. return frustumTest.select( shadowNode, float( 1 ) );
  29426. }
  29427. /**
  29428. * Setups the shadow coordinates.
  29429. *
  29430. * @param {NodeBuilder} builder - A reference to the current node builder.
  29431. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  29432. * @return {Node<vec3>} The shadow coordinates.
  29433. */
  29434. setupShadowCoord( builder, shadowPosition ) {
  29435. const { shadow } = this;
  29436. const { renderer } = builder;
  29437. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  29438. let shadowCoord = shadowPosition;
  29439. let coordZ;
  29440. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  29441. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  29442. coordZ = shadowCoord.z;
  29443. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  29444. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  29445. }
  29446. } else {
  29447. const w = shadowCoord.w;
  29448. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  29449. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  29450. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  29451. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  29452. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  29453. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  29454. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  29455. }
  29456. shadowCoord = vec3(
  29457. shadowCoord.x,
  29458. shadowCoord.y.oneMinus(), // follow webgpu standards
  29459. coordZ.add( bias )
  29460. );
  29461. return shadowCoord;
  29462. }
  29463. /**
  29464. * Returns the shadow filtering function for the given shadow type.
  29465. *
  29466. * @param {number} type - The shadow type.
  29467. * @return {Function} The filtering function.
  29468. */
  29469. getShadowFilterFn( type ) {
  29470. return _shadowFilterLib[ type ];
  29471. }
  29472. setupRenderTarget( shadow, builder ) {
  29473. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  29474. depthTexture.name = 'ShadowDepthTexture';
  29475. depthTexture.compareFunction = LessCompare;
  29476. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  29477. shadowMap.texture.name = 'ShadowMap';
  29478. shadowMap.texture.type = shadow.mapType;
  29479. shadowMap.depthTexture = depthTexture;
  29480. return { shadowMap, depthTexture };
  29481. }
  29482. /**
  29483. * Setups the shadow output node.
  29484. *
  29485. * @param {NodeBuilder} builder - A reference to the current node builder.
  29486. * @return {Node<vec3>} The shadow output node.
  29487. */
  29488. setupShadow( builder ) {
  29489. const { renderer } = builder;
  29490. const { light, shadow } = this;
  29491. const shadowMapType = renderer.shadowMap.type;
  29492. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  29493. shadow.camera.updateProjectionMatrix();
  29494. // VSM
  29495. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  29496. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  29497. if ( shadowMap.depth > 1 ) {
  29498. if ( ! shadowMap._vsmShadowMapVertical ) {
  29499. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  29500. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  29501. }
  29502. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  29503. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  29504. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  29505. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  29506. }
  29507. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  29508. } else {
  29509. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  29510. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  29511. }
  29512. let shadowPassVertical = texture( depthTexture );
  29513. if ( depthTexture.isArrayTexture ) {
  29514. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  29515. }
  29516. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  29517. if ( depthTexture.isArrayTexture ) {
  29518. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  29519. }
  29520. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  29521. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  29522. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  29523. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  29524. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  29525. material.name = 'VSMVertical';
  29526. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  29527. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  29528. material.name = 'VSMHorizontal';
  29529. }
  29530. //
  29531. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  29532. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  29533. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( normalWorld.mul( normalBias ) ) );
  29534. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  29535. //
  29536. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  29537. if ( filterFn === null ) {
  29538. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  29539. }
  29540. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  29541. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  29542. let shadowColor = texture( shadowMap.texture, shadowCoord );
  29543. if ( depthTexture.isArrayTexture ) {
  29544. shadowColor = shadowColor.depth( this.depthLayer );
  29545. }
  29546. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  29547. this.shadowMap = shadowMap;
  29548. this.shadow.map = shadowMap;
  29549. return shadowOutput;
  29550. }
  29551. /**
  29552. * The implementation performs the setup of the output node. An output is only
  29553. * produces if shadow mapping is globally enabled in the renderer.
  29554. *
  29555. * @param {NodeBuilder} builder - A reference to the current node builder.
  29556. * @return {ShaderCallNodeInternal} The output node.
  29557. */
  29558. setup( builder ) {
  29559. if ( builder.renderer.shadowMap.enabled === false ) return;
  29560. return Fn( () => {
  29561. let node = this._node;
  29562. this.setupShadowPosition( builder );
  29563. if ( node === null ) {
  29564. this._node = node = this.setupShadow( builder );
  29565. }
  29566. if ( builder.material.shadowNode ) { // @deprecated, r171
  29567. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  29568. }
  29569. if ( builder.material.receivedShadowNode ) {
  29570. node = builder.material.receivedShadowNode( node );
  29571. }
  29572. return node;
  29573. } )();
  29574. }
  29575. /**
  29576. * Renders the shadow. The logic of this function could be included
  29577. * into {@link ShadowNode#updateShadow} however more specialized shadow
  29578. * nodes might require a custom shadow map rendering. By having a
  29579. * dedicated method, it's easier to overwrite the default behavior.
  29580. *
  29581. * @param {NodeFrame} frame - A reference to the current node frame.
  29582. */
  29583. renderShadow( frame ) {
  29584. const { shadow, shadowMap, light } = this;
  29585. const { renderer, scene } = frame;
  29586. shadow.updateMatrices( light );
  29587. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  29588. renderer.render( scene, shadow.camera );
  29589. }
  29590. /**
  29591. * Updates the shadow.
  29592. *
  29593. * @param {NodeFrame} frame - A reference to the current node frame.
  29594. */
  29595. updateShadow( frame ) {
  29596. const { shadowMap, light, shadow } = this;
  29597. const { renderer, scene, camera } = frame;
  29598. const shadowType = renderer.shadowMap.type;
  29599. const depthVersion = shadowMap.depthTexture.version;
  29600. this._depthVersionCached = depthVersion;
  29601. const _shadowCameraLayer = shadow.camera.layers.mask;
  29602. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  29603. shadow.camera.layers.mask = camera.layers.mask;
  29604. }
  29605. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  29606. const currentMRT = renderer.getMRT();
  29607. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  29608. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  29609. scene.overrideMaterial = getShadowMaterial( light );
  29610. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  29611. renderer.setClearColor( 0x000000, 0 );
  29612. renderer.setRenderTarget( shadowMap );
  29613. this.renderShadow( frame );
  29614. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  29615. // vsm blur pass
  29616. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  29617. this.vsmPass( renderer );
  29618. }
  29619. shadow.camera.layers.mask = _shadowCameraLayer;
  29620. restoreRendererAndSceneState( renderer, scene, _rendererState );
  29621. }
  29622. /**
  29623. * For VSM additional render passes are required.
  29624. *
  29625. * @param {Renderer} renderer - A reference to the current renderer.
  29626. */
  29627. vsmPass( renderer ) {
  29628. const { shadow } = this;
  29629. const depth = this.shadowMap.depth;
  29630. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  29631. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  29632. renderer.setRenderTarget( this.vsmShadowMapVertical );
  29633. _quadMesh.material = this.vsmMaterialVertical;
  29634. _quadMesh.render( renderer );
  29635. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  29636. _quadMesh.material = this.vsmMaterialHorizontal;
  29637. _quadMesh.render( renderer );
  29638. }
  29639. /**
  29640. * Frees the internal resources of this shadow node.
  29641. */
  29642. dispose() {
  29643. this.shadowMap.dispose();
  29644. this.shadowMap = null;
  29645. if ( this.vsmShadowMapVertical !== null ) {
  29646. this.vsmShadowMapVertical.dispose();
  29647. this.vsmShadowMapVertical = null;
  29648. this.vsmMaterialVertical.dispose();
  29649. this.vsmMaterialVertical = null;
  29650. }
  29651. if ( this.vsmShadowMapHorizontal !== null ) {
  29652. this.vsmShadowMapHorizontal.dispose();
  29653. this.vsmShadowMapHorizontal = null;
  29654. this.vsmMaterialHorizontal.dispose();
  29655. this.vsmMaterialHorizontal = null;
  29656. }
  29657. super.dispose();
  29658. }
  29659. /**
  29660. * The implementation performs the update of the shadow map if necessary.
  29661. *
  29662. * @param {NodeFrame} frame - A reference to the current node frame.
  29663. */
  29664. updateBefore( frame ) {
  29665. const { shadow } = this;
  29666. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  29667. if ( needsUpdate ) {
  29668. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  29669. needsUpdate = false;
  29670. }
  29671. this._cameraFrameId[ frame.camera ] = frame.frameId;
  29672. }
  29673. if ( needsUpdate ) {
  29674. this.updateShadow( frame );
  29675. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  29676. shadow.needsUpdate = false;
  29677. }
  29678. }
  29679. }
  29680. }
  29681. /**
  29682. * TSL function for creating an instance of `ShadowNode`.
  29683. *
  29684. * @tsl
  29685. * @function
  29686. * @param {Light} light - The shadow casting light.
  29687. * @param {?LightShadow} [shadow] - The light shadow.
  29688. * @return {ShadowNode} The created shadow node.
  29689. */
  29690. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  29691. const _clearColor$1 = /*@__PURE__*/ new Color();
  29692. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  29693. // vector suitable for 2D texture mapping. This code uses the following layout for the
  29694. // 2D texture:
  29695. //
  29696. // xzXZ
  29697. // y Y
  29698. //
  29699. // Y - Positive y direction
  29700. // y - Negative y direction
  29701. // X - Positive x direction
  29702. // x - Negative x direction
  29703. // Z - Positive z direction
  29704. // z - Negative z direction
  29705. //
  29706. // Source and test bed:
  29707. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  29708. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  29709. const v = pos.toVar();
  29710. // Number of texels to avoid at the edge of each square
  29711. const absV = abs( v );
  29712. // Intersect unit cube
  29713. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  29714. absV.mulAssign( scaleToCube );
  29715. // Apply scale to avoid seams
  29716. // two texels less per square (one texel will do for NEAREST)
  29717. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  29718. // Unwrap
  29719. // space: -1 ... 1 range for each square
  29720. //
  29721. // #X## dim := ( 4 , 2 )
  29722. // # # center := ( 1 , 1 )
  29723. const planar = vec2( v.xy ).toVar();
  29724. const almostATexel = texelSizeY.mul( 1.5 );
  29725. const almostOne = almostATexel.oneMinus();
  29726. If( absV.z.greaterThanEqual( almostOne ), () => {
  29727. If( v.z.greaterThan( 0.0 ), () => {
  29728. planar.x.assign( sub( 4.0, v.x ) );
  29729. } );
  29730. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  29731. const signX = sign( v.x );
  29732. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  29733. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  29734. const signY = sign( v.y );
  29735. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  29736. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  29737. } );
  29738. // Transform to UV space
  29739. // scale := 0.5 / dim
  29740. // translate := ( center + 0.5 ) / dim
  29741. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  29742. } ).setLayout( {
  29743. name: 'cubeToUV',
  29744. type: 'vec2',
  29745. inputs: [
  29746. { name: 'pos', type: 'vec3' },
  29747. { name: 'texelSizeY', type: 'float' }
  29748. ]
  29749. } );
  29750. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  29751. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  29752. } );
  29753. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  29754. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  29755. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  29756. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  29757. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  29758. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  29759. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  29760. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  29761. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  29762. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  29763. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  29764. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  29765. .mul( 1.0 / 9.0 );
  29766. } );
  29767. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  29768. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  29769. // the vector from the light to the world-space position of the fragment.
  29770. const lightToPosition = shadowCoord.xyz.toVar();
  29771. const lightToPositionLength = lightToPosition.length();
  29772. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  29773. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  29774. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  29775. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  29776. const result = float( 1.0 ).toVar();
  29777. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  29778. // dp = normalized distance from light to fragment position
  29779. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  29780. dp.addAssign( bias );
  29781. // bd3D = base direction 3D
  29782. const bd3D = lightToPosition.normalize();
  29783. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  29784. // percentage-closer filtering
  29785. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  29786. } );
  29787. return result;
  29788. } );
  29789. const _viewport = /*@__PURE__*/ new Vector4();
  29790. const _viewportSize = /*@__PURE__*/ new Vector2();
  29791. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  29792. /**
  29793. * Represents the shadow implementation for point light nodes.
  29794. *
  29795. * @augments ShadowNode
  29796. */
  29797. class PointShadowNode extends ShadowNode {
  29798. static get type() {
  29799. return 'PointShadowNode';
  29800. }
  29801. /**
  29802. * Constructs a new point shadow node.
  29803. *
  29804. * @param {PointLight} light - The shadow casting point light.
  29805. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  29806. */
  29807. constructor( light, shadow = null ) {
  29808. super( light, shadow );
  29809. }
  29810. /**
  29811. * Overwrites the default implementation to return point light shadow specific
  29812. * filtering functions.
  29813. *
  29814. * @param {number} type - The shadow type.
  29815. * @return {Function} The filtering function.
  29816. */
  29817. getShadowFilterFn( type ) {
  29818. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  29819. }
  29820. /**
  29821. * Overwrites the default implementation so the unaltered shadow position is used.
  29822. *
  29823. * @param {NodeBuilder} builder - A reference to the current node builder.
  29824. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  29825. * @return {Node<vec3>} The shadow coordinates.
  29826. */
  29827. setupShadowCoord( builder, shadowPosition ) {
  29828. return shadowPosition;
  29829. }
  29830. /**
  29831. * Overwrites the default implementation to only use point light specific
  29832. * shadow filter functions.
  29833. *
  29834. * @param {NodeBuilder} builder - A reference to the current node builder.
  29835. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  29836. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  29837. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  29838. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  29839. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  29840. * @param {LightShadow} inputs.shadow - The light shadow.
  29841. * @return {Node<float>} The result node of the shadow filtering.
  29842. */
  29843. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  29844. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  29845. }
  29846. /**
  29847. * Overwrites the default implementation with point light specific
  29848. * rendering code.
  29849. *
  29850. * @param {NodeFrame} frame - A reference to the current node frame.
  29851. */
  29852. renderShadow( frame ) {
  29853. const { shadow, shadowMap, light } = this;
  29854. const { renderer, scene } = frame;
  29855. const shadowFrameExtents = shadow.getFrameExtents();
  29856. _shadowMapSize.copy( shadow.mapSize );
  29857. _shadowMapSize.multiply( shadowFrameExtents );
  29858. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  29859. _viewportSize.copy( shadow.mapSize );
  29860. //
  29861. const previousAutoClear = renderer.autoClear;
  29862. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  29863. const previousClearAlpha = renderer.getClearAlpha();
  29864. renderer.autoClear = false;
  29865. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  29866. renderer.clear();
  29867. const viewportCount = shadow.getViewportCount();
  29868. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  29869. const viewport = shadow.getViewport( vp );
  29870. const x = _viewportSize.x * viewport.x;
  29871. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  29872. _viewport.set(
  29873. x,
  29874. y,
  29875. _viewportSize.x * viewport.z,
  29876. _viewportSize.y * viewport.w
  29877. );
  29878. shadowMap.viewport.copy( _viewport );
  29879. shadow.updateMatrices( light, vp );
  29880. renderer.render( scene, shadow.camera );
  29881. }
  29882. //
  29883. renderer.autoClear = previousAutoClear;
  29884. renderer.setClearColor( previousClearColor, previousClearAlpha );
  29885. }
  29886. }
  29887. /**
  29888. * TSL function for creating an instance of `PointShadowNode`.
  29889. *
  29890. * @tsl
  29891. * @function
  29892. * @param {PointLight} light - The shadow casting point light.
  29893. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  29894. * @return {PointShadowNode} The created point shadow node.
  29895. */
  29896. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  29897. /**
  29898. * Base class for analytic light nodes.
  29899. *
  29900. * @augments LightingNode
  29901. */
  29902. class AnalyticLightNode extends LightingNode {
  29903. static get type() {
  29904. return 'AnalyticLightNode';
  29905. }
  29906. /**
  29907. * Constructs a new analytic light node.
  29908. *
  29909. * @param {?Light} [light=null] - The light source.
  29910. */
  29911. constructor( light = null ) {
  29912. super();
  29913. /**
  29914. * The light source.
  29915. *
  29916. * @type {?Light}
  29917. * @default null
  29918. */
  29919. this.light = light;
  29920. /**
  29921. * The light's color value.
  29922. *
  29923. * @type {Color}
  29924. */
  29925. this.color = new Color();
  29926. /**
  29927. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  29928. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  29929. *
  29930. * @type {Node}
  29931. */
  29932. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  29933. /**
  29934. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  29935. * The final color node is represented by a different node when using shadows.
  29936. *
  29937. * @type {?Node}
  29938. * @default null
  29939. */
  29940. this.baseColorNode = null;
  29941. /**
  29942. * Represents the light's shadow.
  29943. *
  29944. * @type {?ShadowNode}
  29945. * @default null
  29946. */
  29947. this.shadowNode = null;
  29948. /**
  29949. * Represents the light's shadow color.
  29950. *
  29951. * @type {?Node}
  29952. * @default null
  29953. */
  29954. this.shadowColorNode = null;
  29955. /**
  29956. * This flag can be used for type testing.
  29957. *
  29958. * @type {boolean}
  29959. * @readonly
  29960. * @default true
  29961. */
  29962. this.isAnalyticLightNode = true;
  29963. /**
  29964. * Overwritten since analytic light nodes are updated
  29965. * once per frame.
  29966. *
  29967. * @type {string}
  29968. * @default 'frame'
  29969. */
  29970. this.updateType = NodeUpdateType.FRAME;
  29971. }
  29972. getHash() {
  29973. return this.light.uuid;
  29974. }
  29975. /**
  29976. * Returns a node representing a direction vector which points from the current
  29977. * position in view space to the light's position in view space.
  29978. *
  29979. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  29980. * @return {Node<vec3>} The light vector node.
  29981. */
  29982. getLightVector( builder ) {
  29983. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  29984. }
  29985. /**
  29986. * Sets up the direct lighting for the analytic light node.
  29987. *
  29988. * @abstract
  29989. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  29990. * @return {Object|undefined} The direct light data (color and direction).
  29991. */
  29992. setupDirect( /*builder*/ ) { }
  29993. /**
  29994. * Sets up the direct rect area lighting for the analytic light node.
  29995. *
  29996. * @abstract
  29997. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  29998. * @return {Object|undefined} The direct rect area light data.
  29999. */
  30000. setupDirectRectArea( /*builder*/ ) { }
  30001. /**
  30002. * Setups the shadow node for this light. The method exists so concrete light classes
  30003. * can setup different types of shadow nodes.
  30004. *
  30005. * @return {ShadowNode} The created shadow node.
  30006. */
  30007. setupShadowNode() {
  30008. return shadow( this.light );
  30009. }
  30010. /**
  30011. * Setups the shadow for this light. This method is only executed if the light
  30012. * cast shadows and the current build object receives shadows. It incorporates
  30013. * shadows into the lighting computation.
  30014. *
  30015. * @param {NodeBuilder} builder - The current node builder.
  30016. */
  30017. setupShadow( builder ) {
  30018. const { renderer } = builder;
  30019. if ( renderer.shadowMap.enabled === false ) return;
  30020. let shadowColorNode = this.shadowColorNode;
  30021. if ( shadowColorNode === null ) {
  30022. const customShadowNode = this.light.shadow.shadowNode;
  30023. let shadowNode;
  30024. if ( customShadowNode !== undefined ) {
  30025. shadowNode = nodeObject( customShadowNode );
  30026. } else {
  30027. shadowNode = this.setupShadowNode();
  30028. }
  30029. this.shadowNode = shadowNode;
  30030. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  30031. this.baseColorNode = this.colorNode;
  30032. }
  30033. //
  30034. this.colorNode = shadowColorNode;
  30035. }
  30036. /**
  30037. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  30038. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  30039. * invocate the respective interface methods.
  30040. *
  30041. * @param {NodeBuilder} builder - The current node builder.
  30042. */
  30043. setup( builder ) {
  30044. this.colorNode = this.baseColorNode || this.colorNode;
  30045. if ( this.light.castShadow ) {
  30046. if ( builder.object.receiveShadow ) {
  30047. this.setupShadow( builder );
  30048. }
  30049. } else if ( this.shadowNode !== null ) {
  30050. this.shadowNode.dispose();
  30051. this.shadowNode = null;
  30052. this.shadowColorNode = null;
  30053. }
  30054. const directLightData = this.setupDirect( builder );
  30055. const directRectAreaLightData = this.setupDirectRectArea( builder );
  30056. if ( directLightData ) {
  30057. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  30058. }
  30059. if ( directRectAreaLightData ) {
  30060. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  30061. }
  30062. }
  30063. /**
  30064. * The update method is used to update light uniforms per frame.
  30065. * Potentially overwritten in concrete light nodes to update light
  30066. * specific uniforms.
  30067. *
  30068. * @param {NodeFrame} frame - A reference to the current node frame.
  30069. */
  30070. update( /*frame*/ ) {
  30071. const { light } = this;
  30072. this.color.copy( light.color ).multiplyScalar( light.intensity );
  30073. }
  30074. }
  30075. /**
  30076. * Represents a `discard` shader operation in TSL.
  30077. *
  30078. * @method
  30079. * @param {Object} inputs - The input parameter object.
  30080. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  30081. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  30082. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  30083. * @return {Node<float>} The distance falloff.
  30084. */
  30085. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  30086. // based upon Frostbite 3 Moving to Physically-based Rendering
  30087. // page 32, equation 26: E[window1]
  30088. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  30089. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  30090. return cutoffDistance.greaterThan( 0 ).select(
  30091. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  30092. distanceFalloff
  30093. );
  30094. } ); // validated
  30095. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  30096. const lightDirection = lightVector.normalize();
  30097. const lightDistance = lightVector.length();
  30098. const attenuation = getDistanceAttenuation( {
  30099. lightDistance,
  30100. cutoffDistance,
  30101. decayExponent
  30102. } );
  30103. const lightColor = color.mul( attenuation );
  30104. return { lightDirection, lightColor };
  30105. };
  30106. /**
  30107. * Module for representing point lights as nodes.
  30108. *
  30109. * @augments AnalyticLightNode
  30110. */
  30111. class PointLightNode extends AnalyticLightNode {
  30112. static get type() {
  30113. return 'PointLightNode';
  30114. }
  30115. /**
  30116. * Constructs a new point light node.
  30117. *
  30118. * @param {?PointLight} [light=null] - The point light source.
  30119. */
  30120. constructor( light = null ) {
  30121. super( light );
  30122. /**
  30123. * Uniform node representing the cutoff distance.
  30124. *
  30125. * @type {UniformNode<float>}
  30126. */
  30127. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  30128. /**
  30129. * Uniform node representing the decay exponent.
  30130. *
  30131. * @type {UniformNode<float>}
  30132. */
  30133. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  30134. }
  30135. /**
  30136. * Overwritten to updated point light specific uniforms.
  30137. *
  30138. * @param {NodeFrame} frame - A reference to the current node frame.
  30139. */
  30140. update( frame ) {
  30141. const { light } = this;
  30142. super.update( frame );
  30143. this.cutoffDistanceNode.value = light.distance;
  30144. this.decayExponentNode.value = light.decay;
  30145. }
  30146. /**
  30147. * Overwritten to setup point light specific shadow.
  30148. *
  30149. * @return {PointShadowNode}
  30150. */
  30151. setupShadowNode() {
  30152. return pointShadow( this.light );
  30153. }
  30154. setupDirect( builder ) {
  30155. return directPointLight( {
  30156. color: this.colorNode,
  30157. lightVector: this.getLightVector( builder ),
  30158. cutoffDistance: this.cutoffDistanceNode,
  30159. decayExponent: this.decayExponentNode
  30160. } );
  30161. }
  30162. }
  30163. /**
  30164. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  30165. *
  30166. * @tsl
  30167. * @function
  30168. * @param {Node<vec2>} coord - The uv coordinates.
  30169. * @return {Node<float>} The result data.
  30170. */
  30171. const checker = /*@__PURE__*/ Fn( ( [ coord = uv$1() ] ) => {
  30172. const uv = coord.mul( 2.0 );
  30173. const cx = uv.x.floor();
  30174. const cy = uv.y.floor();
  30175. const result = cx.add( cy ).mod( 2.0 );
  30176. return result.sign();
  30177. } );
  30178. /**
  30179. * Generates a circle based on the uv coordinates.
  30180. *
  30181. * @tsl
  30182. * @function
  30183. * @param {Node<vec2>} coord - The uv to generate the circle.
  30184. * @return {Node<float>} The circle shape.
  30185. */
  30186. const shapeCircle = Fn( ( [ coord = uv$1() ], { renderer, material } ) => {
  30187. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  30188. let alpha;
  30189. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  30190. const dlen = float( len2.fwidth() ).toVar();
  30191. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  30192. } else {
  30193. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  30194. }
  30195. return alpha;
  30196. } );
  30197. // Three.js Transpiler
  30198. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  30199. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  30200. const f = float( f_immutable ).toVar();
  30201. const t = float( t_immutable ).toVar();
  30202. const b = bool( b_immutable ).toVar();
  30203. return select( b, t, f );
  30204. } ).setLayout( {
  30205. name: 'mx_select',
  30206. type: 'float',
  30207. inputs: [
  30208. { name: 'b', type: 'bool' },
  30209. { name: 't', type: 'float' },
  30210. { name: 'f', type: 'float' }
  30211. ]
  30212. } );
  30213. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  30214. const b = bool( b_immutable ).toVar();
  30215. const val = float( val_immutable ).toVar();
  30216. return select( b, val.negate(), val );
  30217. } ).setLayout( {
  30218. name: 'mx_negate_if',
  30219. type: 'float',
  30220. inputs: [
  30221. { name: 'val', type: 'float' },
  30222. { name: 'b', type: 'bool' }
  30223. ]
  30224. } );
  30225. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  30226. const x = float( x_immutable ).toVar();
  30227. return int( floor( x ) );
  30228. } ).setLayout( {
  30229. name: 'mx_floor',
  30230. type: 'int',
  30231. inputs: [
  30232. { name: 'x', type: 'float' }
  30233. ]
  30234. } );
  30235. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  30236. const x = float( x_immutable ).toVar();
  30237. i.assign( mx_floor( x ) );
  30238. return x.sub( float( i ) );
  30239. } );
  30240. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  30241. const t = float( t_immutable ).toVar();
  30242. const s = float( s_immutable ).toVar();
  30243. const v3 = float( v3_immutable ).toVar();
  30244. const v2 = float( v2_immutable ).toVar();
  30245. const v1 = float( v1_immutable ).toVar();
  30246. const v0 = float( v0_immutable ).toVar();
  30247. const s1 = float( sub( 1.0, s ) ).toVar();
  30248. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  30249. } ).setLayout( {
  30250. name: 'mx_bilerp_0',
  30251. type: 'float',
  30252. inputs: [
  30253. { name: 'v0', type: 'float' },
  30254. { name: 'v1', type: 'float' },
  30255. { name: 'v2', type: 'float' },
  30256. { name: 'v3', type: 'float' },
  30257. { name: 's', type: 'float' },
  30258. { name: 't', type: 'float' }
  30259. ]
  30260. } );
  30261. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  30262. const t = float( t_immutable ).toVar();
  30263. const s = float( s_immutable ).toVar();
  30264. const v3 = vec3( v3_immutable ).toVar();
  30265. const v2 = vec3( v2_immutable ).toVar();
  30266. const v1 = vec3( v1_immutable ).toVar();
  30267. const v0 = vec3( v0_immutable ).toVar();
  30268. const s1 = float( sub( 1.0, s ) ).toVar();
  30269. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  30270. } ).setLayout( {
  30271. name: 'mx_bilerp_1',
  30272. type: 'vec3',
  30273. inputs: [
  30274. { name: 'v0', type: 'vec3' },
  30275. { name: 'v1', type: 'vec3' },
  30276. { name: 'v2', type: 'vec3' },
  30277. { name: 'v3', type: 'vec3' },
  30278. { name: 's', type: 'float' },
  30279. { name: 't', type: 'float' }
  30280. ]
  30281. } );
  30282. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  30283. 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 ] ) => {
  30284. const r = float( r_immutable ).toVar();
  30285. const t = float( t_immutable ).toVar();
  30286. const s = float( s_immutable ).toVar();
  30287. const v7 = float( v7_immutable ).toVar();
  30288. const v6 = float( v6_immutable ).toVar();
  30289. const v5 = float( v5_immutable ).toVar();
  30290. const v4 = float( v4_immutable ).toVar();
  30291. const v3 = float( v3_immutable ).toVar();
  30292. const v2 = float( v2_immutable ).toVar();
  30293. const v1 = float( v1_immutable ).toVar();
  30294. const v0 = float( v0_immutable ).toVar();
  30295. const s1 = float( sub( 1.0, s ) ).toVar();
  30296. const t1 = float( sub( 1.0, t ) ).toVar();
  30297. const r1 = float( sub( 1.0, r ) ).toVar();
  30298. 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 ) ) ) ) ) );
  30299. } ).setLayout( {
  30300. name: 'mx_trilerp_0',
  30301. type: 'float',
  30302. inputs: [
  30303. { name: 'v0', type: 'float' },
  30304. { name: 'v1', type: 'float' },
  30305. { name: 'v2', type: 'float' },
  30306. { name: 'v3', type: 'float' },
  30307. { name: 'v4', type: 'float' },
  30308. { name: 'v5', type: 'float' },
  30309. { name: 'v6', type: 'float' },
  30310. { name: 'v7', type: 'float' },
  30311. { name: 's', type: 'float' },
  30312. { name: 't', type: 'float' },
  30313. { name: 'r', type: 'float' }
  30314. ]
  30315. } );
  30316. 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 ] ) => {
  30317. const r = float( r_immutable ).toVar();
  30318. const t = float( t_immutable ).toVar();
  30319. const s = float( s_immutable ).toVar();
  30320. const v7 = vec3( v7_immutable ).toVar();
  30321. const v6 = vec3( v6_immutable ).toVar();
  30322. const v5 = vec3( v5_immutable ).toVar();
  30323. const v4 = vec3( v4_immutable ).toVar();
  30324. const v3 = vec3( v3_immutable ).toVar();
  30325. const v2 = vec3( v2_immutable ).toVar();
  30326. const v1 = vec3( v1_immutable ).toVar();
  30327. const v0 = vec3( v0_immutable ).toVar();
  30328. const s1 = float( sub( 1.0, s ) ).toVar();
  30329. const t1 = float( sub( 1.0, t ) ).toVar();
  30330. const r1 = float( sub( 1.0, r ) ).toVar();
  30331. 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 ) ) ) ) ) );
  30332. } ).setLayout( {
  30333. name: 'mx_trilerp_1',
  30334. type: 'vec3',
  30335. inputs: [
  30336. { name: 'v0', type: 'vec3' },
  30337. { name: 'v1', type: 'vec3' },
  30338. { name: 'v2', type: 'vec3' },
  30339. { name: 'v3', type: 'vec3' },
  30340. { name: 'v4', type: 'vec3' },
  30341. { name: 'v5', type: 'vec3' },
  30342. { name: 'v6', type: 'vec3' },
  30343. { name: 'v7', type: 'vec3' },
  30344. { name: 's', type: 'float' },
  30345. { name: 't', type: 'float' },
  30346. { name: 'r', type: 'float' }
  30347. ]
  30348. } );
  30349. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  30350. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  30351. const y = float( y_immutable ).toVar();
  30352. const x = float( x_immutable ).toVar();
  30353. const hash = uint( hash_immutable ).toVar();
  30354. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  30355. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  30356. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  30357. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  30358. } ).setLayout( {
  30359. name: 'mx_gradient_float_0',
  30360. type: 'float',
  30361. inputs: [
  30362. { name: 'hash', type: 'uint' },
  30363. { name: 'x', type: 'float' },
  30364. { name: 'y', type: 'float' }
  30365. ]
  30366. } );
  30367. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  30368. const z = float( z_immutable ).toVar();
  30369. const y = float( y_immutable ).toVar();
  30370. const x = float( x_immutable ).toVar();
  30371. const hash = uint( hash_immutable ).toVar();
  30372. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  30373. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  30374. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  30375. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  30376. } ).setLayout( {
  30377. name: 'mx_gradient_float_1',
  30378. type: 'float',
  30379. inputs: [
  30380. { name: 'hash', type: 'uint' },
  30381. { name: 'x', type: 'float' },
  30382. { name: 'y', type: 'float' },
  30383. { name: 'z', type: 'float' }
  30384. ]
  30385. } );
  30386. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  30387. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  30388. const y = float( y_immutable ).toVar();
  30389. const x = float( x_immutable ).toVar();
  30390. const hash = uvec3( hash_immutable ).toVar();
  30391. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  30392. } ).setLayout( {
  30393. name: 'mx_gradient_vec3_0',
  30394. type: 'vec3',
  30395. inputs: [
  30396. { name: 'hash', type: 'uvec3' },
  30397. { name: 'x', type: 'float' },
  30398. { name: 'y', type: 'float' }
  30399. ]
  30400. } );
  30401. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  30402. const z = float( z_immutable ).toVar();
  30403. const y = float( y_immutable ).toVar();
  30404. const x = float( x_immutable ).toVar();
  30405. const hash = uvec3( hash_immutable ).toVar();
  30406. 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 ) );
  30407. } ).setLayout( {
  30408. name: 'mx_gradient_vec3_1',
  30409. type: 'vec3',
  30410. inputs: [
  30411. { name: 'hash', type: 'uvec3' },
  30412. { name: 'x', type: 'float' },
  30413. { name: 'y', type: 'float' },
  30414. { name: 'z', type: 'float' }
  30415. ]
  30416. } );
  30417. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  30418. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30419. const v = float( v_immutable ).toVar();
  30420. return mul( 0.6616, v );
  30421. } ).setLayout( {
  30422. name: 'mx_gradient_scale2d_0',
  30423. type: 'float',
  30424. inputs: [
  30425. { name: 'v', type: 'float' }
  30426. ]
  30427. } );
  30428. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30429. const v = float( v_immutable ).toVar();
  30430. return mul( 0.9820, v );
  30431. } ).setLayout( {
  30432. name: 'mx_gradient_scale3d_0',
  30433. type: 'float',
  30434. inputs: [
  30435. { name: 'v', type: 'float' }
  30436. ]
  30437. } );
  30438. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30439. const v = vec3( v_immutable ).toVar();
  30440. return mul( 0.6616, v );
  30441. } ).setLayout( {
  30442. name: 'mx_gradient_scale2d_1',
  30443. type: 'vec3',
  30444. inputs: [
  30445. { name: 'v', type: 'vec3' }
  30446. ]
  30447. } );
  30448. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  30449. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  30450. const v = vec3( v_immutable ).toVar();
  30451. return mul( 0.9820, v );
  30452. } ).setLayout( {
  30453. name: 'mx_gradient_scale3d_1',
  30454. type: 'vec3',
  30455. inputs: [
  30456. { name: 'v', type: 'vec3' }
  30457. ]
  30458. } );
  30459. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  30460. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  30461. const k = int( k_immutable ).toVar();
  30462. const x = uint( x_immutable ).toVar();
  30463. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  30464. } ).setLayout( {
  30465. name: 'mx_rotl32',
  30466. type: 'uint',
  30467. inputs: [
  30468. { name: 'x', type: 'uint' },
  30469. { name: 'k', type: 'int' }
  30470. ]
  30471. } );
  30472. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  30473. a.subAssign( c );
  30474. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  30475. c.addAssign( b );
  30476. b.subAssign( a );
  30477. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  30478. a.addAssign( c );
  30479. c.subAssign( b );
  30480. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  30481. b.addAssign( a );
  30482. a.subAssign( c );
  30483. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  30484. c.addAssign( b );
  30485. b.subAssign( a );
  30486. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  30487. a.addAssign( c );
  30488. c.subAssign( b );
  30489. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  30490. b.addAssign( a );
  30491. } );
  30492. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  30493. const c = uint( c_immutable ).toVar();
  30494. const b = uint( b_immutable ).toVar();
  30495. const a = uint( a_immutable ).toVar();
  30496. c.bitXorAssign( b );
  30497. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  30498. a.bitXorAssign( c );
  30499. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  30500. b.bitXorAssign( a );
  30501. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  30502. c.bitXorAssign( b );
  30503. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  30504. a.bitXorAssign( c );
  30505. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  30506. b.bitXorAssign( a );
  30507. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  30508. c.bitXorAssign( b );
  30509. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  30510. return c;
  30511. } ).setLayout( {
  30512. name: 'mx_bjfinal',
  30513. type: 'uint',
  30514. inputs: [
  30515. { name: 'a', type: 'uint' },
  30516. { name: 'b', type: 'uint' },
  30517. { name: 'c', type: 'uint' }
  30518. ]
  30519. } );
  30520. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  30521. const bits = uint( bits_immutable ).toVar();
  30522. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  30523. } ).setLayout( {
  30524. name: 'mx_bits_to_01',
  30525. type: 'float',
  30526. inputs: [
  30527. { name: 'bits', type: 'uint' }
  30528. ]
  30529. } );
  30530. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  30531. const t = float( t_immutable ).toVar();
  30532. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  30533. } ).setLayout( {
  30534. name: 'mx_fade',
  30535. type: 'float',
  30536. inputs: [
  30537. { name: 't', type: 'float' }
  30538. ]
  30539. } );
  30540. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  30541. const x = int( x_immutable ).toVar();
  30542. const len = uint( uint( 1 ) ).toVar();
  30543. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  30544. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  30545. } ).setLayout( {
  30546. name: 'mx_hash_int_0',
  30547. type: 'uint',
  30548. inputs: [
  30549. { name: 'x', type: 'int' }
  30550. ]
  30551. } );
  30552. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  30553. const y = int( y_immutable ).toVar();
  30554. const x = int( x_immutable ).toVar();
  30555. const len = uint( uint( 2 ) ).toVar();
  30556. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30557. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30558. a.addAssign( uint( x ) );
  30559. b.addAssign( uint( y ) );
  30560. return mx_bjfinal( a, b, c );
  30561. } ).setLayout( {
  30562. name: 'mx_hash_int_1',
  30563. type: 'uint',
  30564. inputs: [
  30565. { name: 'x', type: 'int' },
  30566. { name: 'y', type: 'int' }
  30567. ]
  30568. } );
  30569. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  30570. const z = int( z_immutable ).toVar();
  30571. const y = int( y_immutable ).toVar();
  30572. const x = int( x_immutable ).toVar();
  30573. const len = uint( uint( 3 ) ).toVar();
  30574. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30575. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30576. a.addAssign( uint( x ) );
  30577. b.addAssign( uint( y ) );
  30578. c.addAssign( uint( z ) );
  30579. return mx_bjfinal( a, b, c );
  30580. } ).setLayout( {
  30581. name: 'mx_hash_int_2',
  30582. type: 'uint',
  30583. inputs: [
  30584. { name: 'x', type: 'int' },
  30585. { name: 'y', type: 'int' },
  30586. { name: 'z', type: 'int' }
  30587. ]
  30588. } );
  30589. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  30590. const xx = int( xx_immutable ).toVar();
  30591. const z = int( z_immutable ).toVar();
  30592. const y = int( y_immutable ).toVar();
  30593. const x = int( x_immutable ).toVar();
  30594. const len = uint( uint( 4 ) ).toVar();
  30595. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30596. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30597. a.addAssign( uint( x ) );
  30598. b.addAssign( uint( y ) );
  30599. c.addAssign( uint( z ) );
  30600. mx_bjmix( a, b, c );
  30601. a.addAssign( uint( xx ) );
  30602. return mx_bjfinal( a, b, c );
  30603. } ).setLayout( {
  30604. name: 'mx_hash_int_3',
  30605. type: 'uint',
  30606. inputs: [
  30607. { name: 'x', type: 'int' },
  30608. { name: 'y', type: 'int' },
  30609. { name: 'z', type: 'int' },
  30610. { name: 'xx', type: 'int' }
  30611. ]
  30612. } );
  30613. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  30614. const yy = int( yy_immutable ).toVar();
  30615. const xx = int( xx_immutable ).toVar();
  30616. const z = int( z_immutable ).toVar();
  30617. const y = int( y_immutable ).toVar();
  30618. const x = int( x_immutable ).toVar();
  30619. const len = uint( uint( 5 ) ).toVar();
  30620. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  30621. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  30622. a.addAssign( uint( x ) );
  30623. b.addAssign( uint( y ) );
  30624. c.addAssign( uint( z ) );
  30625. mx_bjmix( a, b, c );
  30626. a.addAssign( uint( xx ) );
  30627. b.addAssign( uint( yy ) );
  30628. return mx_bjfinal( a, b, c );
  30629. } ).setLayout( {
  30630. name: 'mx_hash_int_4',
  30631. type: 'uint',
  30632. inputs: [
  30633. { name: 'x', type: 'int' },
  30634. { name: 'y', type: 'int' },
  30635. { name: 'z', type: 'int' },
  30636. { name: 'xx', type: 'int' },
  30637. { name: 'yy', type: 'int' }
  30638. ]
  30639. } );
  30640. 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 ] );
  30641. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  30642. const y = int( y_immutable ).toVar();
  30643. const x = int( x_immutable ).toVar();
  30644. const h = uint( mx_hash_int( x, y ) ).toVar();
  30645. const result = uvec3().toVar();
  30646. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  30647. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  30648. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  30649. return result;
  30650. } ).setLayout( {
  30651. name: 'mx_hash_vec3_0',
  30652. type: 'uvec3',
  30653. inputs: [
  30654. { name: 'x', type: 'int' },
  30655. { name: 'y', type: 'int' }
  30656. ]
  30657. } );
  30658. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  30659. const z = int( z_immutable ).toVar();
  30660. const y = int( y_immutable ).toVar();
  30661. const x = int( x_immutable ).toVar();
  30662. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  30663. const result = uvec3().toVar();
  30664. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  30665. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  30666. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  30667. return result;
  30668. } ).setLayout( {
  30669. name: 'mx_hash_vec3_1',
  30670. type: 'uvec3',
  30671. inputs: [
  30672. { name: 'x', type: 'int' },
  30673. { name: 'y', type: 'int' },
  30674. { name: 'z', type: 'int' }
  30675. ]
  30676. } );
  30677. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  30678. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30679. const p = vec2( p_immutable ).toVar();
  30680. const X = int().toVar(), Y = int().toVar();
  30681. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30682. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30683. const u = float( mx_fade( fx ) ).toVar();
  30684. const v = float( mx_fade( fy ) ).toVar();
  30685. 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();
  30686. return mx_gradient_scale2d( result );
  30687. } ).setLayout( {
  30688. name: 'mx_perlin_noise_float_0',
  30689. type: 'float',
  30690. inputs: [
  30691. { name: 'p', type: 'vec2' }
  30692. ]
  30693. } );
  30694. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30695. const p = vec3( p_immutable ).toVar();
  30696. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30697. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30698. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30699. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  30700. const u = float( mx_fade( fx ) ).toVar();
  30701. const v = float( mx_fade( fy ) ).toVar();
  30702. const w = float( mx_fade( fz ) ).toVar();
  30703. 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();
  30704. return mx_gradient_scale3d( result );
  30705. } ).setLayout( {
  30706. name: 'mx_perlin_noise_float_1',
  30707. type: 'float',
  30708. inputs: [
  30709. { name: 'p', type: 'vec3' }
  30710. ]
  30711. } );
  30712. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  30713. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30714. const p = vec2( p_immutable ).toVar();
  30715. const X = int().toVar(), Y = int().toVar();
  30716. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30717. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30718. const u = float( mx_fade( fx ) ).toVar();
  30719. const v = float( mx_fade( fy ) ).toVar();
  30720. 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();
  30721. return mx_gradient_scale2d( result );
  30722. } ).setLayout( {
  30723. name: 'mx_perlin_noise_vec3_0',
  30724. type: 'vec3',
  30725. inputs: [
  30726. { name: 'p', type: 'vec2' }
  30727. ]
  30728. } );
  30729. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30730. const p = vec3( p_immutable ).toVar();
  30731. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  30732. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  30733. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  30734. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  30735. const u = float( mx_fade( fx ) ).toVar();
  30736. const v = float( mx_fade( fy ) ).toVar();
  30737. const w = float( mx_fade( fz ) ).toVar();
  30738. 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();
  30739. return mx_gradient_scale3d( result );
  30740. } ).setLayout( {
  30741. name: 'mx_perlin_noise_vec3_1',
  30742. type: 'vec3',
  30743. inputs: [
  30744. { name: 'p', type: 'vec3' }
  30745. ]
  30746. } );
  30747. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  30748. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30749. const p = float( p_immutable ).toVar();
  30750. const ix = int( mx_floor( p ) ).toVar();
  30751. return mx_bits_to_01( mx_hash_int( ix ) );
  30752. } ).setLayout( {
  30753. name: 'mx_cell_noise_float_0',
  30754. type: 'float',
  30755. inputs: [
  30756. { name: 'p', type: 'float' }
  30757. ]
  30758. } );
  30759. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30760. const p = vec2( p_immutable ).toVar();
  30761. const ix = int( mx_floor( p.x ) ).toVar();
  30762. const iy = int( mx_floor( p.y ) ).toVar();
  30763. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  30764. } ).setLayout( {
  30765. name: 'mx_cell_noise_float_1',
  30766. type: 'float',
  30767. inputs: [
  30768. { name: 'p', type: 'vec2' }
  30769. ]
  30770. } );
  30771. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30772. const p = vec3( p_immutable ).toVar();
  30773. const ix = int( mx_floor( p.x ) ).toVar();
  30774. const iy = int( mx_floor( p.y ) ).toVar();
  30775. const iz = int( mx_floor( p.z ) ).toVar();
  30776. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  30777. } ).setLayout( {
  30778. name: 'mx_cell_noise_float_2',
  30779. type: 'float',
  30780. inputs: [
  30781. { name: 'p', type: 'vec3' }
  30782. ]
  30783. } );
  30784. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30785. const p = vec4( p_immutable ).toVar();
  30786. const ix = int( mx_floor( p.x ) ).toVar();
  30787. const iy = int( mx_floor( p.y ) ).toVar();
  30788. const iz = int( mx_floor( p.z ) ).toVar();
  30789. const iw = int( mx_floor( p.w ) ).toVar();
  30790. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  30791. } ).setLayout( {
  30792. name: 'mx_cell_noise_float_3',
  30793. type: 'float',
  30794. inputs: [
  30795. { name: 'p', type: 'vec4' }
  30796. ]
  30797. } );
  30798. 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 ] );
  30799. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30800. const p = float( p_immutable ).toVar();
  30801. const ix = int( mx_floor( p ) ).toVar();
  30802. 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 ) ) ) );
  30803. } ).setLayout( {
  30804. name: 'mx_cell_noise_vec3_0',
  30805. type: 'vec3',
  30806. inputs: [
  30807. { name: 'p', type: 'float' }
  30808. ]
  30809. } );
  30810. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30811. const p = vec2( p_immutable ).toVar();
  30812. const ix = int( mx_floor( p.x ) ).toVar();
  30813. const iy = int( mx_floor( p.y ) ).toVar();
  30814. 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 ) ) ) );
  30815. } ).setLayout( {
  30816. name: 'mx_cell_noise_vec3_1',
  30817. type: 'vec3',
  30818. inputs: [
  30819. { name: 'p', type: 'vec2' }
  30820. ]
  30821. } );
  30822. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30823. const p = vec3( p_immutable ).toVar();
  30824. const ix = int( mx_floor( p.x ) ).toVar();
  30825. const iy = int( mx_floor( p.y ) ).toVar();
  30826. const iz = int( mx_floor( p.z ) ).toVar();
  30827. 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 ) ) ) );
  30828. } ).setLayout( {
  30829. name: 'mx_cell_noise_vec3_2',
  30830. type: 'vec3',
  30831. inputs: [
  30832. { name: 'p', type: 'vec3' }
  30833. ]
  30834. } );
  30835. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  30836. const p = vec4( p_immutable ).toVar();
  30837. const ix = int( mx_floor( p.x ) ).toVar();
  30838. const iy = int( mx_floor( p.y ) ).toVar();
  30839. const iz = int( mx_floor( p.z ) ).toVar();
  30840. const iw = int( mx_floor( p.w ) ).toVar();
  30841. 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 ) ) ) );
  30842. } ).setLayout( {
  30843. name: 'mx_cell_noise_vec3_3',
  30844. type: 'vec3',
  30845. inputs: [
  30846. { name: 'p', type: 'vec4' }
  30847. ]
  30848. } );
  30849. 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 ] );
  30850. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30851. const diminish = float( diminish_immutable ).toVar();
  30852. const lacunarity = float( lacunarity_immutable ).toVar();
  30853. const octaves = int( octaves_immutable ).toVar();
  30854. const p = vec3( p_immutable ).toVar();
  30855. const result = float( 0.0 ).toVar();
  30856. const amplitude = float( 1.0 ).toVar();
  30857. Loop( octaves, () => {
  30858. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  30859. amplitude.mulAssign( diminish );
  30860. p.mulAssign( lacunarity );
  30861. } );
  30862. return result;
  30863. } ).setLayout( {
  30864. name: 'mx_fractal_noise_float',
  30865. type: 'float',
  30866. inputs: [
  30867. { name: 'p', type: 'vec3' },
  30868. { name: 'octaves', type: 'int' },
  30869. { name: 'lacunarity', type: 'float' },
  30870. { name: 'diminish', type: 'float' }
  30871. ]
  30872. } );
  30873. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30874. const diminish = float( diminish_immutable ).toVar();
  30875. const lacunarity = float( lacunarity_immutable ).toVar();
  30876. const octaves = int( octaves_immutable ).toVar();
  30877. const p = vec3( p_immutable ).toVar();
  30878. const result = vec3( 0.0 ).toVar();
  30879. const amplitude = float( 1.0 ).toVar();
  30880. Loop( octaves, () => {
  30881. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  30882. amplitude.mulAssign( diminish );
  30883. p.mulAssign( lacunarity );
  30884. } );
  30885. return result;
  30886. } ).setLayout( {
  30887. name: 'mx_fractal_noise_vec3',
  30888. type: 'vec3',
  30889. inputs: [
  30890. { name: 'p', type: 'vec3' },
  30891. { name: 'octaves', type: 'int' },
  30892. { name: 'lacunarity', type: 'float' },
  30893. { name: 'diminish', type: 'float' }
  30894. ]
  30895. } );
  30896. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30897. const diminish = float( diminish_immutable ).toVar();
  30898. const lacunarity = float( lacunarity_immutable ).toVar();
  30899. const octaves = int( octaves_immutable ).toVar();
  30900. const p = vec3( p_immutable ).toVar();
  30901. 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 ) );
  30902. } ).setLayout( {
  30903. name: 'mx_fractal_noise_vec2',
  30904. type: 'vec2',
  30905. inputs: [
  30906. { name: 'p', type: 'vec3' },
  30907. { name: 'octaves', type: 'int' },
  30908. { name: 'lacunarity', type: 'float' },
  30909. { name: 'diminish', type: 'float' }
  30910. ]
  30911. } );
  30912. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  30913. const diminish = float( diminish_immutable ).toVar();
  30914. const lacunarity = float( lacunarity_immutable ).toVar();
  30915. const octaves = int( octaves_immutable ).toVar();
  30916. const p = vec3( p_immutable ).toVar();
  30917. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  30918. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  30919. return vec4( c, f );
  30920. } ).setLayout( {
  30921. name: 'mx_fractal_noise_vec4',
  30922. type: 'vec4',
  30923. inputs: [
  30924. { name: 'p', type: 'vec3' },
  30925. { name: 'octaves', type: 'int' },
  30926. { name: 'lacunarity', type: 'float' },
  30927. { name: 'diminish', type: 'float' }
  30928. ]
  30929. } );
  30930. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  30931. const metric = int( metric_immutable ).toVar();
  30932. const jitter = float( jitter_immutable ).toVar();
  30933. const yoff = int( yoff_immutable ).toVar();
  30934. const xoff = int( xoff_immutable ).toVar();
  30935. const y = int( y_immutable ).toVar();
  30936. const x = int( x_immutable ).toVar();
  30937. const p = vec2( p_immutable ).toVar();
  30938. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  30939. const off = vec2( tmp.x, tmp.y ).toVar();
  30940. off.subAssign( 0.5 );
  30941. off.mulAssign( jitter );
  30942. off.addAssign( 0.5 );
  30943. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  30944. const diff = vec2( cellpos.sub( p ) ).toVar();
  30945. If( metric.equal( int( 2 ) ), () => {
  30946. return abs( diff.x ).add( abs( diff.y ) );
  30947. } );
  30948. If( metric.equal( int( 3 ) ), () => {
  30949. return max$1( abs( diff.x ), abs( diff.y ) );
  30950. } );
  30951. return dot( diff, diff );
  30952. } ).setLayout( {
  30953. name: 'mx_worley_distance_0',
  30954. type: 'float',
  30955. inputs: [
  30956. { name: 'p', type: 'vec2' },
  30957. { name: 'x', type: 'int' },
  30958. { name: 'y', type: 'int' },
  30959. { name: 'xoff', type: 'int' },
  30960. { name: 'yoff', type: 'int' },
  30961. { name: 'jitter', type: 'float' },
  30962. { name: 'metric', type: 'int' }
  30963. ]
  30964. } );
  30965. 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 ] ) => {
  30966. const metric = int( metric_immutable ).toVar();
  30967. const jitter = float( jitter_immutable ).toVar();
  30968. const zoff = int( zoff_immutable ).toVar();
  30969. const yoff = int( yoff_immutable ).toVar();
  30970. const xoff = int( xoff_immutable ).toVar();
  30971. const z = int( z_immutable ).toVar();
  30972. const y = int( y_immutable ).toVar();
  30973. const x = int( x_immutable ).toVar();
  30974. const p = vec3( p_immutable ).toVar();
  30975. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  30976. off.subAssign( 0.5 );
  30977. off.mulAssign( jitter );
  30978. off.addAssign( 0.5 );
  30979. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  30980. const diff = vec3( cellpos.sub( p ) ).toVar();
  30981. If( metric.equal( int( 2 ) ), () => {
  30982. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  30983. } );
  30984. If( metric.equal( int( 3 ) ), () => {
  30985. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  30986. } );
  30987. return dot( diff, diff );
  30988. } ).setLayout( {
  30989. name: 'mx_worley_distance_1',
  30990. type: 'float',
  30991. inputs: [
  30992. { name: 'p', type: 'vec3' },
  30993. { name: 'x', type: 'int' },
  30994. { name: 'y', type: 'int' },
  30995. { name: 'z', type: 'int' },
  30996. { name: 'xoff', type: 'int' },
  30997. { name: 'yoff', type: 'int' },
  30998. { name: 'zoff', type: 'int' },
  30999. { name: 'jitter', type: 'float' },
  31000. { name: 'metric', type: 'int' }
  31001. ]
  31002. } );
  31003. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  31004. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31005. const metric = int( metric_immutable ).toVar();
  31006. const jitter = float( jitter_immutable ).toVar();
  31007. const p = vec2( p_immutable ).toVar();
  31008. const X = int().toVar(), Y = int().toVar();
  31009. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31010. const sqdist = float( 1e6 ).toVar();
  31011. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31012. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31013. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31014. sqdist.assign( min$1( sqdist, dist ) );
  31015. } );
  31016. } );
  31017. If( metric.equal( int( 0 ) ), () => {
  31018. sqdist.assign( sqrt( sqdist ) );
  31019. } );
  31020. return sqdist;
  31021. } ).setLayout( {
  31022. name: 'mx_worley_noise_float_0',
  31023. type: 'float',
  31024. inputs: [
  31025. { name: 'p', type: 'vec2' },
  31026. { name: 'jitter', type: 'float' },
  31027. { name: 'metric', type: 'int' }
  31028. ]
  31029. } );
  31030. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31031. const metric = int( metric_immutable ).toVar();
  31032. const jitter = float( jitter_immutable ).toVar();
  31033. const p = vec2( p_immutable ).toVar();
  31034. const X = int().toVar(), Y = int().toVar();
  31035. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31036. const sqdist = vec2( 1e6, 1e6 ).toVar();
  31037. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31038. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31039. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31040. If( dist.lessThan( sqdist.x ), () => {
  31041. sqdist.y.assign( sqdist.x );
  31042. sqdist.x.assign( dist );
  31043. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31044. sqdist.y.assign( dist );
  31045. } );
  31046. } );
  31047. } );
  31048. If( metric.equal( int( 0 ) ), () => {
  31049. sqdist.assign( sqrt( sqdist ) );
  31050. } );
  31051. return sqdist;
  31052. } ).setLayout( {
  31053. name: 'mx_worley_noise_vec2_0',
  31054. type: 'vec2',
  31055. inputs: [
  31056. { name: 'p', type: 'vec2' },
  31057. { name: 'jitter', type: 'float' },
  31058. { name: 'metric', type: 'int' }
  31059. ]
  31060. } );
  31061. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31062. const metric = int( metric_immutable ).toVar();
  31063. const jitter = float( jitter_immutable ).toVar();
  31064. const p = vec2( p_immutable ).toVar();
  31065. const X = int().toVar(), Y = int().toVar();
  31066. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  31067. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  31068. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31069. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31070. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  31071. If( dist.lessThan( sqdist.x ), () => {
  31072. sqdist.z.assign( sqdist.y );
  31073. sqdist.y.assign( sqdist.x );
  31074. sqdist.x.assign( dist );
  31075. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31076. sqdist.z.assign( sqdist.y );
  31077. sqdist.y.assign( dist );
  31078. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  31079. sqdist.z.assign( dist );
  31080. } );
  31081. } );
  31082. } );
  31083. If( metric.equal( int( 0 ) ), () => {
  31084. sqdist.assign( sqrt( sqdist ) );
  31085. } );
  31086. return sqdist;
  31087. } ).setLayout( {
  31088. name: 'mx_worley_noise_vec3_0',
  31089. type: 'vec3',
  31090. inputs: [
  31091. { name: 'p', type: 'vec2' },
  31092. { name: 'jitter', type: 'float' },
  31093. { name: 'metric', type: 'int' }
  31094. ]
  31095. } );
  31096. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31097. const metric = int( metric_immutable ).toVar();
  31098. const jitter = float( jitter_immutable ).toVar();
  31099. const p = vec3( p_immutable ).toVar();
  31100. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31101. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31102. const sqdist = float( 1e6 ).toVar();
  31103. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31104. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31105. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31106. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31107. sqdist.assign( min$1( sqdist, dist ) );
  31108. } );
  31109. } );
  31110. } );
  31111. If( metric.equal( int( 0 ) ), () => {
  31112. sqdist.assign( sqrt( sqdist ) );
  31113. } );
  31114. return sqdist;
  31115. } ).setLayout( {
  31116. name: 'mx_worley_noise_float_1',
  31117. type: 'float',
  31118. inputs: [
  31119. { name: 'p', type: 'vec3' },
  31120. { name: 'jitter', type: 'float' },
  31121. { name: 'metric', type: 'int' }
  31122. ]
  31123. } );
  31124. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  31125. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31126. const metric = int( metric_immutable ).toVar();
  31127. const jitter = float( jitter_immutable ).toVar();
  31128. const p = vec3( p_immutable ).toVar();
  31129. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31130. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31131. const sqdist = vec2( 1e6, 1e6 ).toVar();
  31132. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31133. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31134. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31135. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31136. If( dist.lessThan( sqdist.x ), () => {
  31137. sqdist.y.assign( sqdist.x );
  31138. sqdist.x.assign( dist );
  31139. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31140. sqdist.y.assign( dist );
  31141. } );
  31142. } );
  31143. } );
  31144. } );
  31145. If( metric.equal( int( 0 ) ), () => {
  31146. sqdist.assign( sqrt( sqdist ) );
  31147. } );
  31148. return sqdist;
  31149. } ).setLayout( {
  31150. name: 'mx_worley_noise_vec2_1',
  31151. type: 'vec2',
  31152. inputs: [
  31153. { name: 'p', type: 'vec3' },
  31154. { name: 'jitter', type: 'float' },
  31155. { name: 'metric', type: 'int' }
  31156. ]
  31157. } );
  31158. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  31159. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  31160. const metric = int( metric_immutable ).toVar();
  31161. const jitter = float( jitter_immutable ).toVar();
  31162. const p = vec3( p_immutable ).toVar();
  31163. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  31164. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  31165. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  31166. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  31167. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  31168. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  31169. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  31170. If( dist.lessThan( sqdist.x ), () => {
  31171. sqdist.z.assign( sqdist.y );
  31172. sqdist.y.assign( sqdist.x );
  31173. sqdist.x.assign( dist );
  31174. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  31175. sqdist.z.assign( sqdist.y );
  31176. sqdist.y.assign( dist );
  31177. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  31178. sqdist.z.assign( dist );
  31179. } );
  31180. } );
  31181. } );
  31182. } );
  31183. If( metric.equal( int( 0 ) ), () => {
  31184. sqdist.assign( sqrt( sqdist ) );
  31185. } );
  31186. return sqdist;
  31187. } ).setLayout( {
  31188. name: 'mx_worley_noise_vec3_1',
  31189. type: 'vec3',
  31190. inputs: [
  31191. { name: 'p', type: 'vec3' },
  31192. { name: 'jitter', type: 'float' },
  31193. { name: 'metric', type: 'int' }
  31194. ]
  31195. } );
  31196. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  31197. // Unified Noise 2D
  31198. const mx_unifiednoise2d$1 = /*@__PURE__*/ Fn( ( [
  31199. noiseType_immutable, texcoord_immutable, freq_immutable, offset_immutable,
  31200. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  31201. octaves_immutable, lacunarity_immutable, diminish_immutable
  31202. ] ) => {
  31203. const noiseType = int( noiseType_immutable ).toVar();
  31204. const texcoord = vec2( texcoord_immutable ).toVar();
  31205. const freq = vec2( freq_immutable ).toVar();
  31206. const offset = vec2( offset_immutable ).toVar();
  31207. const jitter = float( jitter_immutable ).toVar();
  31208. const outmin = float( outmin_immutable ).toVar();
  31209. const outmax = float( outmax_immutable ).toVar();
  31210. const clampoutput = bool( clampoutput_immutable ).toVar();
  31211. const octaves = int( octaves_immutable ).toVar();
  31212. const lacunarity = float( lacunarity_immutable ).toVar();
  31213. const diminish = float( diminish_immutable ).toVar();
  31214. // Compute input position
  31215. const p = texcoord.mul( freq ).add( offset );
  31216. const result = float( 0.0 ).toVar();
  31217. // Perlin
  31218. If( noiseType.equal( int( 0 ) ), () => {
  31219. result.assign( mx_perlin_noise_vec3( p ) );
  31220. } );
  31221. // Cell
  31222. If( noiseType.equal( int( 1 ) ), () => {
  31223. result.assign( mx_cell_noise_vec3( p ) );
  31224. } );
  31225. // Worley (metric=0 = euclidean)
  31226. If( noiseType.equal( int( 2 ) ), () => {
  31227. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  31228. } );
  31229. // Fractal (use vec3(p, 0.0) for 2D input)
  31230. If( noiseType.equal( int( 3 ) ), () => {
  31231. result.assign( mx_fractal_noise_vec3$1( vec3( p, 0.0 ), octaves, lacunarity, diminish ) );
  31232. } );
  31233. // Remap output to [outmin, outmax]
  31234. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  31235. // Clamp if requested
  31236. If( clampoutput, () => {
  31237. result.assign( clamp( result, outmin, outmax ) );
  31238. } );
  31239. return result;
  31240. } ).setLayout( {
  31241. name: 'mx_unifiednoise2d',
  31242. type: 'float',
  31243. inputs: [
  31244. { name: 'noiseType', type: 'int' },
  31245. { name: 'texcoord', type: 'vec2' },
  31246. { name: 'freq', type: 'vec2' },
  31247. { name: 'offset', type: 'vec2' },
  31248. { name: 'jitter', type: 'float' },
  31249. { name: 'outmin', type: 'float' },
  31250. { name: 'outmax', type: 'float' },
  31251. { name: 'clampoutput', type: 'bool' },
  31252. { name: 'octaves', type: 'int' },
  31253. { name: 'lacunarity', type: 'float' },
  31254. { name: 'diminish', type: 'float' }
  31255. ]
  31256. } );
  31257. // Unified Noise 3D
  31258. const mx_unifiednoise3d$1 = /*@__PURE__*/ Fn( ( [
  31259. noiseType_immutable, position_immutable, freq_immutable, offset_immutable,
  31260. jitter_immutable, outmin_immutable, outmax_immutable, clampoutput_immutable,
  31261. octaves_immutable, lacunarity_immutable, diminish_immutable
  31262. ] ) => {
  31263. const noiseType = int( noiseType_immutable ).toVar();
  31264. const position = vec3( position_immutable ).toVar();
  31265. const freq = vec3( freq_immutable ).toVar();
  31266. const offset = vec3( offset_immutable ).toVar();
  31267. const jitter = float( jitter_immutable ).toVar();
  31268. const outmin = float( outmin_immutable ).toVar();
  31269. const outmax = float( outmax_immutable ).toVar();
  31270. const clampoutput = bool( clampoutput_immutable ).toVar();
  31271. const octaves = int( octaves_immutable ).toVar();
  31272. const lacunarity = float( lacunarity_immutable ).toVar();
  31273. const diminish = float( diminish_immutable ).toVar();
  31274. // Compute input position
  31275. const p = position.mul( freq ).add( offset );
  31276. const result = float( 0.0 ).toVar();
  31277. // Perlin
  31278. If( noiseType.equal( int( 0 ) ), () => {
  31279. result.assign( mx_perlin_noise_vec3( p ) );
  31280. } );
  31281. // Cell
  31282. If( noiseType.equal( int( 1 ) ), () => {
  31283. result.assign( mx_cell_noise_vec3( p ) );
  31284. } );
  31285. // Worley (metric=0 = euclidean)
  31286. If( noiseType.equal( int( 2 ) ), () => {
  31287. result.assign( mx_worley_noise_vec3$1( p, jitter, int( 0 ) ) );
  31288. } );
  31289. // Fractal
  31290. If( noiseType.equal( int( 3 ) ), () => {
  31291. result.assign( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) );
  31292. } );
  31293. // Remap output to [outmin, outmax]
  31294. result.assign( result.mul( outmax.sub( outmin ) ).add( outmin ) );
  31295. // Clamp if requested
  31296. If( clampoutput, () => {
  31297. result.assign( clamp( result, outmin, outmax ) );
  31298. } );
  31299. return result;
  31300. } ).setLayout( {
  31301. name: 'mx_unifiednoise3d',
  31302. type: 'float',
  31303. inputs: [
  31304. { name: 'noiseType', type: 'int' },
  31305. { name: 'position', type: 'vec3' },
  31306. { name: 'freq', type: 'vec3' },
  31307. { name: 'offset', type: 'vec3' },
  31308. { name: 'jitter', type: 'float' },
  31309. { name: 'outmin', type: 'float' },
  31310. { name: 'outmax', type: 'float' },
  31311. { name: 'clampoutput', type: 'bool' },
  31312. { name: 'octaves', type: 'int' },
  31313. { name: 'lacunarity', type: 'float' },
  31314. { name: 'diminish', type: 'float' }
  31315. ]
  31316. } );
  31317. // Three.js Transpiler
  31318. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  31319. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  31320. const s = hsv.y;
  31321. const v = hsv.z;
  31322. const result = vec3().toVar();
  31323. If( s.lessThan( 0.0001 ), () => {
  31324. result.assign( vec3( v, v, v ) );
  31325. } ).Else( () => {
  31326. let h = hsv.x;
  31327. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  31328. const hi = int( trunc( h ) );
  31329. const f = h.sub( float( hi ) );
  31330. const p = v.mul( s.oneMinus() );
  31331. const q = v.mul( s.mul( f ).oneMinus() );
  31332. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  31333. If( hi.equal( int( 0 ) ), () => {
  31334. result.assign( vec3( v, t, p ) );
  31335. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  31336. result.assign( vec3( q, v, p ) );
  31337. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  31338. result.assign( vec3( p, v, t ) );
  31339. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  31340. result.assign( vec3( p, q, v ) );
  31341. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  31342. result.assign( vec3( t, p, v ) );
  31343. } ).Else( () => {
  31344. result.assign( vec3( v, p, q ) );
  31345. } );
  31346. } );
  31347. return result;
  31348. } ).setLayout( {
  31349. name: 'mx_hsvtorgb',
  31350. type: 'vec3',
  31351. inputs: [
  31352. { name: 'hsv', type: 'vec3' }
  31353. ]
  31354. } );
  31355. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  31356. const c = vec3( c_immutable ).toVar();
  31357. const r = float( c.x ).toVar();
  31358. const g = float( c.y ).toVar();
  31359. const b = float( c.z ).toVar();
  31360. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  31361. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  31362. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  31363. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  31364. v.assign( maxcomp );
  31365. If( maxcomp.greaterThan( 0.0 ), () => {
  31366. s.assign( delta.div( maxcomp ) );
  31367. } ).Else( () => {
  31368. s.assign( 0.0 );
  31369. } );
  31370. If( s.lessThanEqual( 0.0 ), () => {
  31371. h.assign( 0.0 );
  31372. } ).Else( () => {
  31373. If( r.greaterThanEqual( maxcomp ), () => {
  31374. h.assign( g.sub( b ).div( delta ) );
  31375. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  31376. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  31377. } ).Else( () => {
  31378. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  31379. } );
  31380. h.mulAssign( 1.0 / 6.0 );
  31381. If( h.lessThan( 0.0 ), () => {
  31382. h.addAssign( 1.0 );
  31383. } );
  31384. } );
  31385. return vec3( h, s, v );
  31386. } ).setLayout( {
  31387. name: 'mx_rgbtohsv',
  31388. type: 'vec3',
  31389. inputs: [
  31390. { name: 'c', type: 'vec3' }
  31391. ]
  31392. } );
  31393. // Three.js Transpiler
  31394. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  31395. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  31396. const color = vec3( color_immutable ).toVar();
  31397. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  31398. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  31399. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  31400. return mix( linSeg, powSeg, isAbove );
  31401. } ).setLayout( {
  31402. name: 'mx_srgb_texture_to_lin_rec709',
  31403. type: 'vec3',
  31404. inputs: [
  31405. { name: 'color', type: 'vec3' }
  31406. ]
  31407. } );
  31408. const mx_aastep = ( threshold, value ) => {
  31409. threshold = float( threshold );
  31410. value = float( value );
  31411. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  31412. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  31413. };
  31414. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  31415. const mx_ramplr = ( valuel, valuer, texcoord = uv$1() ) => _ramp( valuel, valuer, texcoord, 'x' );
  31416. const mx_ramptb = ( valuet, valueb, texcoord = uv$1() ) => _ramp( valuet, valueb, texcoord, 'y' );
  31417. // Bilinear ramp: interpolate between four corners (tl, tr, bl, br) using texcoord.x and texcoord.y
  31418. const mx_ramp4 = (
  31419. valuetl, valuetr, valuebl, valuebr, texcoord = uv$1()
  31420. ) => {
  31421. const u = texcoord.x.clamp();
  31422. const v = texcoord.y.clamp();
  31423. const top = mix( valuetl, valuetr, u );
  31424. const bottom = mix( valuebl, valuebr, u );
  31425. return mix( top, bottom, v );
  31426. };
  31427. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  31428. const mx_splitlr = ( valuel, valuer, center, texcoord = uv$1() ) => _split( valuel, valuer, center, texcoord, 'x' );
  31429. const mx_splittb = ( valuet, valueb, center, texcoord = uv$1() ) => _split( valuet, valueb, center, texcoord, 'y' );
  31430. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv$1() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  31431. const mx_safepower = ( in1, in2 = 1 ) => {
  31432. in1 = float( in1 );
  31433. return in1.abs().pow( in2 ).mul( in1.sign() );
  31434. };
  31435. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  31436. const mx_noise_float = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31437. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31438. const mx_noise_vec3 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  31439. const mx_noise_vec4 = ( texcoord = uv$1(), amplitude = 1, pivot = 0 ) => {
  31440. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  31441. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  31442. return noise_vec4.mul( amplitude ).add( pivot );
  31443. };
  31444. 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 );
  31445. 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 );
  31446. const mx_worley_noise_float = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  31447. const mx_worley_noise_vec2 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  31448. const mx_worley_noise_vec3 = ( texcoord = uv$1(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  31449. const mx_cell_noise_float = ( texcoord = uv$1() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  31450. 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 );
  31451. 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 );
  31452. 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 );
  31453. 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 );
  31454. // === Moved from MaterialXLoader.js ===
  31455. // Math ops
  31456. const mx_add = ( in1, in2 = float( 0 ) ) => add( in1, in2 );
  31457. const mx_subtract = ( in1, in2 = float( 0 ) ) => sub( in1, in2 );
  31458. const mx_multiply = ( in1, in2 = float( 1 ) ) => mul( in1, in2 );
  31459. const mx_divide = ( in1, in2 = float( 1 ) ) => div( in1, in2 );
  31460. const mx_modulo = ( in1, in2 = float( 1 ) ) => mod( in1, in2 );
  31461. const mx_power = ( in1, in2 = float( 1 ) ) => pow( in1, in2 );
  31462. const mx_atan2 = ( in1 = float( 0 ), in2 = float( 1 ) ) => atan( in1, in2 );
  31463. const mx_timer = () => time;
  31464. const mx_frame = () => frameId;
  31465. const mx_invert = ( in1, amount = float( 1 ) ) => sub( amount, in1 );
  31466. const mx_ifgreater = ( value1, value2, in1, in2 ) => value1.greaterThan( value2 ).mix( in1, in2 );
  31467. const mx_ifgreatereq = ( value1, value2, in1, in2 ) => value1.greaterThanEqual( value2 ).mix( in1, in2 );
  31468. const mx_ifequal = ( value1, value2, in1, in2 ) => value1.equal( value2 ).mix( in1, in2 );
  31469. // Enhanced separate node to support multi-output referencing (outx, outy, outz, outw)
  31470. const mx_separate = ( in1, channelOrOut = null ) => {
  31471. if ( typeof channelOrOut === 'string' ) {
  31472. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  31473. const c = channelOrOut.replace( /^out/, '' ).toLowerCase();
  31474. if ( map[ c ] !== undefined ) return in1.element( map[ c ] );
  31475. }
  31476. if ( typeof channelOrOut === 'number' ) {
  31477. return in1.element( channelOrOut );
  31478. }
  31479. if ( typeof channelOrOut === 'string' && channelOrOut.length === 1 ) {
  31480. const map = { x: 0, r: 0, y: 1, g: 1, z: 2, b: 2, w: 3, a: 3 };
  31481. if ( map[ channelOrOut ] !== undefined ) return in1.element( map[ channelOrOut ] );
  31482. }
  31483. return in1;
  31484. };
  31485. const mx_place2d = (
  31486. texcoord, pivot = vec2( 0.5, 0.5 ), scale = vec2( 1, 1 ), rotate = float( 0 ), offset = vec2( 0, 0 )/*, operationorder = int( 0 )*/
  31487. ) => {
  31488. let uv = texcoord;
  31489. if ( pivot ) uv = uv.sub( pivot );
  31490. if ( scale ) uv = uv.mul( scale );
  31491. if ( rotate ) {
  31492. const rad = rotate.mul( Math.PI / 180.0 );
  31493. const cosR = rad.cos();
  31494. const sinR = rad.sin();
  31495. uv = vec2(
  31496. uv.x.mul( cosR ).sub( uv.y.mul( sinR ) ),
  31497. uv.x.mul( sinR ).add( uv.y.mul( cosR ) )
  31498. );
  31499. }
  31500. if ( pivot ) uv = uv.add( pivot );
  31501. if ( offset ) uv = uv.add( offset );
  31502. return uv;
  31503. };
  31504. const mx_rotate2d = ( input, amount ) => {
  31505. input = vec2( input );
  31506. amount = float( amount );
  31507. const radians = amount.mul( Math.PI / 180.0 );
  31508. return rotate( input, radians );
  31509. };
  31510. const mx_rotate3d = ( input, amount, axis ) => {
  31511. input = vec3( input );
  31512. amount = float( amount );
  31513. axis = vec3( axis );
  31514. const radians = amount.mul( Math.PI / 180.0 );
  31515. const nAxis = axis.normalize();
  31516. const cosA = radians.cos();
  31517. const sinA = radians.sin();
  31518. const oneMinusCosA = float( 1 ).sub( cosA );
  31519. const rot =
  31520. input.mul( cosA )
  31521. .add( nAxis.cross( input ).mul( sinA ) )
  31522. .add( nAxis.mul( nAxis.dot( input ) ).mul( oneMinusCosA ) );
  31523. return rot;
  31524. };
  31525. const mx_heighttonormal = ( input, scale/*, texcoord*/ ) => {
  31526. input = vec3( input );
  31527. scale = float( scale );
  31528. return bumpMap( input, scale );
  31529. };
  31530. /**
  31531. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  31532. *
  31533. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  31534. *
  31535. * ```js
  31536. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  31537. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  31538. * ```
  31539. *
  31540. * @tsl
  31541. * @function
  31542. * @param {Node<vec3>} normal - The normal to correct.
  31543. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  31544. * @param {Node<vec3>} cubePos - The cube position.
  31545. * @return {Node<vec3>} The parallax corrected normal.
  31546. */
  31547. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  31548. const nDir = normalize( normal ).toVar();
  31549. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  31550. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  31551. const rbminmax = vec3().toVar();
  31552. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  31553. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  31554. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  31555. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  31556. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  31557. return boxIntersection.sub( cubePos );
  31558. } );
  31559. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  31560. // normal is assumed to have unit length
  31561. const x = normal.x, y = normal.y, z = normal.z;
  31562. // band 0
  31563. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  31564. // band 1
  31565. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  31566. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  31567. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  31568. // band 2
  31569. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  31570. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  31571. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  31572. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  31573. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  31574. return result;
  31575. } );
  31576. // constants
  31577. var TSL = /*#__PURE__*/Object.freeze({
  31578. __proto__: null,
  31579. BRDF_GGX: BRDF_GGX,
  31580. BRDF_Lambert: BRDF_Lambert,
  31581. BasicPointShadowFilter: BasicPointShadowFilter,
  31582. BasicShadowFilter: BasicShadowFilter,
  31583. Break: Break,
  31584. Const: Const,
  31585. Continue: Continue,
  31586. DFGApprox: DFGApprox,
  31587. D_GGX: D_GGX,
  31588. Discard: Discard,
  31589. EPSILON: EPSILON,
  31590. F_Schlick: F_Schlick,
  31591. Fn: Fn,
  31592. INFINITY: INFINITY,
  31593. If: If,
  31594. Loop: Loop,
  31595. NodeAccess: NodeAccess,
  31596. NodeShaderStage: NodeShaderStage,
  31597. NodeType: NodeType,
  31598. NodeUpdateType: NodeUpdateType,
  31599. OnMaterialUpdate: OnMaterialUpdate,
  31600. OnObjectUpdate: OnObjectUpdate,
  31601. PCFShadowFilter: PCFShadowFilter,
  31602. PCFSoftShadowFilter: PCFSoftShadowFilter,
  31603. PI: PI,
  31604. PI2: PI2,
  31605. PointShadowFilter: PointShadowFilter,
  31606. Return: Return,
  31607. Schlick_to_F0: Schlick_to_F0,
  31608. ScriptableNodeResources: ScriptableNodeResources,
  31609. ShaderNode: ShaderNode,
  31610. Stack: Stack,
  31611. Switch: Switch,
  31612. TBNViewMatrix: TBNViewMatrix,
  31613. VSMShadowFilter: VSMShadowFilter,
  31614. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  31615. Var: Var,
  31616. VarIntent: VarIntent,
  31617. abs: abs,
  31618. acesFilmicToneMapping: acesFilmicToneMapping,
  31619. acos: acos,
  31620. add: add,
  31621. addMethodChaining: addMethodChaining,
  31622. addNodeElement: addNodeElement,
  31623. agxToneMapping: agxToneMapping,
  31624. all: all,
  31625. alphaT: alphaT,
  31626. and: and,
  31627. anisotropy: anisotropy,
  31628. anisotropyB: anisotropyB,
  31629. anisotropyT: anisotropyT,
  31630. any: any,
  31631. append: append,
  31632. array: array,
  31633. arrayBuffer: arrayBuffer,
  31634. asin: asin,
  31635. assign: assign,
  31636. atan: atan,
  31637. atan2: atan2,
  31638. atomicAdd: atomicAdd,
  31639. atomicAnd: atomicAnd,
  31640. atomicFunc: atomicFunc,
  31641. atomicLoad: atomicLoad,
  31642. atomicMax: atomicMax,
  31643. atomicMin: atomicMin,
  31644. atomicOr: atomicOr,
  31645. atomicStore: atomicStore,
  31646. atomicSub: atomicSub,
  31647. atomicXor: atomicXor,
  31648. attenuationColor: attenuationColor,
  31649. attenuationDistance: attenuationDistance,
  31650. attribute: attribute,
  31651. attributeArray: attributeArray,
  31652. backgroundBlurriness: backgroundBlurriness,
  31653. backgroundIntensity: backgroundIntensity,
  31654. backgroundRotation: backgroundRotation,
  31655. batch: batch,
  31656. bentNormalView: bentNormalView,
  31657. billboarding: billboarding,
  31658. bitAnd: bitAnd,
  31659. bitNot: bitNot,
  31660. bitOr: bitOr,
  31661. bitXor: bitXor,
  31662. bitangentGeometry: bitangentGeometry,
  31663. bitangentLocal: bitangentLocal,
  31664. bitangentView: bitangentView,
  31665. bitangentWorld: bitangentWorld,
  31666. bitcast: bitcast,
  31667. blendBurn: blendBurn,
  31668. blendColor: blendColor,
  31669. blendDodge: blendDodge,
  31670. blendOverlay: blendOverlay,
  31671. blendScreen: blendScreen,
  31672. blur: blur,
  31673. bool: bool,
  31674. buffer: buffer,
  31675. bufferAttribute: bufferAttribute,
  31676. builtin: builtin,
  31677. bumpMap: bumpMap,
  31678. burn: burn,
  31679. bvec2: bvec2,
  31680. bvec3: bvec3,
  31681. bvec4: bvec4,
  31682. bypass: bypass,
  31683. cache: cache,
  31684. call: call,
  31685. cameraFar: cameraFar,
  31686. cameraIndex: cameraIndex,
  31687. cameraNear: cameraNear,
  31688. cameraNormalMatrix: cameraNormalMatrix,
  31689. cameraPosition: cameraPosition,
  31690. cameraProjectionMatrix: cameraProjectionMatrix,
  31691. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  31692. cameraViewMatrix: cameraViewMatrix,
  31693. cameraViewport: cameraViewport,
  31694. cameraWorldMatrix: cameraWorldMatrix,
  31695. cbrt: cbrt,
  31696. cdl: cdl,
  31697. ceil: ceil,
  31698. checker: checker,
  31699. cineonToneMapping: cineonToneMapping,
  31700. clamp: clamp,
  31701. clearcoat: clearcoat,
  31702. clearcoatNormalView: clearcoatNormalView,
  31703. clearcoatRoughness: clearcoatRoughness,
  31704. code: code,
  31705. color: color,
  31706. colorSpaceToWorking: colorSpaceToWorking,
  31707. colorToDirection: colorToDirection,
  31708. compute: compute,
  31709. computeKernel: computeKernel,
  31710. computeSkinning: computeSkinning,
  31711. context: context,
  31712. convert: convert,
  31713. convertColorSpace: convertColorSpace,
  31714. convertToTexture: convertToTexture,
  31715. cos: cos,
  31716. cross: cross,
  31717. cubeTexture: cubeTexture,
  31718. cubeTextureBase: cubeTextureBase,
  31719. cubeToUV: cubeToUV,
  31720. dFdx: dFdx,
  31721. dFdy: dFdy,
  31722. dashSize: dashSize,
  31723. debug: debug,
  31724. decrement: decrement,
  31725. decrementBefore: decrementBefore,
  31726. defaultBuildStages: defaultBuildStages,
  31727. defaultShaderStages: defaultShaderStages,
  31728. defined: defined,
  31729. degrees: degrees,
  31730. deltaTime: deltaTime,
  31731. densityFog: densityFog,
  31732. densityFogFactor: densityFogFactor,
  31733. depth: depth,
  31734. depthPass: depthPass,
  31735. determinant: determinant,
  31736. difference: difference,
  31737. diffuseColor: diffuseColor,
  31738. directPointLight: directPointLight,
  31739. directionToColor: directionToColor,
  31740. directionToFaceDirection: directionToFaceDirection,
  31741. dispersion: dispersion,
  31742. distance: distance,
  31743. div: div,
  31744. dodge: dodge,
  31745. dot: dot,
  31746. drawIndex: drawIndex,
  31747. dynamicBufferAttribute: dynamicBufferAttribute,
  31748. element: element,
  31749. emissive: emissive,
  31750. equal: equal,
  31751. equals: equals,
  31752. equirectUV: equirectUV,
  31753. exp: exp,
  31754. exp2: exp2,
  31755. expression: expression,
  31756. faceDirection: faceDirection,
  31757. faceForward: faceForward,
  31758. faceforward: faceforward,
  31759. float: float,
  31760. floatBitsToInt: floatBitsToInt,
  31761. floatBitsToUint: floatBitsToUint,
  31762. floor: floor,
  31763. fog: fog,
  31764. fract: fract,
  31765. frameGroup: frameGroup,
  31766. frameId: frameId,
  31767. frontFacing: frontFacing,
  31768. fwidth: fwidth,
  31769. gain: gain,
  31770. gapSize: gapSize,
  31771. getConstNodeType: getConstNodeType,
  31772. getCurrentStack: getCurrentStack,
  31773. getDirection: getDirection,
  31774. getDistanceAttenuation: getDistanceAttenuation,
  31775. getGeometryRoughness: getGeometryRoughness,
  31776. getNormalFromDepth: getNormalFromDepth,
  31777. getParallaxCorrectNormal: getParallaxCorrectNormal,
  31778. getRoughness: getRoughness,
  31779. getScreenPosition: getScreenPosition,
  31780. getShIrradianceAt: getShIrradianceAt,
  31781. getShadowMaterial: getShadowMaterial,
  31782. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  31783. getTextureIndex: getTextureIndex,
  31784. getViewPosition: getViewPosition,
  31785. globalId: globalId,
  31786. glsl: glsl,
  31787. glslFn: glslFn,
  31788. grayscale: grayscale,
  31789. greaterThan: greaterThan,
  31790. greaterThanEqual: greaterThanEqual,
  31791. hash: hash,
  31792. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  31793. highpModelViewMatrix: highpModelViewMatrix,
  31794. hue: hue,
  31795. increment: increment,
  31796. incrementBefore: incrementBefore,
  31797. instance: instance,
  31798. instanceIndex: instanceIndex,
  31799. instancedArray: instancedArray,
  31800. instancedBufferAttribute: instancedBufferAttribute,
  31801. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  31802. instancedMesh: instancedMesh,
  31803. int: int,
  31804. intBitsToFloat: intBitsToFloat,
  31805. inverse: inverse,
  31806. inverseSqrt: inverseSqrt,
  31807. inversesqrt: inversesqrt,
  31808. invocationLocalIndex: invocationLocalIndex,
  31809. invocationSubgroupIndex: invocationSubgroupIndex,
  31810. ior: ior,
  31811. iridescence: iridescence,
  31812. iridescenceIOR: iridescenceIOR,
  31813. iridescenceThickness: iridescenceThickness,
  31814. ivec2: ivec2,
  31815. ivec3: ivec3,
  31816. ivec4: ivec4,
  31817. js: js,
  31818. label: label,
  31819. length: length,
  31820. lengthSq: lengthSq,
  31821. lessThan: lessThan,
  31822. lessThanEqual: lessThanEqual,
  31823. lightPosition: lightPosition,
  31824. lightProjectionUV: lightProjectionUV,
  31825. lightShadowMatrix: lightShadowMatrix,
  31826. lightTargetDirection: lightTargetDirection,
  31827. lightTargetPosition: lightTargetPosition,
  31828. lightViewPosition: lightViewPosition,
  31829. lightingContext: lightingContext,
  31830. lights: lights,
  31831. linearDepth: linearDepth,
  31832. linearToneMapping: linearToneMapping,
  31833. localId: localId,
  31834. log: log,
  31835. log2: log2,
  31836. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  31837. luminance: luminance,
  31838. mat2: mat2,
  31839. mat3: mat3,
  31840. mat4: mat4,
  31841. matcapUV: matcapUV,
  31842. materialAO: materialAO,
  31843. materialAlphaTest: materialAlphaTest,
  31844. materialAnisotropy: materialAnisotropy,
  31845. materialAnisotropyVector: materialAnisotropyVector,
  31846. materialAttenuationColor: materialAttenuationColor,
  31847. materialAttenuationDistance: materialAttenuationDistance,
  31848. materialClearcoat: materialClearcoat,
  31849. materialClearcoatNormal: materialClearcoatNormal,
  31850. materialClearcoatRoughness: materialClearcoatRoughness,
  31851. materialColor: materialColor,
  31852. materialDispersion: materialDispersion,
  31853. materialEmissive: materialEmissive,
  31854. materialEnvIntensity: materialEnvIntensity,
  31855. materialEnvRotation: materialEnvRotation,
  31856. materialIOR: materialIOR,
  31857. materialIridescence: materialIridescence,
  31858. materialIridescenceIOR: materialIridescenceIOR,
  31859. materialIridescenceThickness: materialIridescenceThickness,
  31860. materialLightMap: materialLightMap,
  31861. materialLineDashOffset: materialLineDashOffset,
  31862. materialLineDashSize: materialLineDashSize,
  31863. materialLineGapSize: materialLineGapSize,
  31864. materialLineScale: materialLineScale,
  31865. materialLineWidth: materialLineWidth,
  31866. materialMetalness: materialMetalness,
  31867. materialNormal: materialNormal,
  31868. materialOpacity: materialOpacity,
  31869. materialPointSize: materialPointSize,
  31870. materialReference: materialReference,
  31871. materialReflectivity: materialReflectivity,
  31872. materialRefractionRatio: materialRefractionRatio,
  31873. materialRotation: materialRotation,
  31874. materialRoughness: materialRoughness,
  31875. materialSheen: materialSheen,
  31876. materialSheenRoughness: materialSheenRoughness,
  31877. materialShininess: materialShininess,
  31878. materialSpecular: materialSpecular,
  31879. materialSpecularColor: materialSpecularColor,
  31880. materialSpecularIntensity: materialSpecularIntensity,
  31881. materialSpecularStrength: materialSpecularStrength,
  31882. materialThickness: materialThickness,
  31883. materialTransmission: materialTransmission,
  31884. max: max$1,
  31885. maxMipLevel: maxMipLevel,
  31886. mediumpModelViewMatrix: mediumpModelViewMatrix,
  31887. metalness: metalness,
  31888. min: min$1,
  31889. mix: mix,
  31890. mixElement: mixElement,
  31891. mod: mod,
  31892. modInt: modInt,
  31893. modelDirection: modelDirection,
  31894. modelNormalMatrix: modelNormalMatrix,
  31895. modelPosition: modelPosition,
  31896. modelRadius: modelRadius,
  31897. modelScale: modelScale,
  31898. modelViewMatrix: modelViewMatrix,
  31899. modelViewPosition: modelViewPosition,
  31900. modelViewProjection: modelViewProjection,
  31901. modelWorldMatrix: modelWorldMatrix,
  31902. modelWorldMatrixInverse: modelWorldMatrixInverse,
  31903. morphReference: morphReference,
  31904. mrt: mrt,
  31905. mul: mul,
  31906. mx_aastep: mx_aastep,
  31907. mx_add: mx_add,
  31908. mx_atan2: mx_atan2,
  31909. mx_cell_noise_float: mx_cell_noise_float,
  31910. mx_contrast: mx_contrast,
  31911. mx_divide: mx_divide,
  31912. mx_fractal_noise_float: mx_fractal_noise_float,
  31913. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  31914. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  31915. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  31916. mx_frame: mx_frame,
  31917. mx_heighttonormal: mx_heighttonormal,
  31918. mx_hsvtorgb: mx_hsvtorgb,
  31919. mx_ifequal: mx_ifequal,
  31920. mx_ifgreater: mx_ifgreater,
  31921. mx_ifgreatereq: mx_ifgreatereq,
  31922. mx_invert: mx_invert,
  31923. mx_modulo: mx_modulo,
  31924. mx_multiply: mx_multiply,
  31925. mx_noise_float: mx_noise_float,
  31926. mx_noise_vec3: mx_noise_vec3,
  31927. mx_noise_vec4: mx_noise_vec4,
  31928. mx_place2d: mx_place2d,
  31929. mx_power: mx_power,
  31930. mx_ramp4: mx_ramp4,
  31931. mx_ramplr: mx_ramplr,
  31932. mx_ramptb: mx_ramptb,
  31933. mx_rgbtohsv: mx_rgbtohsv,
  31934. mx_rotate2d: mx_rotate2d,
  31935. mx_rotate3d: mx_rotate3d,
  31936. mx_safepower: mx_safepower,
  31937. mx_separate: mx_separate,
  31938. mx_splitlr: mx_splitlr,
  31939. mx_splittb: mx_splittb,
  31940. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  31941. mx_subtract: mx_subtract,
  31942. mx_timer: mx_timer,
  31943. mx_transform_uv: mx_transform_uv,
  31944. mx_unifiednoise2d: mx_unifiednoise2d,
  31945. mx_unifiednoise3d: mx_unifiednoise3d,
  31946. mx_worley_noise_float: mx_worley_noise_float,
  31947. mx_worley_noise_vec2: mx_worley_noise_vec2,
  31948. mx_worley_noise_vec3: mx_worley_noise_vec3,
  31949. negate: negate,
  31950. neutralToneMapping: neutralToneMapping,
  31951. nodeArray: nodeArray,
  31952. nodeImmutable: nodeImmutable,
  31953. nodeObject: nodeObject,
  31954. nodeObjectIntent: nodeObjectIntent,
  31955. nodeObjects: nodeObjects,
  31956. nodeProxy: nodeProxy,
  31957. nodeProxyIntent: nodeProxyIntent,
  31958. normalFlat: normalFlat,
  31959. normalGeometry: normalGeometry,
  31960. normalLocal: normalLocal,
  31961. normalMap: normalMap,
  31962. normalView: normalView,
  31963. normalViewGeometry: normalViewGeometry,
  31964. normalWorld: normalWorld,
  31965. normalWorldGeometry: normalWorldGeometry,
  31966. normalize: normalize,
  31967. not: not,
  31968. notEqual: notEqual,
  31969. numWorkgroups: numWorkgroups,
  31970. objectDirection: objectDirection,
  31971. objectGroup: objectGroup,
  31972. objectPosition: objectPosition,
  31973. objectRadius: objectRadius,
  31974. objectScale: objectScale,
  31975. objectViewPosition: objectViewPosition,
  31976. objectWorldMatrix: objectWorldMatrix,
  31977. oneMinus: oneMinus,
  31978. or: or,
  31979. orthographicDepthToViewZ: orthographicDepthToViewZ,
  31980. oscSawtooth: oscSawtooth,
  31981. oscSine: oscSine,
  31982. oscSquare: oscSquare,
  31983. oscTriangle: oscTriangle,
  31984. output: output,
  31985. outputStruct: outputStruct,
  31986. overlay: overlay,
  31987. overloadingFn: overloadingFn,
  31988. parabola: parabola,
  31989. parallaxDirection: parallaxDirection,
  31990. parallaxUV: parallaxUV,
  31991. parameter: parameter,
  31992. pass: pass,
  31993. passTexture: passTexture,
  31994. pcurve: pcurve,
  31995. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  31996. pmremTexture: pmremTexture,
  31997. pointShadow: pointShadow,
  31998. pointUV: pointUV,
  31999. pointWidth: pointWidth,
  32000. positionGeometry: positionGeometry,
  32001. positionLocal: positionLocal,
  32002. positionPrevious: positionPrevious,
  32003. positionView: positionView,
  32004. positionViewDirection: positionViewDirection,
  32005. positionWorld: positionWorld,
  32006. positionWorldDirection: positionWorldDirection,
  32007. posterize: posterize,
  32008. pow: pow,
  32009. pow2: pow2,
  32010. pow3: pow3,
  32011. pow4: pow4,
  32012. premultiplyAlpha: premultiplyAlpha,
  32013. property: property,
  32014. quadBroadcast: quadBroadcast,
  32015. quadSwapDiagonal: quadSwapDiagonal,
  32016. quadSwapX: quadSwapX,
  32017. quadSwapY: quadSwapY,
  32018. radians: radians,
  32019. rand: rand,
  32020. range: range,
  32021. rangeFog: rangeFog,
  32022. rangeFogFactor: rangeFogFactor,
  32023. reciprocal: reciprocal,
  32024. reference: reference,
  32025. referenceBuffer: referenceBuffer,
  32026. reflect: reflect,
  32027. reflectVector: reflectVector,
  32028. reflectView: reflectView,
  32029. reflector: reflector,
  32030. refract: refract,
  32031. refractVector: refractVector,
  32032. refractView: refractView,
  32033. reinhardToneMapping: reinhardToneMapping,
  32034. remap: remap,
  32035. remapClamp: remapClamp,
  32036. renderGroup: renderGroup,
  32037. renderOutput: renderOutput,
  32038. rendererReference: rendererReference,
  32039. rotate: rotate,
  32040. rotateUV: rotateUV,
  32041. roughness: roughness,
  32042. round: round,
  32043. rtt: rtt,
  32044. sRGBTransferEOTF: sRGBTransferEOTF,
  32045. sRGBTransferOETF: sRGBTransferOETF,
  32046. sample: sample,
  32047. sampler: sampler,
  32048. samplerComparison: samplerComparison,
  32049. saturate: saturate,
  32050. saturation: saturation,
  32051. screen: screen,
  32052. screenCoordinate: screenCoordinate,
  32053. screenDPR: screenDPR,
  32054. screenSize: screenSize,
  32055. screenUV: screenUV,
  32056. scriptable: scriptable,
  32057. scriptableValue: scriptableValue,
  32058. select: select,
  32059. setCurrentStack: setCurrentStack,
  32060. setName: setName,
  32061. shaderStages: shaderStages,
  32062. shadow: shadow,
  32063. shadowPositionWorld: shadowPositionWorld,
  32064. shapeCircle: shapeCircle,
  32065. sharedUniformGroup: sharedUniformGroup,
  32066. sheen: sheen,
  32067. sheenRoughness: sheenRoughness,
  32068. shiftLeft: shiftLeft,
  32069. shiftRight: shiftRight,
  32070. shininess: shininess,
  32071. sign: sign,
  32072. sin: sin,
  32073. sinc: sinc,
  32074. skinning: skinning,
  32075. smoothstep: smoothstep,
  32076. smoothstepElement: smoothstepElement,
  32077. specularColor: specularColor,
  32078. specularF90: specularF90,
  32079. spherizeUV: spherizeUV,
  32080. split: split,
  32081. spritesheetUV: spritesheetUV,
  32082. sqrt: sqrt,
  32083. stack: stack,
  32084. step: step,
  32085. stepElement: stepElement,
  32086. storage: storage,
  32087. storageBarrier: storageBarrier,
  32088. storageObject: storageObject,
  32089. storageTexture: storageTexture,
  32090. string: string,
  32091. struct: struct,
  32092. sub: sub,
  32093. subBuild: subBuild,
  32094. subgroupAdd: subgroupAdd,
  32095. subgroupAll: subgroupAll,
  32096. subgroupAnd: subgroupAnd,
  32097. subgroupAny: subgroupAny,
  32098. subgroupBallot: subgroupBallot,
  32099. subgroupBroadcast: subgroupBroadcast,
  32100. subgroupBroadcastFirst: subgroupBroadcastFirst,
  32101. subgroupElect: subgroupElect,
  32102. subgroupExclusiveAdd: subgroupExclusiveAdd,
  32103. subgroupExclusiveMul: subgroupExclusiveMul,
  32104. subgroupInclusiveAdd: subgroupInclusiveAdd,
  32105. subgroupInclusiveMul: subgroupInclusiveMul,
  32106. subgroupIndex: subgroupIndex,
  32107. subgroupMax: subgroupMax,
  32108. subgroupMin: subgroupMin,
  32109. subgroupMul: subgroupMul,
  32110. subgroupOr: subgroupOr,
  32111. subgroupShuffle: subgroupShuffle,
  32112. subgroupShuffleDown: subgroupShuffleDown,
  32113. subgroupShuffleUp: subgroupShuffleUp,
  32114. subgroupShuffleXor: subgroupShuffleXor,
  32115. subgroupSize: subgroupSize,
  32116. subgroupXor: subgroupXor,
  32117. tan: tan,
  32118. tangentGeometry: tangentGeometry,
  32119. tangentLocal: tangentLocal,
  32120. tangentView: tangentView,
  32121. tangentWorld: tangentWorld,
  32122. texture: texture,
  32123. texture3D: texture3D,
  32124. textureBarrier: textureBarrier,
  32125. textureBicubic: textureBicubic,
  32126. textureBicubicLevel: textureBicubicLevel,
  32127. textureCubeUV: textureCubeUV,
  32128. textureLoad: textureLoad,
  32129. textureSize: textureSize,
  32130. textureStore: textureStore,
  32131. thickness: thickness,
  32132. time: time,
  32133. toneMapping: toneMapping,
  32134. toneMappingExposure: toneMappingExposure,
  32135. toonOutlinePass: toonOutlinePass,
  32136. transformDirection: transformDirection,
  32137. transformNormal: transformNormal,
  32138. transformNormalToView: transformNormalToView,
  32139. transformedClearcoatNormalView: transformedClearcoatNormalView,
  32140. transformedNormalView: transformedNormalView,
  32141. transformedNormalWorld: transformedNormalWorld,
  32142. transmission: transmission,
  32143. transpose: transpose,
  32144. triNoise3D: triNoise3D,
  32145. triplanarTexture: triplanarTexture,
  32146. triplanarTextures: triplanarTextures,
  32147. trunc: trunc,
  32148. uint: uint,
  32149. uintBitsToFloat: uintBitsToFloat,
  32150. uniform: uniform,
  32151. uniformArray: uniformArray,
  32152. uniformCubeTexture: uniformCubeTexture,
  32153. uniformFlow: uniformFlow,
  32154. uniformGroup: uniformGroup,
  32155. uniformTexture: uniformTexture,
  32156. unpremultiplyAlpha: unpremultiplyAlpha,
  32157. userData: userData,
  32158. uv: uv$1,
  32159. uvec2: uvec2,
  32160. uvec3: uvec3,
  32161. uvec4: uvec4,
  32162. varying: varying,
  32163. varyingProperty: varyingProperty,
  32164. vec2: vec2,
  32165. vec3: vec3,
  32166. vec4: vec4,
  32167. vectorComponents: vectorComponents,
  32168. velocity: velocity,
  32169. vertexColor: vertexColor,
  32170. vertexIndex: vertexIndex,
  32171. vertexStage: vertexStage,
  32172. vibrance: vibrance,
  32173. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  32174. viewZToOrthographicDepth: viewZToOrthographicDepth,
  32175. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  32176. viewport: viewport,
  32177. viewportCoordinate: viewportCoordinate,
  32178. viewportDepthTexture: viewportDepthTexture,
  32179. viewportLinearDepth: viewportLinearDepth,
  32180. viewportMipTexture: viewportMipTexture,
  32181. viewportResolution: viewportResolution,
  32182. viewportSafeUV: viewportSafeUV,
  32183. viewportSharedTexture: viewportSharedTexture,
  32184. viewportSize: viewportSize,
  32185. viewportTexture: viewportTexture,
  32186. viewportUV: viewportUV,
  32187. wgsl: wgsl,
  32188. wgslFn: wgslFn,
  32189. workgroupArray: workgroupArray,
  32190. workgroupBarrier: workgroupBarrier,
  32191. workgroupId: workgroupId,
  32192. workingToColorSpace: workingToColorSpace,
  32193. xor: xor
  32194. });
  32195. const _clearColor = /*@__PURE__*/ new Color4();
  32196. /**
  32197. * This renderer module manages the background.
  32198. *
  32199. * @private
  32200. * @augments DataMap
  32201. */
  32202. class Background extends DataMap {
  32203. /**
  32204. * Constructs a new background management component.
  32205. *
  32206. * @param {Renderer} renderer - The renderer.
  32207. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  32208. */
  32209. constructor( renderer, nodes ) {
  32210. super();
  32211. /**
  32212. * The renderer.
  32213. *
  32214. * @type {Renderer}
  32215. */
  32216. this.renderer = renderer;
  32217. /**
  32218. * Renderer component for managing nodes related logic.
  32219. *
  32220. * @type {Nodes}
  32221. */
  32222. this.nodes = nodes;
  32223. }
  32224. /**
  32225. * Updates the background for the given scene. Depending on how `Scene.background`
  32226. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  32227. * or add a mesh to the render list for rendering the background as a textured plane
  32228. * or skybox.
  32229. *
  32230. * @param {Scene} scene - The scene.
  32231. * @param {RenderList} renderList - The current render list.
  32232. * @param {RenderContext} renderContext - The current render context.
  32233. */
  32234. update( scene, renderList, renderContext ) {
  32235. const renderer = this.renderer;
  32236. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  32237. let forceClear = false;
  32238. if ( background === null ) {
  32239. // no background settings, use clear color configuration from the renderer
  32240. renderer._clearColor.getRGB( _clearColor );
  32241. _clearColor.a = renderer._clearColor.a;
  32242. } else if ( background.isColor === true ) {
  32243. // background is an opaque color
  32244. background.getRGB( _clearColor );
  32245. _clearColor.a = 1;
  32246. forceClear = true;
  32247. } else if ( background.isNode === true ) {
  32248. const sceneData = this.get( scene );
  32249. const backgroundNode = background;
  32250. _clearColor.copy( renderer._clearColor );
  32251. let backgroundMesh = sceneData.backgroundMesh;
  32252. if ( backgroundMesh === undefined ) {
  32253. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  32254. // @TODO: Add Texture2D support using node context
  32255. getUV: () => backgroundRotation.mul( normalWorldGeometry ),
  32256. getTextureLevel: () => backgroundBlurriness
  32257. } );
  32258. let viewProj = modelViewProjection;
  32259. viewProj = viewProj.setZ( viewProj.w );
  32260. const nodeMaterial = new NodeMaterial();
  32261. nodeMaterial.name = 'Background.material';
  32262. nodeMaterial.side = BackSide;
  32263. nodeMaterial.depthTest = false;
  32264. nodeMaterial.depthWrite = false;
  32265. nodeMaterial.allowOverride = false;
  32266. nodeMaterial.fog = false;
  32267. nodeMaterial.lights = false;
  32268. nodeMaterial.vertexNode = viewProj;
  32269. nodeMaterial.colorNode = backgroundMeshNode;
  32270. sceneData.backgroundMeshNode = backgroundMeshNode;
  32271. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  32272. backgroundMesh.frustumCulled = false;
  32273. backgroundMesh.name = 'Background.mesh';
  32274. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  32275. this.matrixWorld.copyPosition( camera.matrixWorld );
  32276. };
  32277. function onBackgroundDispose() {
  32278. background.removeEventListener( 'dispose', onBackgroundDispose );
  32279. backgroundMesh.material.dispose();
  32280. backgroundMesh.geometry.dispose();
  32281. }
  32282. background.addEventListener( 'dispose', onBackgroundDispose );
  32283. }
  32284. const backgroundCacheKey = backgroundNode.getCacheKey();
  32285. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  32286. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  32287. sceneData.backgroundMeshNode.needsUpdate = true;
  32288. backgroundMesh.material.needsUpdate = true;
  32289. sceneData.backgroundCacheKey = backgroundCacheKey;
  32290. }
  32291. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  32292. } else {
  32293. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  32294. }
  32295. //
  32296. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  32297. if ( environmentBlendMode === 'additive' ) {
  32298. _clearColor.set( 0, 0, 0, 1 );
  32299. } else if ( environmentBlendMode === 'alpha-blend' ) {
  32300. _clearColor.set( 0, 0, 0, 0 );
  32301. }
  32302. //
  32303. if ( renderer.autoClear === true || forceClear === true ) {
  32304. const clearColorValue = renderContext.clearColorValue;
  32305. clearColorValue.r = _clearColor.r;
  32306. clearColorValue.g = _clearColor.g;
  32307. clearColorValue.b = _clearColor.b;
  32308. clearColorValue.a = _clearColor.a;
  32309. // premultiply alpha
  32310. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  32311. clearColorValue.r *= clearColorValue.a;
  32312. clearColorValue.g *= clearColorValue.a;
  32313. clearColorValue.b *= clearColorValue.a;
  32314. }
  32315. //
  32316. renderContext.depthClearValue = renderer._clearDepth;
  32317. renderContext.stencilClearValue = renderer._clearStencil;
  32318. renderContext.clearColor = renderer.autoClearColor === true;
  32319. renderContext.clearDepth = renderer.autoClearDepth === true;
  32320. renderContext.clearStencil = renderer.autoClearStencil === true;
  32321. } else {
  32322. renderContext.clearColor = false;
  32323. renderContext.clearDepth = false;
  32324. renderContext.clearStencil = false;
  32325. }
  32326. }
  32327. }
  32328. let _id$6 = 0;
  32329. /**
  32330. * A bind group represents a collection of bindings and thus a collection
  32331. * or resources. Bind groups are assigned to pipelines to provide them
  32332. * with the required resources (like uniform buffers or textures).
  32333. *
  32334. * @private
  32335. */
  32336. class BindGroup {
  32337. /**
  32338. * Constructs a new bind group.
  32339. *
  32340. * @param {string} name - The bind group's name.
  32341. * @param {Array<Binding>} bindings - An array of bindings.
  32342. * @param {number} index - The group index.
  32343. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  32344. */
  32345. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  32346. /**
  32347. * The bind group's name.
  32348. *
  32349. * @type {string}
  32350. */
  32351. this.name = name;
  32352. /**
  32353. * An array of bindings.
  32354. *
  32355. * @type {Array<Binding>}
  32356. */
  32357. this.bindings = bindings;
  32358. /**
  32359. * The group index.
  32360. *
  32361. * @type {number}
  32362. */
  32363. this.index = index;
  32364. /**
  32365. * An array of reference bindings.
  32366. *
  32367. * @type {Array<Binding>}
  32368. */
  32369. this.bindingsReference = bindingsReference;
  32370. /**
  32371. * The group's ID.
  32372. *
  32373. * @type {number}
  32374. */
  32375. this.id = _id$6 ++;
  32376. }
  32377. }
  32378. /**
  32379. * This module represents the state of a node builder after it was
  32380. * used to build the nodes for a render object. The state holds the
  32381. * results of the build for further processing in the renderer.
  32382. *
  32383. * Render objects with identical cache keys share the same node builder state.
  32384. *
  32385. * @private
  32386. */
  32387. class NodeBuilderState {
  32388. /**
  32389. * Constructs a new node builder state.
  32390. *
  32391. * @param {string} vertexShader - The native vertex shader code.
  32392. * @param {string} fragmentShader - The native fragment shader code.
  32393. * @param {string} computeShader - The native compute shader code.
  32394. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  32395. * @param {Array<BindGroup>} bindings - An array of bind groups.
  32396. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  32397. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  32398. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  32399. * @param {NodeMaterialObserver} observer - A node material observer.
  32400. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  32401. */
  32402. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  32403. /**
  32404. * The native vertex shader code.
  32405. *
  32406. * @type {string}
  32407. */
  32408. this.vertexShader = vertexShader;
  32409. /**
  32410. * The native fragment shader code.
  32411. *
  32412. * @type {string}
  32413. */
  32414. this.fragmentShader = fragmentShader;
  32415. /**
  32416. * The native compute shader code.
  32417. *
  32418. * @type {string}
  32419. */
  32420. this.computeShader = computeShader;
  32421. /**
  32422. * An array with transform attribute objects.
  32423. * Only relevant when using compute shaders with WebGL 2.
  32424. *
  32425. * @type {Array<Object>}
  32426. */
  32427. this.transforms = transforms;
  32428. /**
  32429. * An array of node attributes representing
  32430. * the attributes of the shaders.
  32431. *
  32432. * @type {Array<NodeAttribute>}
  32433. */
  32434. this.nodeAttributes = nodeAttributes;
  32435. /**
  32436. * An array of bind groups representing the uniform or storage
  32437. * buffers, texture or samplers of the shader.
  32438. *
  32439. * @type {Array<BindGroup>}
  32440. */
  32441. this.bindings = bindings;
  32442. /**
  32443. * An array of nodes that implement their `update()` method.
  32444. *
  32445. * @type {Array<Node>}
  32446. */
  32447. this.updateNodes = updateNodes;
  32448. /**
  32449. * An array of nodes that implement their `updateBefore()` method.
  32450. *
  32451. * @type {Array<Node>}
  32452. */
  32453. this.updateBeforeNodes = updateBeforeNodes;
  32454. /**
  32455. * An array of nodes that implement their `updateAfter()` method.
  32456. *
  32457. * @type {Array<Node>}
  32458. */
  32459. this.updateAfterNodes = updateAfterNodes;
  32460. /**
  32461. * A node material observer.
  32462. *
  32463. * @type {NodeMaterialObserver}
  32464. */
  32465. this.observer = observer;
  32466. /**
  32467. * How often this state is used by render objects.
  32468. *
  32469. * @type {number}
  32470. */
  32471. this.usedTimes = 0;
  32472. }
  32473. /**
  32474. * This method is used to create a array of bind groups based
  32475. * on the existing bind groups of this state. Shared groups are
  32476. * not cloned.
  32477. *
  32478. * @return {Array<BindGroup>} A array of bind groups.
  32479. */
  32480. createBindings() {
  32481. const bindings = [];
  32482. for ( const instanceGroup of this.bindings ) {
  32483. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  32484. if ( shared !== true ) {
  32485. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup.bindingsReference );
  32486. bindings.push( bindingsGroup );
  32487. for ( const instanceBinding of instanceGroup.bindings ) {
  32488. bindingsGroup.bindings.push( instanceBinding.clone() );
  32489. }
  32490. } else {
  32491. bindings.push( instanceGroup );
  32492. }
  32493. }
  32494. return bindings;
  32495. }
  32496. }
  32497. /**
  32498. * {@link NodeBuilder} is going to create instances of this class during the build process
  32499. * of nodes. They represent the final shader attributes that are going to be generated
  32500. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  32501. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  32502. */
  32503. class NodeAttribute {
  32504. /**
  32505. * Constructs a new node attribute.
  32506. *
  32507. * @param {string} name - The name of the attribute.
  32508. * @param {string} type - The type of the attribute.
  32509. * @param {?Node} node - An optional reference to the node.
  32510. */
  32511. constructor( name, type, node = null ) {
  32512. /**
  32513. * This flag can be used for type testing.
  32514. *
  32515. * @type {boolean}
  32516. * @readonly
  32517. * @default true
  32518. */
  32519. this.isNodeAttribute = true;
  32520. /**
  32521. * The name of the attribute.
  32522. *
  32523. * @type {string}
  32524. */
  32525. this.name = name;
  32526. /**
  32527. * The type of the attribute.
  32528. *
  32529. * @type {string}
  32530. */
  32531. this.type = type;
  32532. /**
  32533. * An optional reference to the node.
  32534. *
  32535. * @type {?Node}
  32536. * @default null
  32537. */
  32538. this.node = node;
  32539. }
  32540. }
  32541. /**
  32542. * {@link NodeBuilder} is going to create instances of this class during the build process
  32543. * of nodes. They represent the final shader uniforms that are going to be generated
  32544. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  32545. * for this purpose.
  32546. */
  32547. class NodeUniform {
  32548. /**
  32549. * Constructs a new node uniform.
  32550. *
  32551. * @param {string} name - The name of the uniform.
  32552. * @param {string} type - The type of the uniform.
  32553. * @param {UniformNode} node - An reference to the node.
  32554. */
  32555. constructor( name, type, node ) {
  32556. /**
  32557. * This flag can be used for type testing.
  32558. *
  32559. * @type {boolean}
  32560. * @readonly
  32561. * @default true
  32562. */
  32563. this.isNodeUniform = true;
  32564. /**
  32565. * The name of the uniform.
  32566. *
  32567. * @type {string}
  32568. */
  32569. this.name = name;
  32570. /**
  32571. * The type of the uniform.
  32572. *
  32573. * @type {string}
  32574. */
  32575. this.type = type;
  32576. /**
  32577. * An reference to the node.
  32578. *
  32579. * @type {UniformNode}
  32580. */
  32581. this.node = node;
  32582. }
  32583. /**
  32584. * The value of the uniform node.
  32585. *
  32586. * @type {any}
  32587. */
  32588. get value() {
  32589. return this.node.value;
  32590. }
  32591. set value( val ) {
  32592. this.node.value = val;
  32593. }
  32594. /**
  32595. * The id of the uniform node.
  32596. *
  32597. * @type {number}
  32598. */
  32599. get id() {
  32600. return this.node.id;
  32601. }
  32602. /**
  32603. * The uniform node's group.
  32604. *
  32605. * @type {UniformGroupNode}
  32606. */
  32607. get groupNode() {
  32608. return this.node.groupNode;
  32609. }
  32610. }
  32611. /**
  32612. * {@link NodeBuilder} is going to create instances of this class during the build process
  32613. * of nodes. They represent the final shader variables that are going to be generated
  32614. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  32615. * this purpose.
  32616. */
  32617. class NodeVar {
  32618. /**
  32619. * Constructs a new node variable.
  32620. *
  32621. * @param {string} name - The name of the variable.
  32622. * @param {string} type - The type of the variable.
  32623. * @param {boolean} [readOnly=false] - The read-only flag.
  32624. * @param {?number} [count=null] - The size.
  32625. */
  32626. constructor( name, type, readOnly = false, count = null ) {
  32627. /**
  32628. * This flag can be used for type testing.
  32629. *
  32630. * @type {boolean}
  32631. * @readonly
  32632. * @default true
  32633. */
  32634. this.isNodeVar = true;
  32635. /**
  32636. * The name of the variable.
  32637. *
  32638. * @type {string}
  32639. */
  32640. this.name = name;
  32641. /**
  32642. * The type of the variable.
  32643. *
  32644. * @type {string}
  32645. */
  32646. this.type = type;
  32647. /**
  32648. * The read-only flag.
  32649. *
  32650. * @type {boolean}
  32651. */
  32652. this.readOnly = readOnly;
  32653. /**
  32654. * The size.
  32655. *
  32656. * @type {?number}
  32657. */
  32658. this.count = count;
  32659. }
  32660. }
  32661. /**
  32662. * {@link NodeBuilder} is going to create instances of this class during the build process
  32663. * of nodes. They represent the final shader varyings that are going to be generated
  32664. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  32665. * this purpose.
  32666. *
  32667. * @augments NodeVar
  32668. */
  32669. class NodeVarying extends NodeVar {
  32670. /**
  32671. * Constructs a new node varying.
  32672. *
  32673. * @param {string} name - The name of the varying.
  32674. * @param {string} type - The type of the varying.
  32675. * @param {?string} interpolationType - The interpolation type of the varying.
  32676. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  32677. */
  32678. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  32679. super( name, type );
  32680. /**
  32681. * Whether this varying requires interpolation or not. This property can be used
  32682. * to check if the varying can be optimized for a variable.
  32683. *
  32684. * @type {boolean}
  32685. * @default false
  32686. */
  32687. this.needsInterpolation = false;
  32688. /**
  32689. * This flag can be used for type testing.
  32690. *
  32691. * @type {boolean}
  32692. * @readonly
  32693. * @default true
  32694. */
  32695. this.isNodeVarying = true;
  32696. /**
  32697. * The interpolation type of the varying data.
  32698. *
  32699. * @type {?string}
  32700. * @default null
  32701. */
  32702. this.interpolationType = interpolationType;
  32703. /**
  32704. * The interpolation sampling type of varying data.
  32705. *
  32706. * @type {?string}
  32707. * @default null
  32708. */
  32709. this.interpolationSampling = interpolationSampling;
  32710. }
  32711. }
  32712. /**
  32713. * {@link NodeBuilder} is going to create instances of this class during the build process
  32714. * of nodes. They represent user-defined, native shader code portions that are going to be
  32715. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  32716. * for this purpose.
  32717. */
  32718. class NodeCode {
  32719. /**
  32720. * Constructs a new code node.
  32721. *
  32722. * @param {string} name - The name of the code.
  32723. * @param {string} type - The node type.
  32724. * @param {string} [code=''] - The native shader code.
  32725. */
  32726. constructor( name, type, code = '' ) {
  32727. /**
  32728. * The name of the code.
  32729. *
  32730. * @type {string}
  32731. */
  32732. this.name = name;
  32733. /**
  32734. * The node type.
  32735. *
  32736. * @type {string}
  32737. */
  32738. this.type = type;
  32739. /**
  32740. * The native shader code.
  32741. *
  32742. * @type {string}
  32743. * @default ''
  32744. */
  32745. this.code = code;
  32746. Object.defineProperty( this, 'isNodeCode', { value: true } );
  32747. }
  32748. }
  32749. let _id$5 = 0;
  32750. /**
  32751. * This utility class is used in {@link NodeBuilder} as an internal
  32752. * cache data structure for node data.
  32753. */
  32754. class NodeCache {
  32755. /**
  32756. * Constructs a new node cache.
  32757. *
  32758. * @param {?NodeCache} parent - A reference to a parent cache.
  32759. */
  32760. constructor( parent = null ) {
  32761. /**
  32762. * The id of the cache.
  32763. *
  32764. * @type {number}
  32765. * @readonly
  32766. */
  32767. this.id = _id$5 ++;
  32768. /**
  32769. * A weak map for managing node data.
  32770. *
  32771. * @type {WeakMap<Node, Object>}
  32772. */
  32773. this.nodesData = new WeakMap();
  32774. /**
  32775. * Reference to a parent node cache.
  32776. *
  32777. * @type {?NodeCache}
  32778. * @default null
  32779. */
  32780. this.parent = parent;
  32781. }
  32782. /**
  32783. * Returns the data for the given node.
  32784. *
  32785. * @param {Node} node - The node.
  32786. * @return {?Object} The data for the node.
  32787. */
  32788. getData( node ) {
  32789. let data = this.nodesData.get( node );
  32790. if ( data === undefined && this.parent !== null ) {
  32791. data = this.parent.getData( node );
  32792. }
  32793. return data;
  32794. }
  32795. /**
  32796. * Sets the data for a given node.
  32797. *
  32798. * @param {Node} node - The node.
  32799. * @param {Object} data - The data that should be cached.
  32800. */
  32801. setData( node, data ) {
  32802. this.nodesData.set( node, data );
  32803. }
  32804. }
  32805. class StructType {
  32806. constructor( name, members ) {
  32807. this.name = name;
  32808. this.members = members;
  32809. this.output = false;
  32810. }
  32811. }
  32812. /**
  32813. * Abstract base class for uniforms.
  32814. *
  32815. * @abstract
  32816. * @private
  32817. */
  32818. class Uniform {
  32819. /**
  32820. * Constructs a new uniform.
  32821. *
  32822. * @param {string} name - The uniform's name.
  32823. * @param {any} value - The uniform's value.
  32824. */
  32825. constructor( name, value ) {
  32826. /**
  32827. * The uniform's name.
  32828. *
  32829. * @type {string}
  32830. */
  32831. this.name = name;
  32832. /**
  32833. * The uniform's value.
  32834. *
  32835. * @type {any}
  32836. */
  32837. this.value = value;
  32838. /**
  32839. * Used to build the uniform buffer according to the STD140 layout.
  32840. * Derived uniforms will set this property to a data type specific
  32841. * value.
  32842. *
  32843. * @type {number}
  32844. */
  32845. this.boundary = 0;
  32846. /**
  32847. * The item size. Derived uniforms will set this property to a data
  32848. * type specific value.
  32849. *
  32850. * @type {number}
  32851. */
  32852. this.itemSize = 0;
  32853. /**
  32854. * This property is set by {@link UniformsGroup} and marks
  32855. * the start position in the uniform buffer.
  32856. *
  32857. * @type {number}
  32858. */
  32859. this.offset = 0;
  32860. }
  32861. /**
  32862. * Sets the uniform's value.
  32863. *
  32864. * @param {any} value - The value to set.
  32865. */
  32866. setValue( value ) {
  32867. this.value = value;
  32868. }
  32869. /**
  32870. * Returns the uniform's value.
  32871. *
  32872. * @return {any} The value.
  32873. */
  32874. getValue() {
  32875. return this.value;
  32876. }
  32877. }
  32878. /**
  32879. * Represents a Number uniform.
  32880. *
  32881. * @private
  32882. * @augments Uniform
  32883. */
  32884. class NumberUniform extends Uniform {
  32885. /**
  32886. * Constructs a new Number uniform.
  32887. *
  32888. * @param {string} name - The uniform's name.
  32889. * @param {number} value - The uniform's value.
  32890. */
  32891. constructor( name, value = 0 ) {
  32892. super( name, value );
  32893. /**
  32894. * This flag can be used for type testing.
  32895. *
  32896. * @type {boolean}
  32897. * @readonly
  32898. * @default true
  32899. */
  32900. this.isNumberUniform = true;
  32901. this.boundary = 4;
  32902. this.itemSize = 1;
  32903. }
  32904. }
  32905. /**
  32906. * Represents a Vector2 uniform.
  32907. *
  32908. * @private
  32909. * @augments Uniform
  32910. */
  32911. class Vector2Uniform extends Uniform {
  32912. /**
  32913. * Constructs a new Number uniform.
  32914. *
  32915. * @param {string} name - The uniform's name.
  32916. * @param {Vector2} value - The uniform's value.
  32917. */
  32918. constructor( name, value = new Vector2() ) {
  32919. super( name, value );
  32920. /**
  32921. * This flag can be used for type testing.
  32922. *
  32923. * @type {boolean}
  32924. * @readonly
  32925. * @default true
  32926. */
  32927. this.isVector2Uniform = true;
  32928. this.boundary = 8;
  32929. this.itemSize = 2;
  32930. }
  32931. }
  32932. /**
  32933. * Represents a Vector3 uniform.
  32934. *
  32935. * @private
  32936. * @augments Uniform
  32937. */
  32938. class Vector3Uniform extends Uniform {
  32939. /**
  32940. * Constructs a new Number uniform.
  32941. *
  32942. * @param {string} name - The uniform's name.
  32943. * @param {Vector3} value - The uniform's value.
  32944. */
  32945. constructor( name, value = new Vector3() ) {
  32946. super( name, value );
  32947. /**
  32948. * This flag can be used for type testing.
  32949. *
  32950. * @type {boolean}
  32951. * @readonly
  32952. * @default true
  32953. */
  32954. this.isVector3Uniform = true;
  32955. this.boundary = 16;
  32956. this.itemSize = 3;
  32957. }
  32958. }
  32959. /**
  32960. * Represents a Vector4 uniform.
  32961. *
  32962. * @private
  32963. * @augments Uniform
  32964. */
  32965. class Vector4Uniform extends Uniform {
  32966. /**
  32967. * Constructs a new Number uniform.
  32968. *
  32969. * @param {string} name - The uniform's name.
  32970. * @param {Vector4} value - The uniform's value.
  32971. */
  32972. constructor( name, value = new Vector4() ) {
  32973. super( name, value );
  32974. /**
  32975. * This flag can be used for type testing.
  32976. *
  32977. * @type {boolean}
  32978. * @readonly
  32979. * @default true
  32980. */
  32981. this.isVector4Uniform = true;
  32982. this.boundary = 16;
  32983. this.itemSize = 4;
  32984. }
  32985. }
  32986. /**
  32987. * Represents a Color uniform.
  32988. *
  32989. * @private
  32990. * @augments Uniform
  32991. */
  32992. class ColorUniform extends Uniform {
  32993. /**
  32994. * Constructs a new Number uniform.
  32995. *
  32996. * @param {string} name - The uniform's name.
  32997. * @param {Color} value - The uniform's value.
  32998. */
  32999. constructor( name, value = new Color() ) {
  33000. super( name, value );
  33001. /**
  33002. * This flag can be used for type testing.
  33003. *
  33004. * @type {boolean}
  33005. * @readonly
  33006. * @default true
  33007. */
  33008. this.isColorUniform = true;
  33009. this.boundary = 16;
  33010. this.itemSize = 3;
  33011. }
  33012. }
  33013. /**
  33014. * Represents a Matrix2 uniform.
  33015. *
  33016. * @private
  33017. * @augments Uniform
  33018. */
  33019. class Matrix2Uniform extends Uniform {
  33020. /**
  33021. * Constructs a new Number uniform.
  33022. *
  33023. * @param {string} name - The uniform's name.
  33024. * @param {Matrix2} value - The uniform's value.
  33025. */
  33026. constructor( name, value = new Matrix2() ) {
  33027. super( name, value );
  33028. /**
  33029. * This flag can be used for type testing.
  33030. *
  33031. * @type {boolean}
  33032. * @readonly
  33033. * @default true
  33034. */
  33035. this.isMatrix2Uniform = true;
  33036. this.boundary = 8;
  33037. this.itemSize = 4;
  33038. }
  33039. }
  33040. /**
  33041. * Represents a Matrix3 uniform.
  33042. *
  33043. * @private
  33044. * @augments Uniform
  33045. */
  33046. class Matrix3Uniform extends Uniform {
  33047. /**
  33048. * Constructs a new Number uniform.
  33049. *
  33050. * @param {string} name - The uniform's name.
  33051. * @param {Matrix3} value - The uniform's value.
  33052. */
  33053. constructor( name, value = new Matrix3() ) {
  33054. super( name, value );
  33055. /**
  33056. * This flag can be used for type testing.
  33057. *
  33058. * @type {boolean}
  33059. * @readonly
  33060. * @default true
  33061. */
  33062. this.isMatrix3Uniform = true;
  33063. this.boundary = 48;
  33064. this.itemSize = 12;
  33065. }
  33066. }
  33067. /**
  33068. * Represents a Matrix4 uniform.
  33069. *
  33070. * @private
  33071. * @augments Uniform
  33072. */
  33073. class Matrix4Uniform extends Uniform {
  33074. /**
  33075. * Constructs a new Number uniform.
  33076. *
  33077. * @param {string} name - The uniform's name.
  33078. * @param {Matrix4} value - The uniform's value.
  33079. */
  33080. constructor( name, value = new Matrix4() ) {
  33081. super( name, value );
  33082. /**
  33083. * This flag can be used for type testing.
  33084. *
  33085. * @type {boolean}
  33086. * @readonly
  33087. * @default true
  33088. */
  33089. this.isMatrix4Uniform = true;
  33090. this.boundary = 64;
  33091. this.itemSize = 16;
  33092. }
  33093. }
  33094. /**
  33095. * A special form of Number uniform binding type.
  33096. * It's value is managed by a node object.
  33097. *
  33098. * @private
  33099. * @augments NumberUniform
  33100. */
  33101. class NumberNodeUniform extends NumberUniform {
  33102. /**
  33103. * Constructs a new node-based Number uniform.
  33104. *
  33105. * @param {NodeUniform} nodeUniform - The node uniform.
  33106. */
  33107. constructor( nodeUniform ) {
  33108. super( nodeUniform.name, nodeUniform.value );
  33109. /**
  33110. * The node uniform.
  33111. *
  33112. * @type {NodeUniform}
  33113. */
  33114. this.nodeUniform = nodeUniform;
  33115. }
  33116. /**
  33117. * Overwritten to return the value of the node uniform.
  33118. *
  33119. * @return {number} The value.
  33120. */
  33121. getValue() {
  33122. return this.nodeUniform.value;
  33123. }
  33124. /**
  33125. * Returns the node uniform data type.
  33126. *
  33127. * @return {string} The data type.
  33128. */
  33129. getType() {
  33130. return this.nodeUniform.type;
  33131. }
  33132. }
  33133. /**
  33134. * A special form of Vector2 uniform binding type.
  33135. * It's value is managed by a node object.
  33136. *
  33137. * @private
  33138. * @augments Vector2Uniform
  33139. */
  33140. class Vector2NodeUniform extends Vector2Uniform {
  33141. /**
  33142. * Constructs a new node-based Vector2 uniform.
  33143. *
  33144. * @param {NodeUniform} nodeUniform - The node uniform.
  33145. */
  33146. constructor( nodeUniform ) {
  33147. super( nodeUniform.name, nodeUniform.value );
  33148. /**
  33149. * The node uniform.
  33150. *
  33151. * @type {NodeUniform}
  33152. */
  33153. this.nodeUniform = nodeUniform;
  33154. }
  33155. /**
  33156. * Overwritten to return the value of the node uniform.
  33157. *
  33158. * @return {Vector2} The value.
  33159. */
  33160. getValue() {
  33161. return this.nodeUniform.value;
  33162. }
  33163. /**
  33164. * Returns the node uniform data type.
  33165. *
  33166. * @return {string} The data type.
  33167. */
  33168. getType() {
  33169. return this.nodeUniform.type;
  33170. }
  33171. }
  33172. /**
  33173. * A special form of Vector3 uniform binding type.
  33174. * It's value is managed by a node object.
  33175. *
  33176. * @private
  33177. * @augments Vector3Uniform
  33178. */
  33179. class Vector3NodeUniform extends Vector3Uniform {
  33180. /**
  33181. * Constructs a new node-based Vector3 uniform.
  33182. *
  33183. * @param {NodeUniform} nodeUniform - The node uniform.
  33184. */
  33185. constructor( nodeUniform ) {
  33186. super( nodeUniform.name, nodeUniform.value );
  33187. /**
  33188. * The node uniform.
  33189. *
  33190. * @type {NodeUniform}
  33191. */
  33192. this.nodeUniform = nodeUniform;
  33193. }
  33194. /**
  33195. * Overwritten to return the value of the node uniform.
  33196. *
  33197. * @return {Vector3} The value.
  33198. */
  33199. getValue() {
  33200. return this.nodeUniform.value;
  33201. }
  33202. /**
  33203. * Returns the node uniform data type.
  33204. *
  33205. * @return {string} The data type.
  33206. */
  33207. getType() {
  33208. return this.nodeUniform.type;
  33209. }
  33210. }
  33211. /**
  33212. * A special form of Vector4 uniform binding type.
  33213. * It's value is managed by a node object.
  33214. *
  33215. * @private
  33216. * @augments Vector4Uniform
  33217. */
  33218. class Vector4NodeUniform extends Vector4Uniform {
  33219. /**
  33220. * Constructs a new node-based Vector4 uniform.
  33221. *
  33222. * @param {NodeUniform} nodeUniform - The node uniform.
  33223. */
  33224. constructor( nodeUniform ) {
  33225. super( nodeUniform.name, nodeUniform.value );
  33226. /**
  33227. * The node uniform.
  33228. *
  33229. * @type {NodeUniform}
  33230. */
  33231. this.nodeUniform = nodeUniform;
  33232. }
  33233. /**
  33234. * Overwritten to return the value of the node uniform.
  33235. *
  33236. * @return {Vector4} The value.
  33237. */
  33238. getValue() {
  33239. return this.nodeUniform.value;
  33240. }
  33241. /**
  33242. * Returns the node uniform data type.
  33243. *
  33244. * @return {string} The data type.
  33245. */
  33246. getType() {
  33247. return this.nodeUniform.type;
  33248. }
  33249. }
  33250. /**
  33251. * A special form of Color uniform binding type.
  33252. * It's value is managed by a node object.
  33253. *
  33254. * @private
  33255. * @augments ColorUniform
  33256. */
  33257. class ColorNodeUniform extends ColorUniform {
  33258. /**
  33259. * Constructs a new node-based Color uniform.
  33260. *
  33261. * @param {NodeUniform} nodeUniform - The node uniform.
  33262. */
  33263. constructor( nodeUniform ) {
  33264. super( nodeUniform.name, nodeUniform.value );
  33265. /**
  33266. * The node uniform.
  33267. *
  33268. * @type {NodeUniform}
  33269. */
  33270. this.nodeUniform = nodeUniform;
  33271. }
  33272. /**
  33273. * Overwritten to return the value of the node uniform.
  33274. *
  33275. * @return {Color} The value.
  33276. */
  33277. getValue() {
  33278. return this.nodeUniform.value;
  33279. }
  33280. /**
  33281. * Returns the node uniform data type.
  33282. *
  33283. * @return {string} The data type.
  33284. */
  33285. getType() {
  33286. return this.nodeUniform.type;
  33287. }
  33288. }
  33289. /**
  33290. * A special form of Matrix2 uniform binding type.
  33291. * It's value is managed by a node object.
  33292. *
  33293. * @private
  33294. * @augments Matrix2Uniform
  33295. */
  33296. class Matrix2NodeUniform extends Matrix2Uniform {
  33297. /**
  33298. * Constructs a new node-based Matrix2 uniform.
  33299. *
  33300. * @param {NodeUniform} nodeUniform - The node uniform.
  33301. */
  33302. constructor( nodeUniform ) {
  33303. super( nodeUniform.name, nodeUniform.value );
  33304. /**
  33305. * The node uniform.
  33306. *
  33307. * @type {NodeUniform}
  33308. */
  33309. this.nodeUniform = nodeUniform;
  33310. }
  33311. /**
  33312. * Overwritten to return the value of the node uniform.
  33313. *
  33314. * @return {Matrix2} The value.
  33315. */
  33316. getValue() {
  33317. return this.nodeUniform.value;
  33318. }
  33319. /**
  33320. * Returns the node uniform data type.
  33321. *
  33322. * @return {string} The data type.
  33323. */
  33324. getType() {
  33325. return this.nodeUniform.type;
  33326. }
  33327. }
  33328. /**
  33329. * A special form of Matrix3 uniform binding type.
  33330. * It's value is managed by a node object.
  33331. *
  33332. * @private
  33333. * @augments Matrix3Uniform
  33334. */
  33335. class Matrix3NodeUniform extends Matrix3Uniform {
  33336. /**
  33337. * Constructs a new node-based Matrix3 uniform.
  33338. *
  33339. * @param {NodeUniform} nodeUniform - The node uniform.
  33340. */
  33341. constructor( nodeUniform ) {
  33342. super( nodeUniform.name, nodeUniform.value );
  33343. /**
  33344. * The node uniform.
  33345. *
  33346. * @type {NodeUniform}
  33347. */
  33348. this.nodeUniform = nodeUniform;
  33349. }
  33350. /**
  33351. * Overwritten to return the value of the node uniform.
  33352. *
  33353. * @return {Matrix3} The value.
  33354. */
  33355. getValue() {
  33356. return this.nodeUniform.value;
  33357. }
  33358. /**
  33359. * Returns the node uniform data type.
  33360. *
  33361. * @return {string} The data type.
  33362. */
  33363. getType() {
  33364. return this.nodeUniform.type;
  33365. }
  33366. }
  33367. /**
  33368. * A special form of Matrix4 uniform binding type.
  33369. * It's value is managed by a node object.
  33370. *
  33371. * @private
  33372. * @augments Matrix4Uniform
  33373. */
  33374. class Matrix4NodeUniform extends Matrix4Uniform {
  33375. /**
  33376. * Constructs a new node-based Matrix4 uniform.
  33377. *
  33378. * @param {NodeUniform} nodeUniform - The node uniform.
  33379. */
  33380. constructor( nodeUniform ) {
  33381. super( nodeUniform.name, nodeUniform.value );
  33382. /**
  33383. * The node uniform.
  33384. *
  33385. * @type {NodeUniform}
  33386. */
  33387. this.nodeUniform = nodeUniform;
  33388. }
  33389. /**
  33390. * Overwritten to return the value of the node uniform.
  33391. *
  33392. * @return {Matrix4} The value.
  33393. */
  33394. getValue() {
  33395. return this.nodeUniform.value;
  33396. }
  33397. /**
  33398. * Returns the node uniform data type.
  33399. *
  33400. * @return {string} The data type.
  33401. */
  33402. getType() {
  33403. return this.nodeUniform.type;
  33404. }
  33405. }
  33406. const rendererCache = new WeakMap();
  33407. const typeFromArray = new Map( [
  33408. [ Int8Array, 'int' ],
  33409. [ Int16Array, 'int' ],
  33410. [ Int32Array, 'int' ],
  33411. [ Uint8Array, 'uint' ],
  33412. [ Uint16Array, 'uint' ],
  33413. [ Uint32Array, 'uint' ],
  33414. [ Float32Array, 'float' ]
  33415. ] );
  33416. const toFloat = ( value ) => {
  33417. if ( /e/g.test( value ) ) {
  33418. return String( value ).replace( /\+/g, '' );
  33419. } else {
  33420. value = Number( value );
  33421. return value + ( value % 1 ? '' : '.0' );
  33422. }
  33423. };
  33424. /**
  33425. * Base class for builders which generate a shader program based
  33426. * on a 3D object and its node material definition.
  33427. */
  33428. class NodeBuilder {
  33429. /**
  33430. * Constructs a new node builder.
  33431. *
  33432. * @param {Object3D} object - The 3D object.
  33433. * @param {Renderer} renderer - The current renderer.
  33434. * @param {NodeParser} parser - A reference to a node parser.
  33435. */
  33436. constructor( object, renderer, parser ) {
  33437. /**
  33438. * The 3D object.
  33439. *
  33440. * @type {Object3D}
  33441. */
  33442. this.object = object;
  33443. /**
  33444. * The material of the 3D object.
  33445. *
  33446. * @type {?Material}
  33447. */
  33448. this.material = ( object && object.material ) || null;
  33449. /**
  33450. * The geometry of the 3D object.
  33451. *
  33452. * @type {?BufferGeometry}
  33453. */
  33454. this.geometry = ( object && object.geometry ) || null;
  33455. /**
  33456. * The current renderer.
  33457. *
  33458. * @type {Renderer}
  33459. */
  33460. this.renderer = renderer;
  33461. /**
  33462. * A reference to a node parser.
  33463. *
  33464. * @type {NodeParser}
  33465. */
  33466. this.parser = parser;
  33467. /**
  33468. * The scene the 3D object belongs to.
  33469. *
  33470. * @type {?Scene}
  33471. * @default null
  33472. */
  33473. this.scene = null;
  33474. /**
  33475. * The camera the 3D object is rendered with.
  33476. *
  33477. * @type {?Camera}
  33478. * @default null
  33479. */
  33480. this.camera = null;
  33481. /**
  33482. * A list of all nodes the builder is processing
  33483. * for this 3D object.
  33484. *
  33485. * @type {Array<Node>}
  33486. */
  33487. this.nodes = [];
  33488. /**
  33489. * A list of all sequential nodes.
  33490. *
  33491. * @type {Array<Node>}
  33492. */
  33493. this.sequentialNodes = [];
  33494. /**
  33495. * A list of all nodes which {@link Node#update} method should be executed.
  33496. *
  33497. * @type {Array<Node>}
  33498. */
  33499. this.updateNodes = [];
  33500. /**
  33501. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  33502. *
  33503. * @type {Array<Node>}
  33504. */
  33505. this.updateBeforeNodes = [];
  33506. /**
  33507. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  33508. *
  33509. * @type {Array<Node>}
  33510. */
  33511. this.updateAfterNodes = [];
  33512. /**
  33513. * A dictionary that assigns each node to a unique hash.
  33514. *
  33515. * @type {Object<number,Node>}
  33516. */
  33517. this.hashNodes = {};
  33518. /**
  33519. * A reference to a node material observer.
  33520. *
  33521. * @type {?NodeMaterialObserver}
  33522. * @default null
  33523. */
  33524. this.observer = null;
  33525. /**
  33526. * A reference to the current lights node.
  33527. *
  33528. * @type {?LightsNode}
  33529. * @default null
  33530. */
  33531. this.lightsNode = null;
  33532. /**
  33533. * A reference to the current environment node.
  33534. *
  33535. * @type {?Node}
  33536. * @default null
  33537. */
  33538. this.environmentNode = null;
  33539. /**
  33540. * A reference to the current fog node.
  33541. *
  33542. * @type {?Node}
  33543. * @default null
  33544. */
  33545. this.fogNode = null;
  33546. /**
  33547. * The current clipping context.
  33548. *
  33549. * @type {?ClippingContext}
  33550. */
  33551. this.clippingContext = null;
  33552. /**
  33553. * The generated vertex shader.
  33554. *
  33555. * @type {?string}
  33556. */
  33557. this.vertexShader = null;
  33558. /**
  33559. * The generated fragment shader.
  33560. *
  33561. * @type {?string}
  33562. */
  33563. this.fragmentShader = null;
  33564. /**
  33565. * The generated compute shader.
  33566. *
  33567. * @type {?string}
  33568. */
  33569. this.computeShader = null;
  33570. /**
  33571. * Nodes used in the primary flow of code generation.
  33572. *
  33573. * @type {Object<string,Array<Node>>}
  33574. */
  33575. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  33576. /**
  33577. * Nodes code from `.flowNodes`.
  33578. *
  33579. * @type {Object<string,string>}
  33580. */
  33581. this.flowCode = { vertex: '', fragment: '', compute: '' };
  33582. /**
  33583. * This dictionary holds the node uniforms of the builder.
  33584. * The uniforms are maintained in an array for each shader stage.
  33585. *
  33586. * @type {Object}
  33587. */
  33588. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  33589. /**
  33590. * This dictionary holds the output structs of the builder.
  33591. * The structs are maintained in an array for each shader stage.
  33592. *
  33593. * @type {Object}
  33594. */
  33595. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  33596. /**
  33597. * This dictionary holds the types of the builder.
  33598. *
  33599. * @type {Object}
  33600. */
  33601. this.types = { vertex: [], fragment: [], compute: [], index: 0 };
  33602. /**
  33603. * This dictionary holds the bindings for each shader stage.
  33604. *
  33605. * @type {Object}
  33606. */
  33607. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  33608. /**
  33609. * This dictionary maintains the binding indices per bind group.
  33610. *
  33611. * @type {Object}
  33612. */
  33613. this.bindingsIndexes = {};
  33614. /**
  33615. * Reference to the array of bind groups.
  33616. *
  33617. * @type {?Array<BindGroup>}
  33618. */
  33619. this.bindGroups = null;
  33620. /**
  33621. * This array holds the node attributes of this builder
  33622. * created via {@link AttributeNode}.
  33623. *
  33624. * @type {Array<NodeAttribute>}
  33625. */
  33626. this.attributes = [];
  33627. /**
  33628. * This array holds the node attributes of this builder
  33629. * created via {@link BufferAttributeNode}.
  33630. *
  33631. * @type {Array<NodeAttribute>}
  33632. */
  33633. this.bufferAttributes = [];
  33634. /**
  33635. * This array holds the node varyings of this builder.
  33636. *
  33637. * @type {Array<NodeVarying>}
  33638. */
  33639. this.varyings = [];
  33640. /**
  33641. * This dictionary holds the (native) node codes of this builder.
  33642. * The codes are maintained in an array for each shader stage.
  33643. *
  33644. * @type {Object<string,Array<NodeCode>>}
  33645. */
  33646. this.codes = {};
  33647. /**
  33648. * This dictionary holds the node variables of this builder.
  33649. * The variables are maintained in an array for each shader stage.
  33650. * This dictionary is also used to count the number of variables
  33651. * according to their type (const, vars).
  33652. *
  33653. * @type {Object<string,Array<NodeVar>|number>}
  33654. */
  33655. this.vars = {};
  33656. /**
  33657. * This dictionary holds the declarations for each shader stage.
  33658. *
  33659. * @type {Object}
  33660. */
  33661. this.declarations = {};
  33662. /**
  33663. * Current code flow.
  33664. * All code generated in this stack will be stored in `.flow`.
  33665. *
  33666. * @type {{code: string}}
  33667. */
  33668. this.flow = { code: '' };
  33669. /**
  33670. * A chain of nodes.
  33671. * Used to check recursive calls in node-graph.
  33672. *
  33673. * @type {Array<Node>}
  33674. */
  33675. this.chaining = [];
  33676. /**
  33677. * The current stack.
  33678. * This reflects the current process in the code block hierarchy,
  33679. * it is useful to know if the current process is inside a conditional for example.
  33680. *
  33681. * @type {StackNode}
  33682. */
  33683. this.stack = stack();
  33684. /**
  33685. * List of stack nodes.
  33686. * The current stack hierarchy is stored in an array.
  33687. *
  33688. * @type {Array<StackNode>}
  33689. */
  33690. this.stacks = [];
  33691. /**
  33692. * A tab value. Used for shader string generation.
  33693. *
  33694. * @type {string}
  33695. * @default '\t'
  33696. */
  33697. this.tab = '\t';
  33698. /**
  33699. * Reference to the current function node.
  33700. *
  33701. * @type {?FunctionNode}
  33702. * @default null
  33703. */
  33704. this.currentFunctionNode = null;
  33705. /**
  33706. * The builder's context.
  33707. *
  33708. * @type {Object}
  33709. */
  33710. this.context = {
  33711. material: this.material
  33712. };
  33713. /**
  33714. * The builder's cache.
  33715. *
  33716. * @type {NodeCache}
  33717. */
  33718. this.cache = new NodeCache();
  33719. /**
  33720. * Since the {@link NodeBuilder#cache} might be temporarily
  33721. * overwritten by other caches, this member retains the reference
  33722. * to the builder's own cache.
  33723. *
  33724. * @type {NodeCache}
  33725. * @default this.cache
  33726. */
  33727. this.globalCache = this.cache;
  33728. this.flowsData = new WeakMap();
  33729. /**
  33730. * The current shader stage.
  33731. *
  33732. * @type {?('vertex'|'fragment'|'compute'|'any')}
  33733. */
  33734. this.shaderStage = null;
  33735. /**
  33736. * The current build stage.
  33737. *
  33738. * @type {?('setup'|'analyze'|'generate')}
  33739. */
  33740. this.buildStage = null;
  33741. /**
  33742. * The sub-build layers.
  33743. *
  33744. * @type {Array<SubBuildNode>}
  33745. * @default []
  33746. */
  33747. this.subBuildLayers = [];
  33748. /**
  33749. * The current stack of nodes.
  33750. *
  33751. * @type {?StackNode}
  33752. * @default null
  33753. */
  33754. this.currentStack = null;
  33755. /**
  33756. * The current sub-build TSL function(Fn).
  33757. *
  33758. * @type {?string}
  33759. * @default null
  33760. */
  33761. this.subBuildFn = null;
  33762. }
  33763. /**
  33764. * Returns the bind groups of the current renderer.
  33765. *
  33766. * @return {ChainMap} The cache.
  33767. */
  33768. getBindGroupsCache() {
  33769. let bindGroupsCache = rendererCache.get( this.renderer );
  33770. if ( bindGroupsCache === undefined ) {
  33771. bindGroupsCache = new ChainMap();
  33772. rendererCache.set( this.renderer, bindGroupsCache );
  33773. }
  33774. return bindGroupsCache;
  33775. }
  33776. /**
  33777. * Factory method for creating an instance of {@link RenderTarget} with the given
  33778. * dimensions and options.
  33779. *
  33780. * @param {number} width - The width of the render target.
  33781. * @param {number} height - The height of the render target.
  33782. * @param {Object} options - The options of the render target.
  33783. * @return {RenderTarget} The render target.
  33784. */
  33785. createRenderTarget( width, height, options ) {
  33786. return new RenderTarget( width, height, options );
  33787. }
  33788. /**
  33789. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  33790. * dimensions and options.
  33791. *
  33792. * @param {number} size - The size of the cube render target.
  33793. * @param {Object} options - The options of the cube render target.
  33794. * @return {CubeRenderTarget} The cube render target.
  33795. */
  33796. createCubeRenderTarget( size, options ) {
  33797. return new CubeRenderTarget( size, options );
  33798. }
  33799. /**
  33800. * Whether the given node is included in the internal array of nodes or not.
  33801. *
  33802. * @param {Node} node - The node to test.
  33803. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  33804. */
  33805. includes( node ) {
  33806. return this.nodes.includes( node );
  33807. }
  33808. /**
  33809. * Returns the output struct name which is required by
  33810. * {@link OutputStructNode}.
  33811. *
  33812. * @abstract
  33813. * @return {string} The name of the output struct.
  33814. */
  33815. getOutputStructName() {}
  33816. /**
  33817. * Returns a bind group for the given group name and binding.
  33818. *
  33819. * @private
  33820. * @param {string} groupName - The group name.
  33821. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  33822. * @return {BindGroup} The bind group
  33823. */
  33824. _getBindGroup( groupName, bindings ) {
  33825. const bindGroupsCache = this.getBindGroupsCache();
  33826. //
  33827. const bindingsArray = [];
  33828. let sharedGroup = true;
  33829. for ( const binding of bindings ) {
  33830. bindingsArray.push( binding );
  33831. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  33832. }
  33833. //
  33834. let bindGroup;
  33835. if ( sharedGroup ) {
  33836. bindGroup = bindGroupsCache.get( bindingsArray );
  33837. if ( bindGroup === undefined ) {
  33838. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  33839. bindGroupsCache.set( bindingsArray, bindGroup );
  33840. }
  33841. } else {
  33842. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  33843. }
  33844. return bindGroup;
  33845. }
  33846. /**
  33847. * Returns an array of node uniform groups for the given group name and shader stage.
  33848. *
  33849. * @param {string} groupName - The group name.
  33850. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33851. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  33852. */
  33853. getBindGroupArray( groupName, shaderStage ) {
  33854. const bindings = this.bindings[ shaderStage ];
  33855. let bindGroup = bindings[ groupName ];
  33856. if ( bindGroup === undefined ) {
  33857. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  33858. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  33859. }
  33860. bindings[ groupName ] = bindGroup = [];
  33861. }
  33862. return bindGroup;
  33863. }
  33864. /**
  33865. * Returns a list bindings of all shader stages separated by groups.
  33866. *
  33867. * @return {Array<BindGroup>} The list of bindings.
  33868. */
  33869. getBindings() {
  33870. let bindingsGroups = this.bindGroups;
  33871. if ( bindingsGroups === null ) {
  33872. const groups = {};
  33873. const bindings = this.bindings;
  33874. for ( const shaderStage of shaderStages ) {
  33875. for ( const groupName in bindings[ shaderStage ] ) {
  33876. const uniforms = bindings[ shaderStage ][ groupName ];
  33877. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  33878. groupUniforms.push( ...uniforms );
  33879. }
  33880. }
  33881. bindingsGroups = [];
  33882. for ( const groupName in groups ) {
  33883. const group = groups[ groupName ];
  33884. const bindingsGroup = this._getBindGroup( groupName, group );
  33885. bindingsGroups.push( bindingsGroup );
  33886. }
  33887. this.bindGroups = bindingsGroups;
  33888. }
  33889. return bindingsGroups;
  33890. }
  33891. /**
  33892. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  33893. */
  33894. sortBindingGroups() {
  33895. const bindingsGroups = this.getBindings();
  33896. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  33897. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  33898. const bindingGroup = bindingsGroups[ i ];
  33899. this.bindingsIndexes[ bindingGroup.name ].group = i;
  33900. bindingGroup.index = i;
  33901. }
  33902. }
  33903. /**
  33904. * The builder maintains each node in a hash-based dictionary.
  33905. * This method sets the given node (value) with the given hash (key) into this dictionary.
  33906. *
  33907. * @param {Node} node - The node to add.
  33908. * @param {number} hash - The hash of the node.
  33909. */
  33910. setHashNode( node, hash ) {
  33911. this.hashNodes[ hash ] = node;
  33912. }
  33913. /**
  33914. * Adds a node to this builder.
  33915. *
  33916. * @param {Node} node - The node to add.
  33917. */
  33918. addNode( node ) {
  33919. if ( this.nodes.includes( node ) === false ) {
  33920. this.nodes.push( node );
  33921. this.setHashNode( node, node.getHash( this ) );
  33922. }
  33923. }
  33924. /**
  33925. * It is used to add Nodes that will be used as FRAME and RENDER events,
  33926. * and need to follow a certain sequence in the calls to work correctly.
  33927. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  33928. *
  33929. * @param {Node} node - The node to add.
  33930. */
  33931. addSequentialNode( node ) {
  33932. if ( this.sequentialNodes.includes( node ) === false ) {
  33933. this.sequentialNodes.push( node );
  33934. }
  33935. }
  33936. /**
  33937. * Checks the update types of nodes
  33938. */
  33939. buildUpdateNodes() {
  33940. for ( const node of this.nodes ) {
  33941. const updateType = node.getUpdateType();
  33942. if ( updateType !== NodeUpdateType.NONE ) {
  33943. this.updateNodes.push( node );
  33944. }
  33945. }
  33946. for ( const node of this.sequentialNodes ) {
  33947. const updateBeforeType = node.getUpdateBeforeType();
  33948. const updateAfterType = node.getUpdateAfterType();
  33949. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  33950. this.updateBeforeNodes.push( node );
  33951. }
  33952. if ( updateAfterType !== NodeUpdateType.NONE ) {
  33953. this.updateAfterNodes.push( node );
  33954. }
  33955. }
  33956. }
  33957. /**
  33958. * A reference the current node which is the
  33959. * last node in the chain of nodes.
  33960. *
  33961. * @type {Node}
  33962. */
  33963. get currentNode() {
  33964. return this.chaining[ this.chaining.length - 1 ];
  33965. }
  33966. /**
  33967. * Whether the given texture is filtered or not.
  33968. *
  33969. * @param {Texture} texture - The texture to check.
  33970. * @return {boolean} Whether the given texture is filtered or not.
  33971. */
  33972. isFilteredTexture( texture ) {
  33973. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  33974. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  33975. }
  33976. /**
  33977. * Adds the given node to the internal node chain.
  33978. * This is used to check recursive calls in node-graph.
  33979. *
  33980. * @param {Node} node - The node to add.
  33981. */
  33982. addChain( node ) {
  33983. /*
  33984. if ( this.chaining.indexOf( node ) !== - 1 ) {
  33985. console.warn( 'Recursive node: ', node );
  33986. }
  33987. */
  33988. this.chaining.push( node );
  33989. }
  33990. /**
  33991. * Removes the given node from the internal node chain.
  33992. *
  33993. * @param {Node} node - The node to remove.
  33994. */
  33995. removeChain( node ) {
  33996. const lastChain = this.chaining.pop();
  33997. if ( lastChain !== node ) {
  33998. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  33999. }
  34000. }
  34001. /**
  34002. * Returns the native shader method name for a given generic name. E.g.
  34003. * the method name `textureDimensions` matches the WGSL name but must be
  34004. * resolved to `textureSize` in GLSL.
  34005. *
  34006. * @abstract
  34007. * @param {string} method - The method name to resolve.
  34008. * @return {string} The resolved method name.
  34009. */
  34010. getMethod( method ) {
  34011. return method;
  34012. }
  34013. /**
  34014. * Returns the native snippet for a ternary operation. E.g. GLSL would output
  34015. * a ternary op as `cond ? x : y` whereas WGSL would output it as `select(y, x, cond)`
  34016. *
  34017. * @abstract
  34018. * @param {string} condSnippet - The condition determining which expression gets resolved.
  34019. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  34020. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  34021. * @return {string} The resolved method name.
  34022. */
  34023. getTernary( /* condSnippet, ifSnippet, elseSnippet*/ ) {
  34024. return null;
  34025. }
  34026. /**
  34027. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  34028. *
  34029. * @param {number} hash - The hash of the node.
  34030. * @return {Node} The found node.
  34031. */
  34032. getNodeFromHash( hash ) {
  34033. return this.hashNodes[ hash ];
  34034. }
  34035. /**
  34036. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  34037. *
  34038. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  34039. * @param {Node} node - The node to add.
  34040. * @return {Node} The node.
  34041. */
  34042. addFlow( shaderStage, node ) {
  34043. this.flowNodes[ shaderStage ].push( node );
  34044. return node;
  34045. }
  34046. /**
  34047. * Sets builder's context.
  34048. *
  34049. * @param {Object} context - The context to set.
  34050. */
  34051. setContext( context ) {
  34052. this.context = context;
  34053. }
  34054. /**
  34055. * Returns the builder's current context.
  34056. *
  34057. * @return {Object} The builder's current context.
  34058. */
  34059. getContext() {
  34060. return this.context;
  34061. }
  34062. /**
  34063. * Gets a context used in shader construction that can be shared across different materials.
  34064. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  34065. *
  34066. * @return {Object} The builder's current context without material.
  34067. */
  34068. getSharedContext() {
  34069. ({ ...this.context });
  34070. return this.context;
  34071. }
  34072. /**
  34073. * Sets builder's cache.
  34074. *
  34075. * @param {NodeCache} cache - The cache to set.
  34076. */
  34077. setCache( cache ) {
  34078. this.cache = cache;
  34079. }
  34080. /**
  34081. * Returns the builder's current cache.
  34082. *
  34083. * @return {NodeCache} The builder's current cache.
  34084. */
  34085. getCache() {
  34086. return this.cache;
  34087. }
  34088. /**
  34089. * Returns a cache for the given node.
  34090. *
  34091. * @param {Node} node - The node.
  34092. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  34093. * @return {NodeCache} The cache.
  34094. */
  34095. getCacheFromNode( node, parent = true ) {
  34096. const data = this.getDataFromNode( node );
  34097. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  34098. return data.cache;
  34099. }
  34100. /**
  34101. * Whether the requested feature is available or not.
  34102. *
  34103. * @abstract
  34104. * @param {string} name - The requested feature.
  34105. * @return {boolean} Whether the requested feature is supported or not.
  34106. */
  34107. isAvailable( /*name*/ ) {
  34108. return false;
  34109. }
  34110. /**
  34111. * Returns the vertexIndex input variable as a native shader string.
  34112. *
  34113. * @abstract
  34114. * @return {string} The instanceIndex shader string.
  34115. */
  34116. getVertexIndex() {
  34117. console.warn( 'Abstract function.' );
  34118. }
  34119. /**
  34120. * Returns the instanceIndex input variable as a native shader string.
  34121. *
  34122. * @abstract
  34123. * @return {string} The instanceIndex shader string.
  34124. */
  34125. getInstanceIndex() {
  34126. console.warn( 'Abstract function.' );
  34127. }
  34128. /**
  34129. * Returns the drawIndex input variable as a native shader string.
  34130. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  34131. *
  34132. * @abstract
  34133. * @return {?string} The drawIndex shader string.
  34134. */
  34135. getDrawIndex() {
  34136. console.warn( 'Abstract function.' );
  34137. }
  34138. /**
  34139. * Returns the frontFacing input variable as a native shader string.
  34140. *
  34141. * @abstract
  34142. * @return {string} The frontFacing shader string.
  34143. */
  34144. getFrontFacing() {
  34145. console.warn( 'Abstract function.' );
  34146. }
  34147. /**
  34148. * Returns the fragCoord input variable as a native shader string.
  34149. *
  34150. * @abstract
  34151. * @return {string} The fragCoord shader string.
  34152. */
  34153. getFragCoord() {
  34154. console.warn( 'Abstract function.' );
  34155. }
  34156. /**
  34157. * Whether to flip texture data along its vertical axis or not. WebGL needs
  34158. * this method evaluate to `true`, WebGPU to `false`.
  34159. *
  34160. * @abstract
  34161. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  34162. */
  34163. isFlipY() {
  34164. return false;
  34165. }
  34166. /**
  34167. * Calling this method increases the usage count for the given node by one.
  34168. *
  34169. * @param {Node} node - The node to increase the usage count for.
  34170. * @return {number} The updated usage count.
  34171. */
  34172. increaseUsage( node ) {
  34173. const nodeData = this.getDataFromNode( node );
  34174. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  34175. return nodeData.usageCount;
  34176. }
  34177. /**
  34178. * Generates a texture sample shader string for the given texture data.
  34179. *
  34180. * @abstract
  34181. * @param {Texture} texture - The texture.
  34182. * @param {string} textureProperty - The texture property name.
  34183. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  34184. * @return {string} The generated shader string.
  34185. */
  34186. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  34187. console.warn( 'Abstract function.' );
  34188. }
  34189. /**
  34190. * Generates a texture LOD shader string for the given texture data.
  34191. *
  34192. * @abstract
  34193. * @param {Texture} texture - The texture.
  34194. * @param {string} textureProperty - The texture property name.
  34195. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  34196. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  34197. * @param {string} levelSnippet - Snippet defining the mip level.
  34198. * @return {string} The generated shader string.
  34199. */
  34200. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  34201. console.warn( 'Abstract function.' );
  34202. }
  34203. /**
  34204. * Generates the array declaration string.
  34205. *
  34206. * @param {string} type - The type.
  34207. * @param {?number} [count] - The count.
  34208. * @return {string} The generated value as a shader string.
  34209. */
  34210. generateArrayDeclaration( type, count ) {
  34211. return this.getType( type ) + '[ ' + count + ' ]';
  34212. }
  34213. /**
  34214. * Generates the array shader string for the given type and value.
  34215. *
  34216. * @param {string} type - The type.
  34217. * @param {?number} [count] - The count.
  34218. * @param {?Array<Node>} [values=null] - The default values.
  34219. * @return {string} The generated value as a shader string.
  34220. */
  34221. generateArray( type, count, values = null ) {
  34222. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  34223. for ( let i = 0; i < count; i ++ ) {
  34224. const value = values ? values[ i ] : null;
  34225. if ( value !== null ) {
  34226. snippet += value.build( this, type );
  34227. } else {
  34228. snippet += this.generateConst( type );
  34229. }
  34230. if ( i < count - 1 ) snippet += ', ';
  34231. }
  34232. snippet += ' )';
  34233. return snippet;
  34234. }
  34235. /**
  34236. * Generates the struct shader string.
  34237. *
  34238. * @param {string} type - The type.
  34239. * @param {Array<Object>} [membersLayout] - The count.
  34240. * @param {?Array<Node>} [values=null] - The default values.
  34241. * @return {string} The generated value as a shader string.
  34242. */
  34243. generateStruct( type, membersLayout, values = null ) {
  34244. const snippets = [];
  34245. for ( const member of membersLayout ) {
  34246. const { name, type } = member;
  34247. if ( values && values[ name ] && values[ name ].isNode ) {
  34248. snippets.push( values[ name ].build( this, type ) );
  34249. } else {
  34250. snippets.push( this.generateConst( type ) );
  34251. }
  34252. }
  34253. return type + '( ' + snippets.join( ', ' ) + ' )';
  34254. }
  34255. /**
  34256. * Generates the shader string for the given type and value.
  34257. *
  34258. * @param {string} type - The type.
  34259. * @param {?any} [value=null] - The value.
  34260. * @return {string} The generated value as a shader string.
  34261. */
  34262. generateConst( type, value = null ) {
  34263. if ( value === null ) {
  34264. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  34265. else if ( type === 'bool' ) value = false;
  34266. else if ( type === 'color' ) value = new Color();
  34267. else if ( type === 'vec2' ) value = new Vector2();
  34268. else if ( type === 'vec3' ) value = new Vector3();
  34269. else if ( type === 'vec4' ) value = new Vector4();
  34270. }
  34271. if ( type === 'float' ) return toFloat( value );
  34272. if ( type === 'int' ) return `${ Math.round( value ) }`;
  34273. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  34274. if ( type === 'bool' ) return value ? 'true' : 'false';
  34275. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  34276. const typeLength = this.getTypeLength( type );
  34277. const componentType = this.getComponentType( type );
  34278. const generateConst = value => this.generateConst( componentType, value );
  34279. if ( typeLength === 2 ) {
  34280. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  34281. } else if ( typeLength === 3 ) {
  34282. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  34283. } else if ( typeLength === 4 && type !== 'mat2' ) {
  34284. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  34285. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  34286. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  34287. } else if ( typeLength > 4 ) {
  34288. return `${ this.getType( type ) }()`;
  34289. }
  34290. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  34291. }
  34292. /**
  34293. * It might be necessary to convert certain data types to different ones
  34294. * so this method can be used to hide the conversion.
  34295. *
  34296. * @param {string} type - The type.
  34297. * @return {string} The updated type.
  34298. */
  34299. getType( type ) {
  34300. if ( type === 'color' ) return 'vec3';
  34301. return type;
  34302. }
  34303. /**
  34304. * Whether the given attribute name is defined in the geometry or not.
  34305. *
  34306. * @param {string} name - The attribute name.
  34307. * @return {boolean} Whether the given attribute name is defined in the geometry.
  34308. */
  34309. hasGeometryAttribute( name ) {
  34310. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  34311. }
  34312. /**
  34313. * Returns a node attribute for the given name and type.
  34314. *
  34315. * @param {string} name - The attribute's name.
  34316. * @param {string} type - The attribute's type.
  34317. * @return {NodeAttribute} The node attribute.
  34318. */
  34319. getAttribute( name, type ) {
  34320. const attributes = this.attributes;
  34321. // find attribute
  34322. for ( const attribute of attributes ) {
  34323. if ( attribute.name === name ) {
  34324. return attribute;
  34325. }
  34326. }
  34327. // create a new if no exist
  34328. const attribute = new NodeAttribute( name, type );
  34329. this.registerDeclaration( attribute );
  34330. attributes.push( attribute );
  34331. return attribute;
  34332. }
  34333. /**
  34334. * Returns for the given node and shader stage the property name for the shader.
  34335. *
  34336. * @param {Node} node - The node.
  34337. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34338. * @return {string} The property name.
  34339. */
  34340. getPropertyName( node/*, shaderStage*/ ) {
  34341. return node.name;
  34342. }
  34343. /**
  34344. * Whether the given type is a vector type or not.
  34345. *
  34346. * @param {string} type - The type to check.
  34347. * @return {boolean} Whether the given type is a vector type or not.
  34348. */
  34349. isVector( type ) {
  34350. return /vec\d/.test( type );
  34351. }
  34352. /**
  34353. * Whether the given type is a matrix type or not.
  34354. *
  34355. * @param {string} type - The type to check.
  34356. * @return {boolean} Whether the given type is a matrix type or not.
  34357. */
  34358. isMatrix( type ) {
  34359. return /mat\d/.test( type );
  34360. }
  34361. /**
  34362. * Whether the given type is a reference type or not.
  34363. *
  34364. * @param {string} type - The type to check.
  34365. * @return {boolean} Whether the given type is a reference type or not.
  34366. */
  34367. isReference( type ) {
  34368. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  34369. }
  34370. /**
  34371. * Checks if the given texture requires a manual conversion to the working color space.
  34372. *
  34373. * @abstract
  34374. * @param {Texture} texture - The texture to check.
  34375. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  34376. */
  34377. needsToWorkingColorSpace( /*texture*/ ) {
  34378. return false;
  34379. }
  34380. /**
  34381. * Returns the component type of a given texture.
  34382. *
  34383. * @param {Texture} texture - The texture.
  34384. * @return {string} The component type.
  34385. */
  34386. getComponentTypeFromTexture( texture ) {
  34387. const type = texture.type;
  34388. if ( texture.isDataTexture ) {
  34389. if ( type === IntType ) return 'int';
  34390. if ( type === UnsignedIntType ) return 'uint';
  34391. }
  34392. return 'float';
  34393. }
  34394. /**
  34395. * Returns the element type for a given type.
  34396. *
  34397. * @param {string} type - The type.
  34398. * @return {string} The element type.
  34399. */
  34400. getElementType( type ) {
  34401. if ( type === 'mat2' ) return 'vec2';
  34402. if ( type === 'mat3' ) return 'vec3';
  34403. if ( type === 'mat4' ) return 'vec4';
  34404. return this.getComponentType( type );
  34405. }
  34406. /**
  34407. * Returns the component type for a given type.
  34408. *
  34409. * @param {string} type - The type.
  34410. * @return {string} The component type.
  34411. */
  34412. getComponentType( type ) {
  34413. type = this.getVectorType( type );
  34414. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  34415. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  34416. if ( componentType === null ) return null;
  34417. if ( componentType[ 1 ] === 'b' ) return 'bool';
  34418. if ( componentType[ 1 ] === 'i' ) return 'int';
  34419. if ( componentType[ 1 ] === 'u' ) return 'uint';
  34420. return 'float';
  34421. }
  34422. /**
  34423. * Returns the vector type for a given type.
  34424. *
  34425. * @param {string} type - The type.
  34426. * @return {string} The vector type.
  34427. */
  34428. getVectorType( type ) {
  34429. if ( type === 'color' ) return 'vec3';
  34430. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  34431. return type;
  34432. }
  34433. /**
  34434. * Returns the data type for the given the length and component type.
  34435. *
  34436. * @param {number} length - The length.
  34437. * @param {string} [componentType='float'] - The component type.
  34438. * @return {string} The type.
  34439. */
  34440. getTypeFromLength( length, componentType = 'float' ) {
  34441. if ( length === 1 ) return componentType;
  34442. let baseType = getTypeFromLength( length );
  34443. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  34444. // fix edge case for mat2x2 being same size as vec4
  34445. if ( /mat2/.test( componentType ) === true ) {
  34446. baseType = baseType.replace( 'vec', 'mat' );
  34447. }
  34448. return prefix + baseType;
  34449. }
  34450. /**
  34451. * Returns the type for a given typed array.
  34452. *
  34453. * @param {TypedArray} array - The typed array.
  34454. * @return {string} The type.
  34455. */
  34456. getTypeFromArray( array ) {
  34457. return typeFromArray.get( array.constructor );
  34458. }
  34459. /**
  34460. * Returns the type is an integer type.
  34461. *
  34462. * @param {string} type - The type.
  34463. * @return {boolean} Whether the type is an integer type or not.
  34464. */
  34465. isInteger( type ) {
  34466. return /int|uint|(i|u)vec/.test( type );
  34467. }
  34468. /**
  34469. * Returns the type for a given buffer attribute.
  34470. *
  34471. * @param {BufferAttribute} attribute - The buffer attribute.
  34472. * @return {string} The type.
  34473. */
  34474. getTypeFromAttribute( attribute ) {
  34475. let dataAttribute = attribute;
  34476. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  34477. const array = dataAttribute.array;
  34478. const itemSize = attribute.itemSize;
  34479. const normalized = attribute.normalized;
  34480. let arrayType;
  34481. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  34482. arrayType = this.getTypeFromArray( array );
  34483. }
  34484. return this.getTypeFromLength( itemSize, arrayType );
  34485. }
  34486. /**
  34487. * Returns the length for the given data type.
  34488. *
  34489. * @param {string} type - The data type.
  34490. * @return {number} The length.
  34491. */
  34492. getTypeLength( type ) {
  34493. const vecType = this.getVectorType( type );
  34494. const vecNum = /vec([2-4])/.exec( vecType );
  34495. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  34496. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  34497. if ( /mat2/.test( type ) === true ) return 4;
  34498. if ( /mat3/.test( type ) === true ) return 9;
  34499. if ( /mat4/.test( type ) === true ) return 16;
  34500. return 0;
  34501. }
  34502. /**
  34503. * Returns the vector type for a given matrix type.
  34504. *
  34505. * @param {string} type - The matrix type.
  34506. * @return {string} The vector type.
  34507. */
  34508. getVectorFromMatrix( type ) {
  34509. return type.replace( 'mat', 'vec' );
  34510. }
  34511. /**
  34512. * For a given type this method changes the component type to the
  34513. * given value. E.g. `vec4` should be changed to the new component type
  34514. * `uint` which results in `uvec4`.
  34515. *
  34516. * @param {string} type - The type.
  34517. * @param {string} newComponentType - The new component type.
  34518. * @return {string} The new type.
  34519. */
  34520. changeComponentType( type, newComponentType ) {
  34521. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  34522. }
  34523. /**
  34524. * Returns the integer type pendant for the given type.
  34525. *
  34526. * @param {string} type - The type.
  34527. * @return {string} The integer type.
  34528. */
  34529. getIntegerType( type ) {
  34530. const componentType = this.getComponentType( type );
  34531. if ( componentType === 'int' || componentType === 'uint' ) return type;
  34532. return this.changeComponentType( type, 'int' );
  34533. }
  34534. /**
  34535. * Adds a stack node to the internal stack.
  34536. *
  34537. * @return {StackNode} The added stack node.
  34538. */
  34539. addStack() {
  34540. this.stack = stack( this.stack );
  34541. const previousStack = getCurrentStack();
  34542. this.stacks.push( previousStack );
  34543. setCurrentStack( this.stack );
  34544. return this.stack;
  34545. }
  34546. /**
  34547. * Removes the last stack node from the internal stack.
  34548. *
  34549. * @return {StackNode} The removed stack node.
  34550. */
  34551. removeStack() {
  34552. const lastStack = this.stack;
  34553. this.stack = lastStack.parent;
  34554. setCurrentStack( this.stacks.pop() );
  34555. return lastStack;
  34556. }
  34557. /**
  34558. * The builder maintains (cached) data for each node during the building process. This method
  34559. * can be used to get these data for a specific shader stage and cache.
  34560. *
  34561. * @param {Node} node - The node to get the data for.
  34562. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34563. * @param {?NodeCache} cache - An optional cache.
  34564. * @return {Object} The node data.
  34565. */
  34566. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  34567. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  34568. let nodeData = cache.getData( node );
  34569. if ( nodeData === undefined ) {
  34570. nodeData = {};
  34571. cache.setData( node, nodeData );
  34572. }
  34573. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  34574. //
  34575. let data = nodeData[ shaderStage ];
  34576. const subBuilds = nodeData.any ? nodeData.any.subBuilds : null;
  34577. const subBuild = this.getClosestSubBuild( subBuilds );
  34578. if ( subBuild ) {
  34579. if ( data.subBuildsCache === undefined ) data.subBuildsCache = {};
  34580. data = data.subBuildsCache[ subBuild ] || ( data.subBuildsCache[ subBuild ] = {} );
  34581. data.subBuilds = subBuilds;
  34582. }
  34583. return data;
  34584. }
  34585. /**
  34586. * Returns the properties for the given node and shader stage.
  34587. *
  34588. * @param {Node} node - The node to get the properties for.
  34589. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  34590. * @return {Object} The node properties.
  34591. */
  34592. getNodeProperties( node, shaderStage = 'any' ) {
  34593. const nodeData = this.getDataFromNode( node, shaderStage );
  34594. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  34595. }
  34596. /**
  34597. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  34598. *
  34599. * @param {BufferAttributeNode} node - The buffer attribute node.
  34600. * @param {string} type - The node type.
  34601. * @return {NodeAttribute} The node attribute.
  34602. */
  34603. getBufferAttributeFromNode( node, type ) {
  34604. const nodeData = this.getDataFromNode( node );
  34605. let bufferAttribute = nodeData.bufferAttribute;
  34606. if ( bufferAttribute === undefined ) {
  34607. const index = this.uniforms.index ++;
  34608. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  34609. this.bufferAttributes.push( bufferAttribute );
  34610. nodeData.bufferAttribute = bufferAttribute;
  34611. }
  34612. return bufferAttribute;
  34613. }
  34614. /**
  34615. * Returns an instance of {@link StructType} for the given struct name and shader stage
  34616. * or null if not found.
  34617. *
  34618. * @param {string} name - The name of the struct.
  34619. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34620. * @return {?StructType} The struct type or null if not found.
  34621. */
  34622. getStructTypeNode( name, shaderStage = this.shaderStage ) {
  34623. return this.types[ shaderStage ][ name ] || null;
  34624. }
  34625. /**
  34626. * Returns an instance of {@link StructType} for the given output struct node.
  34627. *
  34628. * @param {OutputStructNode} node - The output struct node.
  34629. * @param {Array<Object>} membersLayout - The output struct types.
  34630. * @param {?string} [name=null] - The name of the struct.
  34631. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34632. * @return {StructType} The struct type attribute.
  34633. */
  34634. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  34635. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  34636. let structType = nodeData.structType;
  34637. if ( structType === undefined ) {
  34638. const index = this.structs.index ++;
  34639. if ( name === null ) name = 'StructType' + index;
  34640. structType = new StructType( name, membersLayout );
  34641. this.structs[ shaderStage ].push( structType );
  34642. this.types[ shaderStage ][ name ] = node;
  34643. nodeData.structType = structType;
  34644. }
  34645. return structType;
  34646. }
  34647. /**
  34648. * Returns an instance of {@link StructType} for the given output struct node.
  34649. *
  34650. * @param {OutputStructNode} node - The output struct node.
  34651. * @param {Array<Object>} membersLayout - The output struct types.
  34652. * @return {StructType} The struct type attribute.
  34653. */
  34654. getOutputStructTypeFromNode( node, membersLayout ) {
  34655. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  34656. structType.output = true;
  34657. return structType;
  34658. }
  34659. /**
  34660. * Returns an instance of {@link NodeUniform} for the given uniform node.
  34661. *
  34662. * @param {UniformNode} node - The uniform node.
  34663. * @param {string} type - The uniform type.
  34664. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34665. * @param {?string} name - The name of the uniform.
  34666. * @return {NodeUniform} The node uniform.
  34667. */
  34668. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  34669. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  34670. let nodeUniform = nodeData.uniform;
  34671. if ( nodeUniform === undefined ) {
  34672. const index = this.uniforms.index ++;
  34673. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  34674. this.uniforms[ shaderStage ].push( nodeUniform );
  34675. this.registerDeclaration( nodeUniform );
  34676. nodeData.uniform = nodeUniform;
  34677. }
  34678. return nodeUniform;
  34679. }
  34680. /**
  34681. * Returns an instance of {@link NodeVar} for the given variable node.
  34682. *
  34683. * @param {VarNode} node - The variable node.
  34684. * @param {?string} name - The variable's name.
  34685. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  34686. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34687. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  34688. *
  34689. * @return {NodeVar} The node variable.
  34690. */
  34691. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  34692. const nodeData = this.getDataFromNode( node, shaderStage );
  34693. const subBuildVariable = this.getSubBuildProperty( 'variable', nodeData.subBuilds );
  34694. let nodeVar = nodeData[ subBuildVariable ];
  34695. if ( nodeVar === undefined ) {
  34696. const idNS = readOnly ? '_const' : '_var';
  34697. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  34698. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  34699. if ( name === null ) {
  34700. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  34701. this.vars[ idNS ] ++;
  34702. }
  34703. //
  34704. if ( subBuildVariable !== 'variable' ) {
  34705. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  34706. }
  34707. //
  34708. const count = node.getArrayCount( this );
  34709. nodeVar = new NodeVar( name, type, readOnly, count );
  34710. if ( ! readOnly ) {
  34711. vars.push( nodeVar );
  34712. }
  34713. this.registerDeclaration( nodeVar );
  34714. nodeData[ subBuildVariable ] = nodeVar;
  34715. }
  34716. return nodeVar;
  34717. }
  34718. /**
  34719. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  34720. *
  34721. * @param {Node} node - The varying node.
  34722. * @return {boolean} Returns true if deterministic.
  34723. */
  34724. isDeterministic( node ) {
  34725. if ( node.isMathNode ) {
  34726. return this.isDeterministic( node.aNode ) &&
  34727. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  34728. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  34729. } else if ( node.isOperatorNode ) {
  34730. return this.isDeterministic( node.aNode ) &&
  34731. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  34732. } else if ( node.isArrayNode ) {
  34733. if ( node.values !== null ) {
  34734. for ( const n of node.values ) {
  34735. if ( ! this.isDeterministic( n ) ) {
  34736. return false;
  34737. }
  34738. }
  34739. }
  34740. return true;
  34741. } else if ( node.isConstNode ) {
  34742. return true;
  34743. }
  34744. return false;
  34745. }
  34746. /**
  34747. * Returns an instance of {@link NodeVarying} for the given varying node.
  34748. *
  34749. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  34750. * @param {?string} name - The varying's name.
  34751. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  34752. * @param {?string} interpolationType - The interpolation type of the varying.
  34753. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  34754. * @return {NodeVar} The node varying.
  34755. */
  34756. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  34757. const nodeData = this.getDataFromNode( node, 'any' );
  34758. const subBuildVarying = this.getSubBuildProperty( 'varying', nodeData.subBuilds );
  34759. let nodeVarying = nodeData[ subBuildVarying ];
  34760. if ( nodeVarying === undefined ) {
  34761. const varyings = this.varyings;
  34762. const index = varyings.length;
  34763. if ( name === null ) name = 'nodeVarying' + index;
  34764. //
  34765. if ( subBuildVarying !== 'varying' ) {
  34766. name = this.getSubBuildProperty( name, nodeData.subBuilds );
  34767. }
  34768. //
  34769. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  34770. varyings.push( nodeVarying );
  34771. this.registerDeclaration( nodeVarying );
  34772. nodeData[ subBuildVarying ] = nodeVarying;
  34773. }
  34774. return nodeVarying;
  34775. }
  34776. /**
  34777. * Registers a node declaration in the current shader stage.
  34778. *
  34779. * @param {Object} node - The node to be registered.
  34780. */
  34781. registerDeclaration( node ) {
  34782. const shaderStage = this.shaderStage;
  34783. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  34784. const property = this.getPropertyName( node );
  34785. let index = 1;
  34786. let name = property;
  34787. // Automatically renames the property if the name is already in use.
  34788. while ( declarations[ name ] !== undefined ) {
  34789. name = property + '_' + index ++;
  34790. }
  34791. if ( index > 1 ) {
  34792. node.name = name;
  34793. console.warn( `THREE.TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  34794. }
  34795. declarations[ name ] = node;
  34796. }
  34797. /**
  34798. * Returns an instance of {@link NodeCode} for the given code node.
  34799. *
  34800. * @param {CodeNode} node - The code node.
  34801. * @param {string} type - The node type.
  34802. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  34803. * @return {NodeCode} The node code.
  34804. */
  34805. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  34806. const nodeData = this.getDataFromNode( node );
  34807. let nodeCode = nodeData.code;
  34808. if ( nodeCode === undefined ) {
  34809. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  34810. const index = codes.length;
  34811. nodeCode = new NodeCode( 'nodeCode' + index, type );
  34812. codes.push( nodeCode );
  34813. nodeData.code = nodeCode;
  34814. }
  34815. return nodeCode;
  34816. }
  34817. /**
  34818. * Adds a code flow based on the code-block hierarchy.
  34819. * This is used so that code-blocks like If,Else create their variables locally if the Node
  34820. * is only used inside one of these conditionals in the current shader stage.
  34821. *
  34822. * @param {Node} node - The node to add.
  34823. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  34824. */
  34825. addFlowCodeHierarchy( node, nodeBlock ) {
  34826. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  34827. let needsFlowCode = true;
  34828. let nodeBlockHierarchy = nodeBlock;
  34829. while ( nodeBlockHierarchy ) {
  34830. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  34831. needsFlowCode = false;
  34832. break;
  34833. }
  34834. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  34835. }
  34836. if ( needsFlowCode ) {
  34837. for ( const flowCode of flowCodes ) {
  34838. this.addLineFlowCode( flowCode );
  34839. }
  34840. }
  34841. }
  34842. /**
  34843. * Add a inline-code to the current flow code-block.
  34844. *
  34845. * @param {Node} node - The node to add.
  34846. * @param {string} code - The code to add.
  34847. * @param {Node} nodeBlock - Current ConditionalNode
  34848. */
  34849. addLineFlowCodeBlock( node, code, nodeBlock ) {
  34850. const nodeData = this.getDataFromNode( node );
  34851. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  34852. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  34853. flowCodes.push( code );
  34854. codeBlock.set( nodeBlock, true );
  34855. }
  34856. /**
  34857. * Add a inline-code to the current flow.
  34858. *
  34859. * @param {string} code - The code to add.
  34860. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  34861. * @return {NodeBuilder} A reference to this node builder.
  34862. */
  34863. addLineFlowCode( code, node = null ) {
  34864. if ( code === '' ) return this;
  34865. if ( node !== null && this.context.nodeBlock ) {
  34866. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  34867. }
  34868. code = this.tab + code;
  34869. if ( ! /;\s*$/.test( code ) ) {
  34870. code = code + ';\n';
  34871. }
  34872. this.flow.code += code;
  34873. return this;
  34874. }
  34875. /**
  34876. * Adds a code to the current code flow.
  34877. *
  34878. * @param {string} code - Shader code.
  34879. * @return {NodeBuilder} A reference to this node builder.
  34880. */
  34881. addFlowCode( code ) {
  34882. this.flow.code += code;
  34883. return this;
  34884. }
  34885. /**
  34886. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  34887. * Typically used in codes with If,Else.
  34888. *
  34889. * @return {NodeBuilder} A reference to this node builder.
  34890. */
  34891. addFlowTab() {
  34892. this.tab += '\t';
  34893. return this;
  34894. }
  34895. /**
  34896. * Removes a tab.
  34897. *
  34898. * @return {NodeBuilder} A reference to this node builder.
  34899. */
  34900. removeFlowTab() {
  34901. this.tab = this.tab.slice( 0, -1 );
  34902. return this;
  34903. }
  34904. /**
  34905. * Gets the current flow data based on a Node.
  34906. *
  34907. * @param {Node} node - Node that the flow was started.
  34908. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  34909. * @return {Object} The flow data.
  34910. */
  34911. getFlowData( node/*, shaderStage*/ ) {
  34912. return this.flowsData.get( node );
  34913. }
  34914. /**
  34915. * Executes the node flow based on a root node to generate the final shader code.
  34916. *
  34917. * @param {Node} node - The node to execute.
  34918. * @return {Object} The code flow.
  34919. */
  34920. flowNode( node ) {
  34921. const output = node.getNodeType( this );
  34922. const flowData = this.flowChildNode( node, output );
  34923. this.flowsData.set( node, flowData );
  34924. return flowData;
  34925. }
  34926. /**
  34927. * Includes a node in the current function node.
  34928. *
  34929. * @param {Node} node - The node to include.
  34930. * @returns {void}
  34931. */
  34932. addInclude( node ) {
  34933. if ( this.currentFunctionNode !== null ) {
  34934. this.currentFunctionNode.includes.push( node );
  34935. }
  34936. }
  34937. /**
  34938. * Returns the native shader operator name for a given generic name.
  34939. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  34940. *
  34941. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  34942. * @return {FunctionNode} The build function node.
  34943. */
  34944. buildFunctionNode( shaderNode ) {
  34945. const fn = new FunctionNode();
  34946. const previous = this.currentFunctionNode;
  34947. this.currentFunctionNode = fn;
  34948. fn.code = this.buildFunctionCode( shaderNode );
  34949. this.currentFunctionNode = previous;
  34950. return fn;
  34951. }
  34952. /**
  34953. * Generates a code flow based on a TSL function: Fn().
  34954. *
  34955. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  34956. * @return {Object}
  34957. */
  34958. flowShaderNode( shaderNode ) {
  34959. const layout = shaderNode.layout;
  34960. const inputs = {
  34961. [ Symbol.iterator ]() {
  34962. let index = 0;
  34963. const values = Object.values( this );
  34964. return {
  34965. next: () => ( {
  34966. value: values[ index ],
  34967. done: index ++ >= values.length
  34968. } )
  34969. };
  34970. }
  34971. };
  34972. for ( const input of layout.inputs ) {
  34973. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  34974. }
  34975. //
  34976. shaderNode.layout = null;
  34977. const callNode = shaderNode.call( inputs );
  34978. const flowData = this.flowStagesNode( callNode, layout.type );
  34979. shaderNode.layout = layout;
  34980. return flowData;
  34981. }
  34982. /**
  34983. * Executes the node in a specific build stage.
  34984. *
  34985. * @param {Node} node - The node to execute.
  34986. * @param {string} buildStage - The build stage to execute the node in.
  34987. * @param {?(Node|string)} [output=null] - Expected output type. For example 'vec3'.
  34988. * @return {?(Node|string)} The result of the node build.
  34989. */
  34990. flowBuildStage( node, buildStage, output = null ) {
  34991. const previousBuildStage = this.getBuildStage();
  34992. this.setBuildStage( buildStage );
  34993. const result = node.build( this, output );
  34994. this.setBuildStage( previousBuildStage );
  34995. return result;
  34996. }
  34997. /**
  34998. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  34999. *
  35000. * @param {Node} node - The node to execute.
  35001. * @param {?string} output - Expected output type. For example 'vec3'.
  35002. * @return {Object}
  35003. */
  35004. flowStagesNode( node, output = null ) {
  35005. const previousFlow = this.flow;
  35006. const previousVars = this.vars;
  35007. const previousDeclarations = this.declarations;
  35008. const previousCache = this.cache;
  35009. const previousBuildStage = this.buildStage;
  35010. const previousStack = this.stack;
  35011. const flow = {
  35012. code: ''
  35013. };
  35014. this.flow = flow;
  35015. this.vars = {};
  35016. this.declarations = {};
  35017. this.cache = new NodeCache();
  35018. this.stack = stack();
  35019. for ( const buildStage of defaultBuildStages ) {
  35020. this.setBuildStage( buildStage );
  35021. flow.result = node.build( this, output );
  35022. }
  35023. flow.vars = this.getVars( this.shaderStage );
  35024. this.flow = previousFlow;
  35025. this.vars = previousVars;
  35026. this.declarations = previousDeclarations;
  35027. this.cache = previousCache;
  35028. this.stack = previousStack;
  35029. this.setBuildStage( previousBuildStage );
  35030. return flow;
  35031. }
  35032. /**
  35033. * Returns the native shader operator name for a given generic name.
  35034. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  35035. *
  35036. * @abstract
  35037. * @param {string} op - The operator name to resolve.
  35038. * @return {?string} The resolved operator name.
  35039. */
  35040. getFunctionOperator( /* op */ ) {
  35041. return null;
  35042. }
  35043. /**
  35044. * Builds the given shader node.
  35045. *
  35046. * @abstract
  35047. * @param {ShaderNodeInternal} shaderNode - The shader node.
  35048. * @return {string} The function code.
  35049. */
  35050. buildFunctionCode( /* shaderNode */ ) {
  35051. console.warn( 'Abstract function.' );
  35052. }
  35053. /**
  35054. * Generates a code flow based on a child Node.
  35055. *
  35056. * @param {Node} node - The node to execute.
  35057. * @param {?string} output - Expected output type. For example 'vec3'.
  35058. * @return {Object} The code flow.
  35059. */
  35060. flowChildNode( node, output = null ) {
  35061. const previousFlow = this.flow;
  35062. const flow = {
  35063. code: ''
  35064. };
  35065. this.flow = flow;
  35066. flow.result = node.build( this, output );
  35067. this.flow = previousFlow;
  35068. return flow;
  35069. }
  35070. /**
  35071. * Executes a flow of code in a different stage.
  35072. *
  35073. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  35074. * return the value in fragment-stage even if it is being executed in an input fragment.
  35075. *
  35076. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35077. * @param {Node} node - The node to execute.
  35078. * @param {?string} output - Expected output type. For example 'vec3'.
  35079. * @param {?string} propertyName - The property name to assign the result.
  35080. * @return {?(Object|Node)} The code flow or node.build() result.
  35081. */
  35082. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  35083. const previousTab = this.tab;
  35084. const previousCache = this.cache;
  35085. const previousShaderStage = this.shaderStage;
  35086. const previousContext = this.context;
  35087. this.setShaderStage( shaderStage );
  35088. const context = { ...this.context };
  35089. delete context.nodeBlock;
  35090. this.cache = this.globalCache;
  35091. this.tab = '\t';
  35092. this.context = context;
  35093. let result = null;
  35094. if ( this.buildStage === 'generate' ) {
  35095. const flowData = this.flowChildNode( node, output );
  35096. if ( propertyName !== null ) {
  35097. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  35098. }
  35099. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  35100. result = flowData;
  35101. } else {
  35102. result = node.build( this );
  35103. }
  35104. this.setShaderStage( previousShaderStage );
  35105. this.cache = previousCache;
  35106. this.tab = previousTab;
  35107. this.context = previousContext;
  35108. return result;
  35109. }
  35110. /**
  35111. * Returns an array holding all node attributes of this node builder.
  35112. *
  35113. * @return {Array<NodeAttribute>} The node attributes of this builder.
  35114. */
  35115. getAttributesArray() {
  35116. return this.attributes.concat( this.bufferAttributes );
  35117. }
  35118. /**
  35119. * Returns the attribute definitions as a shader string for the given shader stage.
  35120. *
  35121. * @abstract
  35122. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35123. * @return {string} The attribute code section.
  35124. */
  35125. getAttributes( /*shaderStage*/ ) {
  35126. console.warn( 'Abstract function.' );
  35127. }
  35128. /**
  35129. * Returns the varying definitions as a shader string for the given shader stage.
  35130. *
  35131. * @abstract
  35132. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35133. * @return {string} The varying code section.
  35134. */
  35135. getVaryings( /*shaderStage*/ ) {
  35136. console.warn( 'Abstract function.' );
  35137. }
  35138. /**
  35139. * Returns a single variable definition as a shader string for the given variable type and name.
  35140. *
  35141. * @param {string} type - The variable's type.
  35142. * @param {string} name - The variable's name.
  35143. * @param {?number} [count=null] - The array length.
  35144. * @return {string} The shader string.
  35145. */
  35146. getVar( type, name, count = null ) {
  35147. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  35148. }
  35149. /**
  35150. * Returns the variable definitions as a shader string for the given shader stage.
  35151. *
  35152. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35153. * @return {string} The variable code section.
  35154. */
  35155. getVars( shaderStage ) {
  35156. let snippet = '';
  35157. const vars = this.vars[ shaderStage ];
  35158. if ( vars !== undefined ) {
  35159. for ( const variable of vars ) {
  35160. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  35161. }
  35162. }
  35163. return snippet;
  35164. }
  35165. /**
  35166. * Returns the uniform definitions as a shader string for the given shader stage.
  35167. *
  35168. * @abstract
  35169. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35170. * @return {string} The uniform code section.
  35171. */
  35172. getUniforms( /*shaderStage*/ ) {
  35173. console.warn( 'Abstract function.' );
  35174. }
  35175. /**
  35176. * Returns the native code definitions as a shader string for the given shader stage.
  35177. *
  35178. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  35179. * @return {string} The native code section.
  35180. */
  35181. getCodes( shaderStage ) {
  35182. const codes = this.codes[ shaderStage ];
  35183. let code = '';
  35184. if ( codes !== undefined ) {
  35185. for ( const nodeCode of codes ) {
  35186. code += nodeCode.code + '\n';
  35187. }
  35188. }
  35189. return code;
  35190. }
  35191. /**
  35192. * Returns the hash of this node builder.
  35193. *
  35194. * @return {string} The hash.
  35195. */
  35196. getHash() {
  35197. return this.vertexShader + this.fragmentShader + this.computeShader;
  35198. }
  35199. /**
  35200. * Sets the current shader stage.
  35201. *
  35202. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  35203. */
  35204. setShaderStage( shaderStage ) {
  35205. this.shaderStage = shaderStage;
  35206. }
  35207. /**
  35208. * Returns the current shader stage.
  35209. *
  35210. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  35211. */
  35212. getShaderStage() {
  35213. return this.shaderStage;
  35214. }
  35215. /**
  35216. * Sets the current build stage.
  35217. *
  35218. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  35219. */
  35220. setBuildStage( buildStage ) {
  35221. this.buildStage = buildStage;
  35222. }
  35223. /**
  35224. * Returns the current build stage.
  35225. *
  35226. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  35227. */
  35228. getBuildStage() {
  35229. return this.buildStage;
  35230. }
  35231. /**
  35232. * Controls the code build of the shader stages.
  35233. *
  35234. * @abstract
  35235. */
  35236. buildCode() {
  35237. console.warn( 'Abstract function.' );
  35238. }
  35239. /**
  35240. * Returns the current sub-build layer.
  35241. *
  35242. * @return {SubBuildNode} The current sub-build layers.
  35243. */
  35244. get subBuild() {
  35245. return this.subBuildLayers[ this.subBuildLayers.length - 1 ] || null;
  35246. }
  35247. /**
  35248. * Adds a sub-build layer to the node builder.
  35249. *
  35250. * @param {SubBuildNode} subBuild - The sub-build layer to add.
  35251. */
  35252. addSubBuild( subBuild ) {
  35253. this.subBuildLayers.push( subBuild );
  35254. }
  35255. /**
  35256. * Removes the last sub-build layer from the node builder.
  35257. *
  35258. * @return {SubBuildNode} The removed sub-build layer.
  35259. */
  35260. removeSubBuild() {
  35261. return this.subBuildLayers.pop();
  35262. }
  35263. /**
  35264. * Returns the closest sub-build layer for the given data.
  35265. *
  35266. * @param {Node|Set<string>|Array<string>} data - The data to get the closest sub-build layer from.
  35267. * @return {?string} The closest sub-build name or null if none found.
  35268. */
  35269. getClosestSubBuild( data ) {
  35270. let subBuilds;
  35271. if ( data && data.isNode ) {
  35272. if ( data.isShaderCallNodeInternal ) {
  35273. subBuilds = data.shaderNode.subBuilds;
  35274. } else if ( data.isStackNode ) {
  35275. subBuilds = [ data.subBuild ];
  35276. } else {
  35277. subBuilds = this.getDataFromNode( data, 'any' ).subBuilds;
  35278. }
  35279. } else if ( data instanceof Set ) {
  35280. subBuilds = [ ...data ];
  35281. } else {
  35282. subBuilds = data;
  35283. }
  35284. if ( ! subBuilds ) return null;
  35285. const subBuildLayers = this.subBuildLayers;
  35286. for ( let i = subBuilds.length - 1; i >= 0; i -- ) {
  35287. const subBuild = subBuilds[ i ];
  35288. if ( subBuildLayers.includes( subBuild ) ) {
  35289. return subBuild;
  35290. }
  35291. }
  35292. return null;
  35293. }
  35294. /**
  35295. * Returns the output node of a sub-build layer.
  35296. *
  35297. * @param {Node} node - The node to get the output from.
  35298. * @return {string} The output node name.
  35299. */
  35300. getSubBuildOutput( node ) {
  35301. return this.getSubBuildProperty( 'outputNode', node );
  35302. }
  35303. /**
  35304. * Returns the sub-build property name for the given property and node.
  35305. *
  35306. * @param {string} [property=''] - The property name.
  35307. * @param {?Node} [node=null] - The node to get the sub-build from.
  35308. * @return {string} The sub-build property name.
  35309. */
  35310. getSubBuildProperty( property = '', node = null ) {
  35311. let subBuild;
  35312. if ( node !== null ) {
  35313. subBuild = this.getClosestSubBuild( node );
  35314. } else {
  35315. subBuild = this.subBuildFn;
  35316. }
  35317. let result;
  35318. if ( subBuild ) {
  35319. result = property ? ( subBuild + '_' + property ) : subBuild;
  35320. } else {
  35321. result = property;
  35322. }
  35323. return result;
  35324. }
  35325. /**
  35326. * Central build method which controls the build for the given object.
  35327. *
  35328. * @return {NodeBuilder} A reference to this node builder.
  35329. */
  35330. build() {
  35331. const { object, material, renderer } = this;
  35332. if ( material !== null ) {
  35333. let nodeMaterial = renderer.library.fromMaterial( material );
  35334. if ( nodeMaterial === null ) {
  35335. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  35336. nodeMaterial = new NodeMaterial();
  35337. }
  35338. nodeMaterial.build( this );
  35339. } else {
  35340. this.addFlow( 'compute', object );
  35341. }
  35342. // setup() -> stage 1: create possible new nodes and/or return an output reference node
  35343. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  35344. // generate() -> stage 3: generate shader
  35345. for ( const buildStage of defaultBuildStages ) {
  35346. this.setBuildStage( buildStage );
  35347. if ( this.context.vertex && this.context.vertex.isNode ) {
  35348. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  35349. }
  35350. for ( const shaderStage of shaderStages ) {
  35351. this.setShaderStage( shaderStage );
  35352. const flowNodes = this.flowNodes[ shaderStage ];
  35353. for ( const node of flowNodes ) {
  35354. if ( buildStage === 'generate' ) {
  35355. this.flowNode( node );
  35356. } else {
  35357. node.build( this );
  35358. }
  35359. }
  35360. }
  35361. }
  35362. this.setBuildStage( null );
  35363. this.setShaderStage( null );
  35364. // stage 4: build code for a specific output
  35365. this.buildCode();
  35366. this.buildUpdateNodes();
  35367. return this;
  35368. }
  35369. /**
  35370. * Returns a uniform representation which is later used for UBO generation and rendering.
  35371. *
  35372. * @param {NodeUniform} uniformNode - The uniform node.
  35373. * @param {string} type - The requested type.
  35374. * @return {Uniform} The uniform.
  35375. */
  35376. getNodeUniform( uniformNode, type ) {
  35377. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  35378. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  35379. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  35380. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  35381. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  35382. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  35383. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  35384. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  35385. throw new Error( `Uniform "${type}" not declared.` );
  35386. }
  35387. /**
  35388. * Formats the given shader snippet from a given type into another one. E.g.
  35389. * this method might be used to convert a simple float string `"1.0"` into a
  35390. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  35391. *
  35392. * @param {string} snippet - The shader snippet.
  35393. * @param {string} fromType - The source type.
  35394. * @param {string} toType - The target type.
  35395. * @return {string} The updated shader string.
  35396. */
  35397. format( snippet, fromType, toType ) {
  35398. fromType = this.getVectorType( fromType );
  35399. toType = this.getVectorType( toType );
  35400. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  35401. return snippet;
  35402. }
  35403. const fromTypeLength = this.getTypeLength( fromType );
  35404. const toTypeLength = this.getTypeLength( toType );
  35405. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  35406. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  35407. }
  35408. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  35409. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  35410. }
  35411. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  35412. // @TODO: ignore for now
  35413. return snippet;
  35414. }
  35415. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  35416. // @TODO: ignore for now
  35417. return snippet;
  35418. }
  35419. if ( fromTypeLength === toTypeLength ) {
  35420. return `${ this.getType( toType ) }( ${ snippet } )`;
  35421. }
  35422. if ( fromTypeLength > toTypeLength ) {
  35423. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  35424. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  35425. }
  35426. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  35427. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  35428. }
  35429. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  35430. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  35431. }
  35432. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  35433. // convert a number value to vector type, e.g:
  35434. // vec3( 1u ) -> vec3( float( 1u ) )
  35435. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  35436. }
  35437. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  35438. }
  35439. /**
  35440. * Returns a signature with the engine's current revision.
  35441. *
  35442. * @return {string} The signature.
  35443. */
  35444. getSignature() {
  35445. return `// Three.js r${ REVISION } - Node System\n`;
  35446. }
  35447. }
  35448. /**
  35449. * Management class for updating nodes. The module tracks metrics like
  35450. * the elapsed time, delta time, the render and frame ID to correctly
  35451. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  35452. * and {@link Node#updateAfter} depending on the node's configuration.
  35453. */
  35454. class NodeFrame {
  35455. /**
  35456. * Constructs a new node fame.
  35457. */
  35458. constructor() {
  35459. /**
  35460. * The elapsed time in seconds.
  35461. *
  35462. * @type {number}
  35463. * @default 0
  35464. */
  35465. this.time = 0;
  35466. /**
  35467. * The delta time in seconds.
  35468. *
  35469. * @type {number}
  35470. * @default 0
  35471. */
  35472. this.deltaTime = 0;
  35473. /**
  35474. * The frame ID.
  35475. *
  35476. * @type {number}
  35477. * @default 0
  35478. */
  35479. this.frameId = 0;
  35480. /**
  35481. * The render ID.
  35482. *
  35483. * @type {number}
  35484. * @default 0
  35485. */
  35486. this.renderId = 0;
  35487. /**
  35488. * Used to control the {@link Node#update} call.
  35489. *
  35490. * @type {WeakMap<Node, Object>}
  35491. */
  35492. this.updateMap = new WeakMap();
  35493. /**
  35494. * Used to control the {@link Node#updateBefore} call.
  35495. *
  35496. * @type {WeakMap<Node, Object>}
  35497. */
  35498. this.updateBeforeMap = new WeakMap();
  35499. /**
  35500. * Used to control the {@link Node#updateAfter} call.
  35501. *
  35502. * @type {WeakMap<Node, Object>}
  35503. */
  35504. this.updateAfterMap = new WeakMap();
  35505. /**
  35506. * A reference to the current renderer.
  35507. *
  35508. * @type {?Renderer}
  35509. * @default null
  35510. */
  35511. this.renderer = null;
  35512. /**
  35513. * A reference to the current material.
  35514. *
  35515. * @type {?Material}
  35516. * @default null
  35517. */
  35518. this.material = null;
  35519. /**
  35520. * A reference to the current camera.
  35521. *
  35522. * @type {?Camera}
  35523. * @default null
  35524. */
  35525. this.camera = null;
  35526. /**
  35527. * A reference to the current 3D object.
  35528. *
  35529. * @type {?Object3D}
  35530. * @default null
  35531. */
  35532. this.object = null;
  35533. /**
  35534. * A reference to the current scene.
  35535. *
  35536. * @type {?Scene}
  35537. * @default null
  35538. */
  35539. this.scene = null;
  35540. }
  35541. /**
  35542. * Returns a dictionary for a given node and update map which
  35543. * is used to correctly call node update methods per frame or render.
  35544. *
  35545. * @private
  35546. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  35547. * @param {Node} nodeRef - The reference to the current node.
  35548. * @return {Object<string,WeakMap<Object, number>>} The dictionary.
  35549. */
  35550. _getMaps( referenceMap, nodeRef ) {
  35551. let maps = referenceMap.get( nodeRef );
  35552. if ( maps === undefined ) {
  35553. maps = {
  35554. renderMap: new WeakMap(),
  35555. frameMap: new WeakMap()
  35556. };
  35557. referenceMap.set( nodeRef, maps );
  35558. }
  35559. return maps;
  35560. }
  35561. /**
  35562. * This method executes the {@link Node#updateBefore} for the given node.
  35563. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  35564. * is only executed once per frame, render or object depending on the update
  35565. * type.
  35566. *
  35567. * @param {Node} node - The node that should be updated.
  35568. */
  35569. updateBeforeNode( node ) {
  35570. const updateType = node.getUpdateBeforeType();
  35571. const reference = node.updateReference( this );
  35572. if ( updateType === NodeUpdateType.FRAME ) {
  35573. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  35574. if ( frameMap.get( reference ) !== this.frameId ) {
  35575. if ( node.updateBefore( this ) !== false ) {
  35576. frameMap.set( reference, this.frameId );
  35577. }
  35578. }
  35579. } else if ( updateType === NodeUpdateType.RENDER ) {
  35580. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  35581. if ( renderMap.get( reference ) !== this.renderId ) {
  35582. if ( node.updateBefore( this ) !== false ) {
  35583. renderMap.set( reference, this.renderId );
  35584. }
  35585. }
  35586. } else if ( updateType === NodeUpdateType.OBJECT ) {
  35587. node.updateBefore( this );
  35588. }
  35589. }
  35590. /**
  35591. * This method executes the {@link Node#updateAfter} for the given node.
  35592. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  35593. * is only executed once per frame, render or object depending on the update
  35594. * type.
  35595. *
  35596. * @param {Node} node - The node that should be updated.
  35597. */
  35598. updateAfterNode( node ) {
  35599. const updateType = node.getUpdateAfterType();
  35600. const reference = node.updateReference( this );
  35601. if ( updateType === NodeUpdateType.FRAME ) {
  35602. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  35603. if ( frameMap.get( reference ) !== this.frameId ) {
  35604. if ( node.updateAfter( this ) !== false ) {
  35605. frameMap.set( reference, this.frameId );
  35606. }
  35607. }
  35608. } else if ( updateType === NodeUpdateType.RENDER ) {
  35609. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  35610. if ( renderMap.get( reference ) !== this.renderId ) {
  35611. if ( node.updateAfter( this ) !== false ) {
  35612. renderMap.set( reference, this.renderId );
  35613. }
  35614. }
  35615. } else if ( updateType === NodeUpdateType.OBJECT ) {
  35616. node.updateAfter( this );
  35617. }
  35618. }
  35619. /**
  35620. * This method executes the {@link Node#update} for the given node.
  35621. * It makes sure {@link Node#updateType} is honored meaning the update
  35622. * is only executed once per frame, render or object depending on the update
  35623. * type.
  35624. *
  35625. * @param {Node} node - The node that should be updated.
  35626. */
  35627. updateNode( node ) {
  35628. const updateType = node.getUpdateType();
  35629. const reference = node.updateReference( this );
  35630. if ( updateType === NodeUpdateType.FRAME ) {
  35631. const { frameMap } = this._getMaps( this.updateMap, reference );
  35632. if ( frameMap.get( reference ) !== this.frameId ) {
  35633. if ( node.update( this ) !== false ) {
  35634. frameMap.set( reference, this.frameId );
  35635. }
  35636. }
  35637. } else if ( updateType === NodeUpdateType.RENDER ) {
  35638. const { renderMap } = this._getMaps( this.updateMap, reference );
  35639. if ( renderMap.get( reference ) !== this.renderId ) {
  35640. if ( node.update( this ) !== false ) {
  35641. renderMap.set( reference, this.renderId );
  35642. }
  35643. }
  35644. } else if ( updateType === NodeUpdateType.OBJECT ) {
  35645. node.update( this );
  35646. }
  35647. }
  35648. /**
  35649. * Updates the internal state of the node frame. This method is
  35650. * called by the renderer in its internal animation loop.
  35651. */
  35652. update() {
  35653. this.frameId ++;
  35654. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  35655. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  35656. this.lastTime = performance.now();
  35657. this.time += this.deltaTime;
  35658. }
  35659. }
  35660. /**
  35661. * Describes the input of a {@link NodeFunction}.
  35662. */
  35663. class NodeFunctionInput {
  35664. /**
  35665. * Constructs a new node function input.
  35666. *
  35667. * @param {string} type - The input type.
  35668. * @param {string} name - The input name.
  35669. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  35670. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  35671. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  35672. */
  35673. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  35674. /**
  35675. * The input type.
  35676. *
  35677. * @type {string}
  35678. */
  35679. this.type = type;
  35680. /**
  35681. * The input name.
  35682. *
  35683. * @type {string}
  35684. */
  35685. this.name = name;
  35686. /**
  35687. * If the input is an Array, count will be the length.
  35688. *
  35689. * @type {?number}
  35690. * @default null
  35691. */
  35692. this.count = count;
  35693. /**
  35694. *The parameter qualifier (only relevant for GLSL).
  35695. *
  35696. * @type {('in'|'out'|'inout')}
  35697. * @default ''
  35698. */
  35699. this.qualifier = qualifier;
  35700. /**
  35701. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  35702. *
  35703. * @type {boolean}
  35704. * @default false
  35705. */
  35706. this.isConst = isConst;
  35707. }
  35708. }
  35709. NodeFunctionInput.isNodeFunctionInput = true;
  35710. /**
  35711. * Module for representing directional lights as nodes.
  35712. *
  35713. * @augments AnalyticLightNode
  35714. */
  35715. class DirectionalLightNode extends AnalyticLightNode {
  35716. static get type() {
  35717. return 'DirectionalLightNode';
  35718. }
  35719. /**
  35720. * Constructs a new directional light node.
  35721. *
  35722. * @param {?DirectionalLight} [light=null] - The directional light source.
  35723. */
  35724. constructor( light = null ) {
  35725. super( light );
  35726. }
  35727. setupDirect() {
  35728. const lightColor = this.colorNode;
  35729. const lightDirection = lightTargetDirection( this.light );
  35730. return { lightDirection, lightColor };
  35731. }
  35732. }
  35733. const _matrix41 = /*@__PURE__*/ new Matrix4();
  35734. const _matrix42 = /*@__PURE__*/ new Matrix4();
  35735. let _ltcLib = null;
  35736. /**
  35737. * Module for representing rect area lights as nodes.
  35738. *
  35739. * @augments AnalyticLightNode
  35740. */
  35741. class RectAreaLightNode extends AnalyticLightNode {
  35742. static get type() {
  35743. return 'RectAreaLightNode';
  35744. }
  35745. /**
  35746. * Constructs a new rect area light node.
  35747. *
  35748. * @param {?RectAreaLight} [light=null] - The rect area light source.
  35749. */
  35750. constructor( light = null ) {
  35751. super( light );
  35752. /**
  35753. * Uniform node representing the half height of the are light.
  35754. *
  35755. * @type {UniformNode<vec3>}
  35756. */
  35757. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  35758. /**
  35759. * Uniform node representing the half width of the are light.
  35760. *
  35761. * @type {UniformNode<vec3>}
  35762. */
  35763. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  35764. /**
  35765. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  35766. * relies on `viewMatrix` which might vary per render call.
  35767. *
  35768. * @type {string}
  35769. * @default 'render'
  35770. */
  35771. this.updateType = NodeUpdateType.RENDER;
  35772. }
  35773. /**
  35774. * Overwritten to updated rect area light specific uniforms.
  35775. *
  35776. * @param {NodeFrame} frame - A reference to the current node frame.
  35777. */
  35778. update( frame ) {
  35779. super.update( frame );
  35780. const { light } = this;
  35781. const viewMatrix = frame.camera.matrixWorldInverse;
  35782. _matrix42.identity();
  35783. _matrix41.copy( light.matrixWorld );
  35784. _matrix41.premultiply( viewMatrix );
  35785. _matrix42.extractRotation( _matrix41 );
  35786. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  35787. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  35788. this.halfWidth.value.applyMatrix4( _matrix42 );
  35789. this.halfHeight.value.applyMatrix4( _matrix42 );
  35790. }
  35791. setupDirectRectArea( builder ) {
  35792. let ltc_1, ltc_2;
  35793. if ( builder.isAvailable( 'float32Filterable' ) ) {
  35794. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  35795. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  35796. } else {
  35797. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  35798. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  35799. }
  35800. const { colorNode, light } = this;
  35801. const lightPosition = lightViewPosition( light );
  35802. return {
  35803. lightColor: colorNode,
  35804. lightPosition,
  35805. halfWidth: this.halfWidth,
  35806. halfHeight: this.halfHeight,
  35807. ltc_1,
  35808. ltc_2
  35809. };
  35810. }
  35811. /**
  35812. * Used to configure the internal BRDF approximation texture data.
  35813. *
  35814. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  35815. */
  35816. static setLTC( ltc ) {
  35817. _ltcLib = ltc;
  35818. }
  35819. }
  35820. /**
  35821. * Module for representing spot lights as nodes.
  35822. *
  35823. * @augments AnalyticLightNode
  35824. */
  35825. class SpotLightNode extends AnalyticLightNode {
  35826. static get type() {
  35827. return 'SpotLightNode';
  35828. }
  35829. /**
  35830. * Constructs a new spot light node.
  35831. *
  35832. * @param {?SpotLight} [light=null] - The spot light source.
  35833. */
  35834. constructor( light = null ) {
  35835. super( light );
  35836. /**
  35837. * Uniform node representing the cone cosine.
  35838. *
  35839. * @type {UniformNode<float>}
  35840. */
  35841. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  35842. /**
  35843. * Uniform node representing the penumbra cosine.
  35844. *
  35845. * @type {UniformNode<float>}
  35846. */
  35847. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  35848. /**
  35849. * Uniform node representing the cutoff distance.
  35850. *
  35851. * @type {UniformNode<float>}
  35852. */
  35853. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  35854. /**
  35855. * Uniform node representing the decay exponent.
  35856. *
  35857. * @type {UniformNode<float>}
  35858. */
  35859. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  35860. /**
  35861. * Uniform node representing the light color.
  35862. *
  35863. * @type {UniformNode<Color>}
  35864. */
  35865. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  35866. }
  35867. /**
  35868. * Overwritten to updated spot light specific uniforms.
  35869. *
  35870. * @param {NodeFrame} frame - A reference to the current node frame.
  35871. */
  35872. update( frame ) {
  35873. super.update( frame );
  35874. const { light } = this;
  35875. this.coneCosNode.value = Math.cos( light.angle );
  35876. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  35877. this.cutoffDistanceNode.value = light.distance;
  35878. this.decayExponentNode.value = light.decay;
  35879. }
  35880. /**
  35881. * Computes the spot attenuation for the given angle.
  35882. *
  35883. * @param {NodeBuilder} builder - The node builder.
  35884. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  35885. * @return {Node<float>} The spot attenuation.
  35886. */
  35887. getSpotAttenuation( builder, angleCosine ) {
  35888. const { coneCosNode, penumbraCosNode } = this;
  35889. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  35890. }
  35891. getLightCoord( builder ) {
  35892. const properties = builder.getNodeProperties( this );
  35893. let projectionUV = properties.projectionUV;
  35894. if ( projectionUV === undefined ) {
  35895. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  35896. properties.projectionUV = projectionUV;
  35897. }
  35898. return projectionUV;
  35899. }
  35900. setupDirect( builder ) {
  35901. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  35902. const lightVector = this.getLightVector( builder );
  35903. const lightDirection = lightVector.normalize();
  35904. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  35905. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  35906. const lightDistance = lightVector.length();
  35907. const lightAttenuation = getDistanceAttenuation( {
  35908. lightDistance,
  35909. cutoffDistance: cutoffDistanceNode,
  35910. decayExponent: decayExponentNode
  35911. } );
  35912. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  35913. let projected, lightCoord;
  35914. if ( light.colorNode ) {
  35915. lightCoord = this.getLightCoord( builder );
  35916. projected = light.colorNode( lightCoord );
  35917. } else if ( light.map ) {
  35918. lightCoord = this.getLightCoord( builder );
  35919. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  35920. }
  35921. if ( projected ) {
  35922. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  35923. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  35924. }
  35925. return { lightColor, lightDirection };
  35926. }
  35927. }
  35928. /**
  35929. * An IES version of the default spot light node.
  35930. *
  35931. * @augments SpotLightNode
  35932. */
  35933. class IESSpotLightNode extends SpotLightNode {
  35934. static get type() {
  35935. return 'IESSpotLightNode';
  35936. }
  35937. /**
  35938. * Overwrites the default implementation to compute an IES conform spot attenuation.
  35939. *
  35940. * @param {NodeBuilder} builder - The node builder.
  35941. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  35942. * @return {Node<float>} The spot attenuation.
  35943. */
  35944. getSpotAttenuation( builder, angleCosine ) {
  35945. const iesMap = this.light.iesMap;
  35946. let spotAttenuation = null;
  35947. if ( iesMap && iesMap.isTexture === true ) {
  35948. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  35949. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  35950. } else {
  35951. spotAttenuation = super.getSpotAttenuation( angleCosine );
  35952. }
  35953. return spotAttenuation;
  35954. }
  35955. }
  35956. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  35957. const d = p.abs().sub( b );
  35958. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  35959. } );
  35960. /**
  35961. * An implementation of a projector light node.
  35962. *
  35963. * @augments SpotLightNode
  35964. */
  35965. class ProjectorLightNode extends SpotLightNode {
  35966. static get type() {
  35967. return 'ProjectorLightNode';
  35968. }
  35969. update( frame ) {
  35970. super.update( frame );
  35971. const light = this.light;
  35972. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  35973. if ( light.aspect === null ) {
  35974. let aspect = 1;
  35975. if ( light.map !== null ) {
  35976. aspect = light.map.width / light.map.height;
  35977. }
  35978. light.shadow.aspect = aspect;
  35979. } else {
  35980. light.shadow.aspect = light.aspect;
  35981. }
  35982. }
  35983. /**
  35984. * Overwrites the default implementation to compute projection attenuation.
  35985. *
  35986. * @param {NodeBuilder} builder - The node builder.
  35987. * @return {Node<float>} The spot attenuation.
  35988. */
  35989. getSpotAttenuation( builder ) {
  35990. const attenuation = float( 0 );
  35991. const penumbraCos = this.penumbraCosNode;
  35992. // compute the fragment's position in the light's clip space
  35993. const spotLightCoord = lightShadowMatrix( this.light ).mul( builder.context.positionWorld || positionWorld );
  35994. // the sign of w determines whether the current fragment is in front or behind the light.
  35995. // to avoid a back-projection, it's important to only compute an attenuation if w is positive
  35996. If( spotLightCoord.w.greaterThan( 0 ), () => {
  35997. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  35998. const boxDist = sdBox( projectionUV.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  35999. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  36000. attenuation.assign( saturate( boxDist.mul( -2 ).mul( angleFactor ) ) );
  36001. } );
  36002. return attenuation;
  36003. }
  36004. }
  36005. /**
  36006. * Module for representing ambient lights as nodes.
  36007. *
  36008. * @augments AnalyticLightNode
  36009. */
  36010. class AmbientLightNode extends AnalyticLightNode {
  36011. static get type() {
  36012. return 'AmbientLightNode';
  36013. }
  36014. /**
  36015. * Constructs a new ambient light node.
  36016. *
  36017. * @param {?AmbientLight} [light=null] - The ambient light source.
  36018. */
  36019. constructor( light = null ) {
  36020. super( light );
  36021. }
  36022. setup( { context } ) {
  36023. context.irradiance.addAssign( this.colorNode );
  36024. }
  36025. }
  36026. /**
  36027. * Module for representing hemisphere lights as nodes.
  36028. *
  36029. * @augments AnalyticLightNode
  36030. */
  36031. class HemisphereLightNode extends AnalyticLightNode {
  36032. static get type() {
  36033. return 'HemisphereLightNode';
  36034. }
  36035. /**
  36036. * Constructs a new hemisphere light node.
  36037. *
  36038. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  36039. */
  36040. constructor( light = null ) {
  36041. super( light );
  36042. /**
  36043. * Uniform node representing the light's position.
  36044. *
  36045. * @type {UniformNode<vec3>}
  36046. */
  36047. this.lightPositionNode = lightPosition( light );
  36048. /**
  36049. * A node representing the light's direction.
  36050. *
  36051. * @type {Node<vec3>}
  36052. */
  36053. this.lightDirectionNode = this.lightPositionNode.normalize();
  36054. /**
  36055. * Uniform node representing the light's ground color.
  36056. *
  36057. * @type {UniformNode<vec3>}
  36058. */
  36059. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  36060. }
  36061. /**
  36062. * Overwritten to updated hemisphere light specific uniforms.
  36063. *
  36064. * @param {NodeFrame} frame - A reference to the current node frame.
  36065. */
  36066. update( frame ) {
  36067. const { light } = this;
  36068. super.update( frame );
  36069. this.lightPositionNode.object3d = light;
  36070. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  36071. }
  36072. setup( builder ) {
  36073. const { colorNode, groundColorNode, lightDirectionNode } = this;
  36074. const dotNL = normalWorld.dot( lightDirectionNode );
  36075. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  36076. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  36077. builder.context.irradiance.addAssign( irradiance );
  36078. }
  36079. }
  36080. /**
  36081. * Module for representing light probes as nodes.
  36082. *
  36083. * @augments AnalyticLightNode
  36084. */
  36085. class LightProbeNode extends AnalyticLightNode {
  36086. static get type() {
  36087. return 'LightProbeNode';
  36088. }
  36089. /**
  36090. * Constructs a new light probe node.
  36091. *
  36092. * @param {?LightProbe} [light=null] - The light probe.
  36093. */
  36094. constructor( light = null ) {
  36095. super( light );
  36096. const array = [];
  36097. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  36098. /**
  36099. * Light probe represented as a uniform of spherical harmonics.
  36100. *
  36101. * @type {UniformArrayNode}
  36102. */
  36103. this.lightProbe = uniformArray( array );
  36104. }
  36105. /**
  36106. * Overwritten to updated light probe specific uniforms.
  36107. *
  36108. * @param {NodeFrame} frame - A reference to the current node frame.
  36109. */
  36110. update( frame ) {
  36111. const { light } = this;
  36112. super.update( frame );
  36113. //
  36114. for ( let i = 0; i < 9; i ++ ) {
  36115. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  36116. }
  36117. }
  36118. setup( builder ) {
  36119. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  36120. builder.context.irradiance.addAssign( irradiance );
  36121. }
  36122. }
  36123. /**
  36124. * Base class for node parsers. A derived parser must be implemented
  36125. * for each supported native shader language.
  36126. */
  36127. class NodeParser {
  36128. /**
  36129. * The method parses the given native code an returns a node function.
  36130. *
  36131. * @abstract
  36132. * @param {string} source - The native shader code.
  36133. * @return {NodeFunction} A node function.
  36134. */
  36135. parseFunction( /*source*/ ) {
  36136. console.warn( 'Abstract function.' );
  36137. }
  36138. }
  36139. /**
  36140. * Base class for node functions. A derived module must be implemented
  36141. * for each supported native shader language. Similar to other `Node*` modules,
  36142. * this class is only relevant during the building process and not used
  36143. * in user-level code.
  36144. */
  36145. class NodeFunction {
  36146. /**
  36147. * Constructs a new node function.
  36148. *
  36149. * @param {string} type - The node type. This type is the return type of the node function.
  36150. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  36151. * @param {string} [name=''] - The function's name.
  36152. * @param {string} [precision=''] - The precision qualifier.
  36153. */
  36154. constructor( type, inputs, name = '', precision = '' ) {
  36155. /**
  36156. * The node type. This type is the return type of the node function.
  36157. *
  36158. * @type {string}
  36159. */
  36160. this.type = type;
  36161. /**
  36162. * The function's inputs.
  36163. *
  36164. * @type {Array<NodeFunctionInput>}
  36165. */
  36166. this.inputs = inputs;
  36167. /**
  36168. * The name of the uniform.
  36169. *
  36170. * @type {string}
  36171. * @default ''
  36172. */
  36173. this.name = name;
  36174. /**
  36175. * The precision qualifier.
  36176. *
  36177. * @type {string}
  36178. * @default ''
  36179. */
  36180. this.precision = precision;
  36181. }
  36182. /**
  36183. * This method returns the native code of the node function.
  36184. *
  36185. * @abstract
  36186. * @param {string} name - The function's name.
  36187. * @return {string} A shader code.
  36188. */
  36189. getCode( /*name = this.name*/ ) {
  36190. console.warn( 'Abstract function.' );
  36191. }
  36192. }
  36193. NodeFunction.isNodeFunction = true;
  36194. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  36195. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  36196. const pragmaMain = '#pragma main';
  36197. const parse$1 = ( source ) => {
  36198. source = source.trim();
  36199. const pragmaMainIndex = source.indexOf( pragmaMain );
  36200. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  36201. const declaration = mainCode.match( declarationRegexp$1 );
  36202. if ( declaration !== null && declaration.length === 5 ) {
  36203. // tokenizer
  36204. const inputsCode = declaration[ 4 ];
  36205. const propsMatches = [];
  36206. let nameMatch = null;
  36207. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  36208. propsMatches.push( nameMatch );
  36209. }
  36210. // parser
  36211. const inputs = [];
  36212. let i = 0;
  36213. while ( i < propsMatches.length ) {
  36214. const isConst = propsMatches[ i ][ 0 ] === 'const';
  36215. if ( isConst === true ) {
  36216. i ++;
  36217. }
  36218. let qualifier = propsMatches[ i ][ 0 ];
  36219. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  36220. i ++;
  36221. } else {
  36222. qualifier = '';
  36223. }
  36224. const type = propsMatches[ i ++ ][ 0 ];
  36225. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  36226. if ( Number.isNaN( count ) === false ) i ++;
  36227. else count = null;
  36228. const name = propsMatches[ i ++ ][ 0 ];
  36229. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  36230. }
  36231. //
  36232. const blockCode = mainCode.substring( declaration[ 0 ].length );
  36233. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  36234. const type = declaration[ 2 ];
  36235. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  36236. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  36237. return {
  36238. type,
  36239. inputs,
  36240. name,
  36241. precision,
  36242. inputsCode,
  36243. blockCode,
  36244. headerCode
  36245. };
  36246. } else {
  36247. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  36248. }
  36249. };
  36250. /**
  36251. * This class represents a GLSL node function.
  36252. *
  36253. * @augments NodeFunction
  36254. */
  36255. class GLSLNodeFunction extends NodeFunction {
  36256. /**
  36257. * Constructs a new GLSL node function.
  36258. *
  36259. * @param {string} source - The GLSL source.
  36260. */
  36261. constructor( source ) {
  36262. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  36263. super( type, inputs, name, precision );
  36264. this.inputsCode = inputsCode;
  36265. this.blockCode = blockCode;
  36266. this.headerCode = headerCode;
  36267. }
  36268. /**
  36269. * This method returns the GLSL code of the node function.
  36270. *
  36271. * @param {string} [name=this.name] - The function's name.
  36272. * @return {string} The shader code.
  36273. */
  36274. getCode( name = this.name ) {
  36275. let code;
  36276. const blockCode = this.blockCode;
  36277. if ( blockCode !== '' ) {
  36278. const { type, inputsCode, headerCode, precision } = this;
  36279. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  36280. if ( precision !== '' ) {
  36281. declarationCode = `${ precision } ${ declarationCode }`;
  36282. }
  36283. code = headerCode + declarationCode + blockCode;
  36284. } else {
  36285. // interface function
  36286. code = '';
  36287. }
  36288. return code;
  36289. }
  36290. }
  36291. /**
  36292. * A GLSL node parser.
  36293. *
  36294. * @augments NodeParser
  36295. */
  36296. class GLSLNodeParser extends NodeParser {
  36297. /**
  36298. * The method parses the given GLSL code an returns a node function.
  36299. *
  36300. * @param {string} source - The GLSL code.
  36301. * @return {GLSLNodeFunction} A node function.
  36302. */
  36303. parseFunction( source ) {
  36304. return new GLSLNodeFunction( source );
  36305. }
  36306. }
  36307. const _outputNodeMap = new WeakMap();
  36308. const _chainKeys$2 = [];
  36309. const _cacheKeyValues = [];
  36310. /**
  36311. * This renderer module manages node-related objects and is the
  36312. * primary interface between the renderer and the node system.
  36313. *
  36314. * @private
  36315. * @augments DataMap
  36316. */
  36317. class Nodes extends DataMap {
  36318. /**
  36319. * Constructs a new nodes management component.
  36320. *
  36321. * @param {Renderer} renderer - The renderer.
  36322. * @param {Backend} backend - The renderer's backend.
  36323. */
  36324. constructor( renderer, backend ) {
  36325. super();
  36326. /**
  36327. * The renderer.
  36328. *
  36329. * @type {Renderer}
  36330. */
  36331. this.renderer = renderer;
  36332. /**
  36333. * The renderer's backend.
  36334. *
  36335. * @type {Backend}
  36336. */
  36337. this.backend = backend;
  36338. /**
  36339. * The node frame.
  36340. *
  36341. * @type {Renderer}
  36342. */
  36343. this.nodeFrame = new NodeFrame();
  36344. /**
  36345. * A cache for managing node builder states.
  36346. *
  36347. * @type {Map<number,NodeBuilderState>}
  36348. */
  36349. this.nodeBuilderCache = new Map();
  36350. /**
  36351. * A cache for managing data cache key data.
  36352. *
  36353. * @type {ChainMap}
  36354. */
  36355. this.callHashCache = new ChainMap();
  36356. /**
  36357. * A cache for managing node uniforms group data.
  36358. *
  36359. * @type {ChainMap}
  36360. */
  36361. this.groupsData = new ChainMap();
  36362. /**
  36363. * A cache for managing node objects of
  36364. * scene properties like fog or environments.
  36365. *
  36366. * @type {Object<string,WeakMap>}
  36367. */
  36368. this.cacheLib = {};
  36369. }
  36370. /**
  36371. * Returns `true` if the given node uniforms group must be updated or not.
  36372. *
  36373. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  36374. * @return {boolean} Whether the node uniforms group requires an update or not.
  36375. */
  36376. updateGroup( nodeUniformsGroup ) {
  36377. const groupNode = nodeUniformsGroup.groupNode;
  36378. const name = groupNode.name;
  36379. // objectGroup is always updated
  36380. if ( name === objectGroup.name ) return true;
  36381. // renderGroup is updated once per render/compute call
  36382. if ( name === renderGroup.name ) {
  36383. const uniformsGroupData = this.get( nodeUniformsGroup );
  36384. const renderId = this.nodeFrame.renderId;
  36385. if ( uniformsGroupData.renderId !== renderId ) {
  36386. uniformsGroupData.renderId = renderId;
  36387. return true;
  36388. }
  36389. return false;
  36390. }
  36391. // frameGroup is updated once per frame
  36392. if ( name === frameGroup.name ) {
  36393. const uniformsGroupData = this.get( nodeUniformsGroup );
  36394. const frameId = this.nodeFrame.frameId;
  36395. if ( uniformsGroupData.frameId !== frameId ) {
  36396. uniformsGroupData.frameId = frameId;
  36397. return true;
  36398. }
  36399. return false;
  36400. }
  36401. // other groups are updated just when groupNode.needsUpdate is true
  36402. _chainKeys$2[ 0 ] = groupNode;
  36403. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  36404. let groupData = this.groupsData.get( _chainKeys$2 );
  36405. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  36406. _chainKeys$2.length = 0;
  36407. if ( groupData.version !== groupNode.version ) {
  36408. groupData.version = groupNode.version;
  36409. return true;
  36410. }
  36411. return false;
  36412. }
  36413. /**
  36414. * Returns the cache key for the given render object.
  36415. *
  36416. * @param {RenderObject} renderObject - The render object.
  36417. * @return {number} The cache key.
  36418. */
  36419. getForRenderCacheKey( renderObject ) {
  36420. return renderObject.initialCacheKey;
  36421. }
  36422. /**
  36423. * Returns a node builder state for the given render object.
  36424. *
  36425. * @param {RenderObject} renderObject - The render object.
  36426. * @return {NodeBuilderState} The node builder state.
  36427. */
  36428. getForRender( renderObject ) {
  36429. const renderObjectData = this.get( renderObject );
  36430. let nodeBuilderState = renderObjectData.nodeBuilderState;
  36431. if ( nodeBuilderState === undefined ) {
  36432. const { nodeBuilderCache } = this;
  36433. const cacheKey = this.getForRenderCacheKey( renderObject );
  36434. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  36435. if ( nodeBuilderState === undefined ) {
  36436. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  36437. nodeBuilder.scene = renderObject.scene;
  36438. nodeBuilder.material = renderObject.material;
  36439. nodeBuilder.camera = renderObject.camera;
  36440. nodeBuilder.context.material = renderObject.material;
  36441. nodeBuilder.lightsNode = renderObject.lightsNode;
  36442. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  36443. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  36444. nodeBuilder.clippingContext = renderObject.clippingContext;
  36445. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  36446. nodeBuilder.enableMultiview();
  36447. }
  36448. nodeBuilder.build();
  36449. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36450. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  36451. }
  36452. nodeBuilderState.usedTimes ++;
  36453. renderObjectData.nodeBuilderState = nodeBuilderState;
  36454. }
  36455. return nodeBuilderState;
  36456. }
  36457. /**
  36458. * Deletes the given object from the internal data map
  36459. *
  36460. * @param {any} object - The object to delete.
  36461. * @return {?Object} The deleted dictionary.
  36462. */
  36463. delete( object ) {
  36464. if ( object.isRenderObject ) {
  36465. const nodeBuilderState = this.get( object ).nodeBuilderState;
  36466. nodeBuilderState.usedTimes --;
  36467. if ( nodeBuilderState.usedTimes === 0 ) {
  36468. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  36469. }
  36470. }
  36471. return super.delete( object );
  36472. }
  36473. /**
  36474. * Returns a node builder state for the given compute node.
  36475. *
  36476. * @param {Node} computeNode - The compute node.
  36477. * @return {NodeBuilderState} The node builder state.
  36478. */
  36479. getForCompute( computeNode ) {
  36480. const computeData = this.get( computeNode );
  36481. let nodeBuilderState = computeData.nodeBuilderState;
  36482. if ( nodeBuilderState === undefined ) {
  36483. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  36484. nodeBuilder.build();
  36485. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  36486. computeData.nodeBuilderState = nodeBuilderState;
  36487. }
  36488. return nodeBuilderState;
  36489. }
  36490. /**
  36491. * Creates a node builder state for the given node builder.
  36492. *
  36493. * @private
  36494. * @param {NodeBuilder} nodeBuilder - The node builder.
  36495. * @return {NodeBuilderState} The node builder state.
  36496. */
  36497. _createNodeBuilderState( nodeBuilder ) {
  36498. return new NodeBuilderState(
  36499. nodeBuilder.vertexShader,
  36500. nodeBuilder.fragmentShader,
  36501. nodeBuilder.computeShader,
  36502. nodeBuilder.getAttributesArray(),
  36503. nodeBuilder.getBindings(),
  36504. nodeBuilder.updateNodes,
  36505. nodeBuilder.updateBeforeNodes,
  36506. nodeBuilder.updateAfterNodes,
  36507. nodeBuilder.observer,
  36508. nodeBuilder.transforms
  36509. );
  36510. }
  36511. /**
  36512. * Returns an environment node for the current configured
  36513. * scene environment.
  36514. *
  36515. * @param {Scene} scene - The scene.
  36516. * @return {Node} A node representing the current scene environment.
  36517. */
  36518. getEnvironmentNode( scene ) {
  36519. this.updateEnvironment( scene );
  36520. let environmentNode = null;
  36521. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  36522. environmentNode = scene.environmentNode;
  36523. } else {
  36524. const sceneData = this.get( scene );
  36525. if ( sceneData.environmentNode ) {
  36526. environmentNode = sceneData.environmentNode;
  36527. }
  36528. }
  36529. return environmentNode;
  36530. }
  36531. /**
  36532. * Returns a background node for the current configured
  36533. * scene background.
  36534. *
  36535. * @param {Scene} scene - The scene.
  36536. * @return {Node} A node representing the current scene background.
  36537. */
  36538. getBackgroundNode( scene ) {
  36539. this.updateBackground( scene );
  36540. let backgroundNode = null;
  36541. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  36542. backgroundNode = scene.backgroundNode;
  36543. } else {
  36544. const sceneData = this.get( scene );
  36545. if ( sceneData.backgroundNode ) {
  36546. backgroundNode = sceneData.backgroundNode;
  36547. }
  36548. }
  36549. return backgroundNode;
  36550. }
  36551. /**
  36552. * Returns a fog node for the current configured scene fog.
  36553. *
  36554. * @param {Scene} scene - The scene.
  36555. * @return {Node} A node representing the current scene fog.
  36556. */
  36557. getFogNode( scene ) {
  36558. this.updateFog( scene );
  36559. return scene.fogNode || this.get( scene ).fogNode || null;
  36560. }
  36561. /**
  36562. * Returns a cache key for the given scene and lights node.
  36563. * This key is used by `RenderObject` as a part of the dynamic
  36564. * cache key (a key that must be checked every time the render
  36565. * objects is drawn).
  36566. *
  36567. * @param {Scene} scene - The scene.
  36568. * @param {LightsNode} lightsNode - The lights node.
  36569. * @return {number} The cache key.
  36570. */
  36571. getCacheKey( scene, lightsNode ) {
  36572. _chainKeys$2[ 0 ] = scene;
  36573. _chainKeys$2[ 1 ] = lightsNode;
  36574. const callId = this.renderer.info.calls;
  36575. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  36576. if ( cacheKeyData.callId !== callId ) {
  36577. const environmentNode = this.getEnvironmentNode( scene );
  36578. const fogNode = this.getFogNode( scene );
  36579. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  36580. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  36581. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  36582. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  36583. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  36584. cacheKeyData.callId = callId;
  36585. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  36586. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  36587. _cacheKeyValues.length = 0;
  36588. }
  36589. _chainKeys$2.length = 0;
  36590. return cacheKeyData.cacheKey;
  36591. }
  36592. /**
  36593. * A boolean that indicates whether tone mapping should be enabled
  36594. * or not.
  36595. *
  36596. * @type {boolean}
  36597. */
  36598. get isToneMappingState() {
  36599. return this.renderer.getRenderTarget() ? false : true;
  36600. }
  36601. /**
  36602. * If a scene background is configured, this method makes sure to
  36603. * represent the background with a corresponding node-based implementation.
  36604. *
  36605. * @param {Scene} scene - The scene.
  36606. */
  36607. updateBackground( scene ) {
  36608. const sceneData = this.get( scene );
  36609. const background = scene.background;
  36610. if ( background ) {
  36611. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  36612. if ( sceneData.background !== background || forceUpdate ) {
  36613. const backgroundNode = this.getCacheNode( 'background', background, () => {
  36614. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  36615. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  36616. return pmremTexture( background );
  36617. } else {
  36618. let envMap;
  36619. if ( background.isCubeTexture === true ) {
  36620. envMap = cubeTexture( background );
  36621. } else {
  36622. envMap = texture( background );
  36623. }
  36624. return cubeMapNode( envMap );
  36625. }
  36626. } else if ( background.isTexture === true ) {
  36627. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  36628. } else if ( background.isColor !== true ) {
  36629. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  36630. }
  36631. }, forceUpdate );
  36632. sceneData.backgroundNode = backgroundNode;
  36633. sceneData.background = background;
  36634. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  36635. }
  36636. } else if ( sceneData.backgroundNode ) {
  36637. delete sceneData.backgroundNode;
  36638. delete sceneData.background;
  36639. }
  36640. }
  36641. /**
  36642. * This method is part of the caching of nodes which are used to represents the
  36643. * scene's background, fog or environment.
  36644. *
  36645. * @param {string} type - The type of object to cache.
  36646. * @param {Object} object - The object.
  36647. * @param {Function} callback - A callback that produces a node representation for the given object.
  36648. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  36649. * @return {Node} The node representation.
  36650. */
  36651. getCacheNode( type, object, callback, forceUpdate = false ) {
  36652. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  36653. let node = nodeCache.get( object );
  36654. if ( node === undefined || forceUpdate ) {
  36655. node = callback();
  36656. nodeCache.set( object, node );
  36657. }
  36658. return node;
  36659. }
  36660. /**
  36661. * If a scene fog is configured, this method makes sure to
  36662. * represent the fog with a corresponding node-based implementation.
  36663. *
  36664. * @param {Scene} scene - The scene.
  36665. */
  36666. updateFog( scene ) {
  36667. const sceneData = this.get( scene );
  36668. const sceneFog = scene.fog;
  36669. if ( sceneFog ) {
  36670. if ( sceneData.fog !== sceneFog ) {
  36671. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  36672. if ( sceneFog.isFogExp2 ) {
  36673. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  36674. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  36675. return fog( color, densityFogFactor( density ) );
  36676. } else if ( sceneFog.isFog ) {
  36677. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  36678. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  36679. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  36680. return fog( color, rangeFogFactor( near, far ) );
  36681. } else {
  36682. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  36683. }
  36684. } );
  36685. sceneData.fogNode = fogNode;
  36686. sceneData.fog = sceneFog;
  36687. }
  36688. } else {
  36689. delete sceneData.fogNode;
  36690. delete sceneData.fog;
  36691. }
  36692. }
  36693. /**
  36694. * If a scene environment is configured, this method makes sure to
  36695. * represent the environment with a corresponding node-based implementation.
  36696. *
  36697. * @param {Scene} scene - The scene.
  36698. */
  36699. updateEnvironment( scene ) {
  36700. const sceneData = this.get( scene );
  36701. const environment = scene.environment;
  36702. if ( environment ) {
  36703. if ( sceneData.environment !== environment ) {
  36704. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  36705. if ( environment.isCubeTexture === true ) {
  36706. return cubeTexture( environment );
  36707. } else if ( environment.isTexture === true ) {
  36708. return texture( environment );
  36709. } else {
  36710. console.error( 'Nodes: Unsupported environment configuration.', environment );
  36711. }
  36712. } );
  36713. sceneData.environmentNode = environmentNode;
  36714. sceneData.environment = environment;
  36715. }
  36716. } else if ( sceneData.environmentNode ) {
  36717. delete sceneData.environmentNode;
  36718. delete sceneData.environment;
  36719. }
  36720. }
  36721. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  36722. const nodeFrame = this.nodeFrame;
  36723. nodeFrame.renderer = renderer;
  36724. nodeFrame.scene = scene;
  36725. nodeFrame.object = object;
  36726. nodeFrame.camera = camera;
  36727. nodeFrame.material = material;
  36728. return nodeFrame;
  36729. }
  36730. getNodeFrameForRender( renderObject ) {
  36731. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  36732. }
  36733. /**
  36734. * Returns the current output cache key.
  36735. *
  36736. * @return {string} The output cache key.
  36737. */
  36738. getOutputCacheKey() {
  36739. const renderer = this.renderer;
  36740. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  36741. }
  36742. /**
  36743. * Checks if the output configuration (tone mapping and color space) for
  36744. * the given target has changed.
  36745. *
  36746. * @param {Texture} outputTarget - The output target.
  36747. * @return {boolean} Whether the output configuration has changed or not.
  36748. */
  36749. hasOutputChange( outputTarget ) {
  36750. const cacheKey = _outputNodeMap.get( outputTarget );
  36751. return cacheKey !== this.getOutputCacheKey();
  36752. }
  36753. /**
  36754. * Returns a node that represents the output configuration (tone mapping and
  36755. * color space) for the current target.
  36756. *
  36757. * @param {Texture} outputTarget - The output target.
  36758. * @return {Node} The output node.
  36759. */
  36760. getOutputNode( outputTarget ) {
  36761. const renderer = this.renderer;
  36762. const cacheKey = this.getOutputCacheKey();
  36763. const output = outputTarget.isArrayTexture ?
  36764. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  36765. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  36766. _outputNodeMap.set( outputTarget, cacheKey );
  36767. return output;
  36768. }
  36769. /**
  36770. * Triggers the call of `updateBefore()` methods
  36771. * for all nodes of the given render object.
  36772. *
  36773. * @param {RenderObject} renderObject - The render object.
  36774. */
  36775. updateBefore( renderObject ) {
  36776. const nodeBuilder = renderObject.getNodeBuilderState();
  36777. for ( const node of nodeBuilder.updateBeforeNodes ) {
  36778. // update frame state for each node
  36779. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  36780. }
  36781. }
  36782. /**
  36783. * Triggers the call of `updateAfter()` methods
  36784. * for all nodes of the given render object.
  36785. *
  36786. * @param {RenderObject} renderObject - The render object.
  36787. */
  36788. updateAfter( renderObject ) {
  36789. const nodeBuilder = renderObject.getNodeBuilderState();
  36790. for ( const node of nodeBuilder.updateAfterNodes ) {
  36791. // update frame state for each node
  36792. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  36793. }
  36794. }
  36795. /**
  36796. * Triggers the call of `update()` methods
  36797. * for all nodes of the given compute node.
  36798. *
  36799. * @param {Node} computeNode - The compute node.
  36800. */
  36801. updateForCompute( computeNode ) {
  36802. const nodeFrame = this.getNodeFrame();
  36803. const nodeBuilder = this.getForCompute( computeNode );
  36804. for ( const node of nodeBuilder.updateNodes ) {
  36805. nodeFrame.updateNode( node );
  36806. }
  36807. }
  36808. /**
  36809. * Triggers the call of `update()` methods
  36810. * for all nodes of the given compute node.
  36811. *
  36812. * @param {RenderObject} renderObject - The render object.
  36813. */
  36814. updateForRender( renderObject ) {
  36815. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36816. const nodeBuilder = renderObject.getNodeBuilderState();
  36817. for ( const node of nodeBuilder.updateNodes ) {
  36818. nodeFrame.updateNode( node );
  36819. }
  36820. }
  36821. /**
  36822. * Returns `true` if the given render object requires a refresh.
  36823. *
  36824. * @param {RenderObject} renderObject - The render object.
  36825. * @return {boolean} Whether the given render object requires a refresh or not.
  36826. */
  36827. needsRefresh( renderObject ) {
  36828. const nodeFrame = this.getNodeFrameForRender( renderObject );
  36829. const monitor = renderObject.getMonitor();
  36830. return monitor.needsRefresh( renderObject, nodeFrame );
  36831. }
  36832. /**
  36833. * Frees the internal resources.
  36834. */
  36835. dispose() {
  36836. super.dispose();
  36837. this.nodeFrame = new NodeFrame();
  36838. this.nodeBuilderCache = new Map();
  36839. this.cacheLib = {};
  36840. }
  36841. }
  36842. const _plane = /*@__PURE__*/ new Plane();
  36843. /**
  36844. * Represents the state that is used to perform clipping via clipping planes.
  36845. * There is a default clipping context for each render context. When the
  36846. * scene holds instances of `ClippingGroup`, there will be a context for each
  36847. * group.
  36848. *
  36849. * @private
  36850. */
  36851. class ClippingContext {
  36852. /**
  36853. * Constructs a new clipping context.
  36854. *
  36855. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  36856. */
  36857. constructor( parentContext = null ) {
  36858. /**
  36859. * The clipping context's version.
  36860. *
  36861. * @type {number}
  36862. * @readonly
  36863. */
  36864. this.version = 0;
  36865. /**
  36866. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  36867. *
  36868. * @type {?boolean}
  36869. * @default null
  36870. */
  36871. this.clipIntersection = null;
  36872. /**
  36873. * The clipping context's cache key.
  36874. *
  36875. * @type {string}
  36876. */
  36877. this.cacheKey = '';
  36878. /**
  36879. * Whether the shadow pass is active or not.
  36880. *
  36881. * @type {boolean}
  36882. * @default false
  36883. */
  36884. this.shadowPass = false;
  36885. /**
  36886. * The view normal matrix.
  36887. *
  36888. * @type {Matrix3}
  36889. */
  36890. this.viewNormalMatrix = new Matrix3();
  36891. /**
  36892. * Internal cache for maintaining clipping contexts.
  36893. *
  36894. * @type {WeakMap<ClippingGroup,ClippingContext>}
  36895. */
  36896. this.clippingGroupContexts = new WeakMap();
  36897. /**
  36898. * The intersection planes.
  36899. *
  36900. * @type {Array<Vector4>}
  36901. */
  36902. this.intersectionPlanes = [];
  36903. /**
  36904. * The intersection planes.
  36905. *
  36906. * @type {Array<Vector4>}
  36907. */
  36908. this.unionPlanes = [];
  36909. /**
  36910. * The version of the clipping context's parent context.
  36911. *
  36912. * @type {?number}
  36913. * @readonly
  36914. */
  36915. this.parentVersion = null;
  36916. if ( parentContext !== null ) {
  36917. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  36918. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  36919. this.shadowPass = parentContext.shadowPass;
  36920. this.viewMatrix = parentContext.viewMatrix;
  36921. }
  36922. }
  36923. /**
  36924. * Projects the given source clipping planes and writes the result into the
  36925. * destination array.
  36926. *
  36927. * @param {Array<Plane>} source - The source clipping planes.
  36928. * @param {Array<Vector4>} destination - The destination.
  36929. * @param {number} offset - The offset.
  36930. */
  36931. projectPlanes( source, destination, offset ) {
  36932. const l = source.length;
  36933. for ( let i = 0; i < l; i ++ ) {
  36934. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  36935. const v = destination[ offset + i ];
  36936. const normal = _plane.normal;
  36937. v.x = - normal.x;
  36938. v.y = - normal.y;
  36939. v.z = - normal.z;
  36940. v.w = _plane.constant;
  36941. }
  36942. }
  36943. /**
  36944. * Updates the root clipping context of a scene.
  36945. *
  36946. * @param {Scene} scene - The scene.
  36947. * @param {Camera} camera - The camera that is used to render the scene.
  36948. */
  36949. updateGlobal( scene, camera ) {
  36950. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  36951. this.viewMatrix = camera.matrixWorldInverse;
  36952. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  36953. }
  36954. /**
  36955. * Updates the clipping context.
  36956. *
  36957. * @param {ClippingContext} parentContext - The parent context.
  36958. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  36959. */
  36960. update( parentContext, clippingGroup ) {
  36961. let update = false;
  36962. if ( parentContext.version !== this.parentVersion ) {
  36963. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  36964. this.unionPlanes = Array.from( parentContext.unionPlanes );
  36965. this.parentVersion = parentContext.version;
  36966. }
  36967. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  36968. this.clipIntersection = clippingGroup.clipIntersection;
  36969. if ( this.clipIntersection ) {
  36970. this.unionPlanes.length = parentContext.unionPlanes.length;
  36971. } else {
  36972. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  36973. }
  36974. }
  36975. const srcClippingPlanes = clippingGroup.clippingPlanes;
  36976. const l = srcClippingPlanes.length;
  36977. let dstClippingPlanes;
  36978. let offset;
  36979. if ( this.clipIntersection ) {
  36980. dstClippingPlanes = this.intersectionPlanes;
  36981. offset = parentContext.intersectionPlanes.length;
  36982. } else {
  36983. dstClippingPlanes = this.unionPlanes;
  36984. offset = parentContext.unionPlanes.length;
  36985. }
  36986. if ( dstClippingPlanes.length !== offset + l ) {
  36987. dstClippingPlanes.length = offset + l;
  36988. for ( let i = 0; i < l; i ++ ) {
  36989. dstClippingPlanes[ offset + i ] = new Vector4();
  36990. }
  36991. update = true;
  36992. }
  36993. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  36994. if ( update ) {
  36995. this.version ++;
  36996. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  36997. }
  36998. }
  36999. /**
  37000. * Returns a clipping context for the given clipping group.
  37001. *
  37002. * @param {ClippingGroup} clippingGroup - The clipping group.
  37003. * @return {ClippingContext} The clipping context.
  37004. */
  37005. getGroupContext( clippingGroup ) {
  37006. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  37007. let context = this.clippingGroupContexts.get( clippingGroup );
  37008. if ( context === undefined ) {
  37009. context = new ClippingContext( this );
  37010. this.clippingGroupContexts.set( clippingGroup, context );
  37011. }
  37012. context.update( this, clippingGroup );
  37013. return context;
  37014. }
  37015. /**
  37016. * The count of union clipping planes.
  37017. *
  37018. * @type {number}
  37019. * @readonly
  37020. */
  37021. get unionClippingCount() {
  37022. return this.unionPlanes.length;
  37023. }
  37024. }
  37025. /**
  37026. * This module is used to represent render bundles inside the renderer
  37027. * for further processing.
  37028. *
  37029. * @private
  37030. */
  37031. class RenderBundle {
  37032. /**
  37033. * Constructs a new bundle group.
  37034. *
  37035. * @param {BundleGroup} bundleGroup - The bundle group.
  37036. * @param {Camera} camera - The camera the bundle group is rendered with.
  37037. */
  37038. constructor( bundleGroup, camera ) {
  37039. this.bundleGroup = bundleGroup;
  37040. this.camera = camera;
  37041. }
  37042. }
  37043. const _chainKeys$1 = [];
  37044. /**
  37045. * This renderer module manages render bundles.
  37046. *
  37047. * @private
  37048. */
  37049. class RenderBundles {
  37050. /**
  37051. * Constructs a new render bundle management component.
  37052. */
  37053. constructor() {
  37054. /**
  37055. * A chain map for maintaining the render bundles.
  37056. *
  37057. * @type {ChainMap}
  37058. */
  37059. this.bundles = new ChainMap();
  37060. }
  37061. /**
  37062. * Returns a render bundle for the given bundle group and camera.
  37063. *
  37064. * @param {BundleGroup} bundleGroup - The bundle group.
  37065. * @param {Camera} camera - The camera the bundle group is rendered with.
  37066. * @return {RenderBundle} The render bundle.
  37067. */
  37068. get( bundleGroup, camera ) {
  37069. const bundles = this.bundles;
  37070. _chainKeys$1[ 0 ] = bundleGroup;
  37071. _chainKeys$1[ 1 ] = camera;
  37072. let bundle = bundles.get( _chainKeys$1 );
  37073. if ( bundle === undefined ) {
  37074. bundle = new RenderBundle( bundleGroup, camera );
  37075. bundles.set( _chainKeys$1, bundle );
  37076. }
  37077. _chainKeys$1.length = 0;
  37078. return bundle;
  37079. }
  37080. /**
  37081. * Frees all internal resources.
  37082. */
  37083. dispose() {
  37084. this.bundles = new ChainMap();
  37085. }
  37086. }
  37087. /**
  37088. * The purpose of a node library is to assign node implementations
  37089. * to existing library features. In `WebGPURenderer` lights, materials
  37090. * which are not based on `NodeMaterial` as well as tone mapping techniques
  37091. * are implemented with node-based modules.
  37092. *
  37093. * @private
  37094. */
  37095. class NodeLibrary {
  37096. /**
  37097. * Constructs a new node library.
  37098. */
  37099. constructor() {
  37100. /**
  37101. * A weak map that maps lights to light nodes.
  37102. *
  37103. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  37104. */
  37105. this.lightNodes = new WeakMap();
  37106. /**
  37107. * A map that maps materials to node materials.
  37108. *
  37109. * @type {Map<string,NodeMaterial.constructor>}
  37110. */
  37111. this.materialNodes = new Map();
  37112. /**
  37113. * A map that maps tone mapping techniques (constants)
  37114. * to tone mapping node functions.
  37115. *
  37116. * @type {Map<number,Function>}
  37117. */
  37118. this.toneMappingNodes = new Map();
  37119. }
  37120. /**
  37121. * Returns a matching node material instance for the given material object.
  37122. *
  37123. * This method also assigns/copies the properties of the given material object
  37124. * to the node material. This is done to make sure the current material
  37125. * configuration carries over to the node version.
  37126. *
  37127. * @param {Material} material - A material.
  37128. * @return {NodeMaterial} The corresponding node material.
  37129. */
  37130. fromMaterial( material ) {
  37131. if ( material.isNodeMaterial ) return material;
  37132. let nodeMaterial = null;
  37133. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  37134. if ( nodeMaterialClass !== null ) {
  37135. nodeMaterial = new nodeMaterialClass();
  37136. for ( const key in material ) {
  37137. nodeMaterial[ key ] = material[ key ];
  37138. }
  37139. }
  37140. return nodeMaterial;
  37141. }
  37142. /**
  37143. * Adds a tone mapping node function for a tone mapping technique (constant).
  37144. *
  37145. * @param {Function} toneMappingNode - The tone mapping node function.
  37146. * @param {number} toneMapping - The tone mapping.
  37147. */
  37148. addToneMapping( toneMappingNode, toneMapping ) {
  37149. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  37150. }
  37151. /**
  37152. * Returns a tone mapping node function for a tone mapping technique (constant).
  37153. *
  37154. * @param {number} toneMapping - The tone mapping.
  37155. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  37156. */
  37157. getToneMappingFunction( toneMapping ) {
  37158. return this.toneMappingNodes.get( toneMapping ) || null;
  37159. }
  37160. /**
  37161. * Returns a node material class definition for a material type.
  37162. *
  37163. * @param {string} materialType - The material type.
  37164. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  37165. */
  37166. getMaterialNodeClass( materialType ) {
  37167. return this.materialNodes.get( materialType ) || null;
  37168. }
  37169. /**
  37170. * Adds a node material class definition for a given material type.
  37171. *
  37172. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  37173. * @param {string} materialClassType - The material type.
  37174. */
  37175. addMaterial( materialNodeClass, materialClassType ) {
  37176. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  37177. }
  37178. /**
  37179. * Returns a light node class definition for a light class definition.
  37180. *
  37181. * @param {Light.constructor} light - The light class definition.
  37182. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  37183. */
  37184. getLightNodeClass( light ) {
  37185. return this.lightNodes.get( light ) || null;
  37186. }
  37187. /**
  37188. * Adds a light node class definition for a given light class definition.
  37189. *
  37190. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  37191. * @param {Light.constructor} lightClass - The light class definition.
  37192. */
  37193. addLight( lightNodeClass, lightClass ) {
  37194. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  37195. }
  37196. /**
  37197. * Adds a node class definition for the given type to the provided type library.
  37198. *
  37199. * @param {Node.constructor} nodeClass - The node class definition.
  37200. * @param {number|string} type - The object type.
  37201. * @param {Map<number|string,Node.constructor>} library - The type library.
  37202. */
  37203. addType( nodeClass, type, library ) {
  37204. if ( library.has( type ) ) {
  37205. console.warn( `Redefinition of node ${ type }` );
  37206. return;
  37207. }
  37208. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37209. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  37210. library.set( type, nodeClass );
  37211. }
  37212. /**
  37213. * Adds a node class definition for the given class definition to the provided type library.
  37214. *
  37215. * @param {Node.constructor} nodeClass - The node class definition.
  37216. * @param {Node.constructor} baseClass - The class definition.
  37217. * @param {WeakMap<Node.constructor, Node.constructor>} library - The type library.
  37218. */
  37219. addClass( nodeClass, baseClass, library ) {
  37220. if ( library.has( baseClass ) ) {
  37221. console.warn( `Redefinition of node ${ baseClass.name }` );
  37222. return;
  37223. }
  37224. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  37225. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  37226. library.set( baseClass, nodeClass );
  37227. }
  37228. }
  37229. const _defaultLights = /*@__PURE__*/ new LightsNode();
  37230. const _chainKeys = [];
  37231. /**
  37232. * This renderer module manages the lights nodes which are unique
  37233. * per scene and camera combination.
  37234. *
  37235. * The lights node itself is later configured in the render list
  37236. * with the actual lights from the scene.
  37237. *
  37238. * @private
  37239. * @augments ChainMap
  37240. */
  37241. class Lighting extends ChainMap {
  37242. /**
  37243. * Constructs a lighting management component.
  37244. */
  37245. constructor() {
  37246. super();
  37247. }
  37248. /**
  37249. * Creates a new lights node for the given array of lights.
  37250. *
  37251. * @param {Array<Light>} lights - The render object.
  37252. * @return {LightsNode} The lights node.
  37253. */
  37254. createNode( lights = [] ) {
  37255. return new LightsNode().setLights( lights );
  37256. }
  37257. /**
  37258. * Returns a lights node for the given scene and camera.
  37259. *
  37260. * @param {Scene} scene - The scene.
  37261. * @param {Camera} camera - The camera.
  37262. * @return {LightsNode} The lights node.
  37263. */
  37264. getNode( scene, camera ) {
  37265. // ignore post-processing
  37266. if ( scene.isQuadMesh ) return _defaultLights;
  37267. _chainKeys[ 0 ] = scene;
  37268. _chainKeys[ 1 ] = camera;
  37269. let node = this.get( _chainKeys );
  37270. if ( node === undefined ) {
  37271. node = this.createNode();
  37272. this.set( _chainKeys, node );
  37273. }
  37274. _chainKeys.length = 0;
  37275. return node;
  37276. }
  37277. }
  37278. /**
  37279. * A special type of render target that is used when rendering
  37280. * with the WebXR Device API.
  37281. *
  37282. * @private
  37283. * @augments RenderTarget
  37284. */
  37285. class XRRenderTarget extends RenderTarget {
  37286. /**
  37287. * Constructs a new XR render target.
  37288. *
  37289. * @param {number} [width=1] - The width of the render target.
  37290. * @param {number} [height=1] - The height of the render target.
  37291. * @param {Object} [options={}] - The configuration options.
  37292. */
  37293. constructor( width = 1, height = 1, options = {} ) {
  37294. super( width, height, options );
  37295. /**
  37296. * This flag can be used for type testing.
  37297. *
  37298. * @type {boolean}
  37299. * @readonly
  37300. * @default true
  37301. */
  37302. this.isXRRenderTarget = true;
  37303. /**
  37304. * Whether the attachments of the render target
  37305. * are defined by external textures. This flag is
  37306. * set to `true` when using the WebXR Layers API.
  37307. *
  37308. * @private
  37309. * @type {boolean}
  37310. * @default false
  37311. */
  37312. this._hasExternalTextures = false;
  37313. /**
  37314. * Whether a depth buffer should automatically be allocated
  37315. * for this XR render target or not.
  37316. *
  37317. * Allocating a depth buffer is the default behavior of XR render
  37318. * targets. However, when using the WebXR Layers API, this flag
  37319. * must be set to `false` when the `ignoreDepthValues` property of
  37320. * the projection layers evaluates to `false`.
  37321. *
  37322. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  37323. *
  37324. * @private
  37325. * @type {boolean}
  37326. * @default true
  37327. */
  37328. this._autoAllocateDepthBuffer = true;
  37329. /**
  37330. * Whether this render target is associated with a XRWebGLLayer.
  37331. *
  37332. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  37333. * this means that you don't have access to its bound color,
  37334. * stencil and depth buffers. We need to handle this framebuffer
  37335. * differently since its textures are always bound.
  37336. *
  37337. * @private
  37338. * @type {boolean}
  37339. * @default false
  37340. * */
  37341. this._isOpaqueFramebuffer = false;
  37342. }
  37343. copy( source ) {
  37344. super.copy( source );
  37345. this._hasExternalTextures = source._hasExternalTextures;
  37346. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  37347. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  37348. return this;
  37349. }
  37350. }
  37351. const _cameraLPos = /*@__PURE__*/ new Vector3();
  37352. const _cameraRPos = /*@__PURE__*/ new Vector3();
  37353. /**
  37354. * The XR manager is built on top of the WebXR Device API to
  37355. * manage XR sessions with `WebGPURenderer`.
  37356. *
  37357. * XR is currently only supported with a WebGL 2 backend.
  37358. *
  37359. * @augments EventDispatcher
  37360. */
  37361. class XRManager extends EventDispatcher {
  37362. /**
  37363. * Constructs a new XR manager.
  37364. *
  37365. * @param {Renderer} renderer - The renderer.
  37366. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  37367. */
  37368. constructor( renderer, multiview = false ) {
  37369. super();
  37370. /**
  37371. * This flag globally enables XR rendering.
  37372. *
  37373. * @type {boolean}
  37374. * @default false
  37375. */
  37376. this.enabled = false;
  37377. /**
  37378. * Whether the XR device is currently presenting or not.
  37379. *
  37380. * @type {boolean}
  37381. * @default false
  37382. * @readonly
  37383. */
  37384. this.isPresenting = false;
  37385. /**
  37386. * Whether the XR camera should automatically be updated or not.
  37387. *
  37388. * @type {boolean}
  37389. * @default true
  37390. */
  37391. this.cameraAutoUpdate = true;
  37392. /**
  37393. * The renderer.
  37394. *
  37395. * @private
  37396. * @type {Renderer}
  37397. */
  37398. this._renderer = renderer;
  37399. // camera
  37400. /**
  37401. * Represents the camera for the left eye.
  37402. *
  37403. * @private
  37404. * @type {PerspectiveCamera}
  37405. */
  37406. this._cameraL = new PerspectiveCamera();
  37407. this._cameraL.viewport = new Vector4();
  37408. /**
  37409. * Represents the camera for the right eye.
  37410. *
  37411. * @private
  37412. * @type {PerspectiveCamera}
  37413. */
  37414. this._cameraR = new PerspectiveCamera();
  37415. this._cameraR.viewport = new Vector4();
  37416. /**
  37417. * A list of cameras used for rendering the XR views.
  37418. *
  37419. * @private
  37420. * @type {Array<Camera>}
  37421. */
  37422. this._cameras = [ this._cameraL, this._cameraR ];
  37423. /**
  37424. * The main XR camera.
  37425. *
  37426. * @private
  37427. * @type {ArrayCamera}
  37428. */
  37429. this._cameraXR = new ArrayCamera();
  37430. /**
  37431. * The current near value of the XR camera.
  37432. *
  37433. * @private
  37434. * @type {?number}
  37435. * @default null
  37436. */
  37437. this._currentDepthNear = null;
  37438. /**
  37439. * The current far value of the XR camera.
  37440. *
  37441. * @private
  37442. * @type {?number}
  37443. * @default null
  37444. */
  37445. this._currentDepthFar = null;
  37446. /**
  37447. * A list of WebXR controllers requested by the application.
  37448. *
  37449. * @private
  37450. * @type {Array<WebXRController>}
  37451. */
  37452. this._controllers = [];
  37453. /**
  37454. * A list of XR input source. Each input source belongs to
  37455. * an instance of WebXRController.
  37456. *
  37457. * @private
  37458. * @type {Array<XRInputSource?>}
  37459. */
  37460. this._controllerInputSources = [];
  37461. /**
  37462. * The XR render target that represents the rendering destination
  37463. * during an active XR session.
  37464. *
  37465. * @private
  37466. * @type {?RenderTarget}
  37467. * @default null
  37468. */
  37469. this._xrRenderTarget = null;
  37470. /**
  37471. * An array holding all the non-projection layers
  37472. *
  37473. * @private
  37474. * @type {Array<Object>}
  37475. * @default []
  37476. */
  37477. this._layers = [];
  37478. /**
  37479. * Whether the XR session uses layers.
  37480. *
  37481. * @type {boolean}
  37482. * @default false
  37483. */
  37484. this._sessionUsesLayers = false;
  37485. /**
  37486. * Whether the device supports binding gl objects.
  37487. *
  37488. * @private
  37489. * @type {boolean}
  37490. * @readonly
  37491. */
  37492. this._supportsGlBinding = typeof XRWebGLBinding !== 'undefined';
  37493. this._frameBufferTargets = null;
  37494. /**
  37495. * Helper function to create native WebXR Layer.
  37496. *
  37497. * @private
  37498. * @type {Function}
  37499. */
  37500. this._createXRLayer = createXRLayer.bind( this );
  37501. /**
  37502. * The current WebGL context.
  37503. *
  37504. * @private
  37505. * @type {?WebGL2RenderingContext}
  37506. * @default null
  37507. */
  37508. this._gl = null;
  37509. /**
  37510. * The current animation context.
  37511. *
  37512. * @private
  37513. * @type {?Window}
  37514. * @default null
  37515. */
  37516. this._currentAnimationContext = null;
  37517. /**
  37518. * The current animation loop.
  37519. *
  37520. * @private
  37521. * @type {?Function}
  37522. * @default null
  37523. */
  37524. this._currentAnimationLoop = null;
  37525. /**
  37526. * The current pixel ratio.
  37527. *
  37528. * @private
  37529. * @type {?number}
  37530. * @default null
  37531. */
  37532. this._currentPixelRatio = null;
  37533. /**
  37534. * The current size of the renderer's canvas
  37535. * in logical pixel unit.
  37536. *
  37537. * @private
  37538. * @type {Vector2}
  37539. */
  37540. this._currentSize = new Vector2();
  37541. /**
  37542. * The default event listener for handling events inside a XR session.
  37543. *
  37544. * @private
  37545. * @type {Function}
  37546. */
  37547. this._onSessionEvent = onSessionEvent.bind( this );
  37548. /**
  37549. * The event listener for handling the end of a XR session.
  37550. *
  37551. * @private
  37552. * @type {Function}
  37553. */
  37554. this._onSessionEnd = onSessionEnd.bind( this );
  37555. /**
  37556. * The event listener for handling the `inputsourceschange` event.
  37557. *
  37558. * @private
  37559. * @type {Function}
  37560. */
  37561. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  37562. /**
  37563. * The animation loop which is used as a replacement for the default
  37564. * animation loop of the application. It is only used when a XR session
  37565. * is active.
  37566. *
  37567. * @private
  37568. * @type {Function}
  37569. */
  37570. this._onAnimationFrame = onAnimationFrame.bind( this );
  37571. /**
  37572. * The current XR reference space.
  37573. *
  37574. * @private
  37575. * @type {?XRReferenceSpace}
  37576. * @default null
  37577. */
  37578. this._referenceSpace = null;
  37579. /**
  37580. * The current XR reference space type.
  37581. *
  37582. * @private
  37583. * @type {XRReferenceSpaceType}
  37584. * @default 'local-floor'
  37585. */
  37586. this._referenceSpaceType = 'local-floor';
  37587. /**
  37588. * A custom reference space defined by the application.
  37589. *
  37590. * @private
  37591. * @type {?XRReferenceSpace}
  37592. * @default null
  37593. */
  37594. this._customReferenceSpace = null;
  37595. /**
  37596. * The framebuffer scale factor.
  37597. *
  37598. * @private
  37599. * @type {number}
  37600. * @default 1
  37601. */
  37602. this._framebufferScaleFactor = 1;
  37603. /**
  37604. * The foveation factor.
  37605. *
  37606. * @private
  37607. * @type {number}
  37608. * @default 1
  37609. */
  37610. this._foveation = 1.0;
  37611. /**
  37612. * A reference to the current XR session.
  37613. *
  37614. * @private
  37615. * @type {?XRSession}
  37616. * @default null
  37617. */
  37618. this._session = null;
  37619. /**
  37620. * A reference to the current XR base layer.
  37621. *
  37622. * @private
  37623. * @type {?XRWebGLLayer}
  37624. * @default null
  37625. */
  37626. this._glBaseLayer = null;
  37627. /**
  37628. * A reference to the current XR binding.
  37629. *
  37630. * @private
  37631. * @type {?XRWebGLBinding}
  37632. * @default null
  37633. */
  37634. this._glBinding = null;
  37635. /**
  37636. * A reference to the current XR projection layer.
  37637. *
  37638. * @private
  37639. * @type {?XRProjectionLayer}
  37640. * @default null
  37641. */
  37642. this._glProjLayer = null;
  37643. /**
  37644. * A reference to the current XR frame.
  37645. *
  37646. * @private
  37647. * @type {?XRFrame}
  37648. * @default null
  37649. */
  37650. this._xrFrame = null;
  37651. /**
  37652. * Whether the browser supports the APIs necessary to use XRProjectionLayers.
  37653. *
  37654. * Note: this does not represent XRSession explicitly requesting
  37655. * `'layers'` as a feature - see `_sessionUsesLayers` and #30112
  37656. *
  37657. * @private
  37658. * @type {boolean}
  37659. * @readonly
  37660. */
  37661. this._supportsLayers = ( this._supportsGlBinding && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  37662. /**
  37663. * Whether the usage of multiview has been requested by the application or not.
  37664. *
  37665. * @private
  37666. * @type {boolean}
  37667. * @default false
  37668. * @readonly
  37669. */
  37670. this._useMultiviewIfPossible = multiview;
  37671. /**
  37672. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  37673. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  37674. *
  37675. * @private
  37676. * @type {boolean}
  37677. * @readonly
  37678. */
  37679. this._useMultiview = false;
  37680. }
  37681. /**
  37682. * Returns an instance of `THREE.Group` that represents the transformation
  37683. * of a XR controller in target ray space. The requested controller is defined
  37684. * by the given index.
  37685. *
  37686. * @param {number} index - The index of the XR controller.
  37687. * @return {Group} A group that represents the controller's transformation.
  37688. */
  37689. getController( index ) {
  37690. const controller = this._getController( index );
  37691. return controller.getTargetRaySpace();
  37692. }
  37693. /**
  37694. * Returns an instance of `THREE.Group` that represents the transformation
  37695. * of a XR controller in grip space. The requested controller is defined
  37696. * by the given index.
  37697. *
  37698. * @param {number} index - The index of the XR controller.
  37699. * @return {Group} A group that represents the controller's transformation.
  37700. */
  37701. getControllerGrip( index ) {
  37702. const controller = this._getController( index );
  37703. return controller.getGripSpace();
  37704. }
  37705. /**
  37706. * Returns an instance of `THREE.Group` that represents the transformation
  37707. * of a XR controller in hand space. The requested controller is defined
  37708. * by the given index.
  37709. *
  37710. * @param {number} index - The index of the XR controller.
  37711. * @return {Group} A group that represents the controller's transformation.
  37712. */
  37713. getHand( index ) {
  37714. const controller = this._getController( index );
  37715. return controller.getHandSpace();
  37716. }
  37717. /**
  37718. * Returns the foveation value.
  37719. *
  37720. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  37721. */
  37722. getFoveation() {
  37723. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  37724. return undefined;
  37725. }
  37726. return this._foveation;
  37727. }
  37728. /**
  37729. * Sets the foveation value.
  37730. *
  37731. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  37732. * and `1` means maximum foveation (the edges render at lower resolution).
  37733. */
  37734. setFoveation( foveation ) {
  37735. this._foveation = foveation;
  37736. if ( this._glProjLayer !== null ) {
  37737. this._glProjLayer.fixedFoveation = foveation;
  37738. }
  37739. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  37740. this._glBaseLayer.fixedFoveation = foveation;
  37741. }
  37742. }
  37743. /**
  37744. * Returns the framebuffer scale factor.
  37745. *
  37746. * @return {number} The framebuffer scale factor.
  37747. */
  37748. getFramebufferScaleFactor() {
  37749. return this._framebufferScaleFactor;
  37750. }
  37751. /**
  37752. * Sets the framebuffer scale factor.
  37753. *
  37754. * This method can not be used during a XR session.
  37755. *
  37756. * @param {number} factor - The framebuffer scale factor.
  37757. */
  37758. setFramebufferScaleFactor( factor ) {
  37759. this._framebufferScaleFactor = factor;
  37760. if ( this.isPresenting === true ) {
  37761. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  37762. }
  37763. }
  37764. /**
  37765. * Returns the reference space type.
  37766. *
  37767. * @return {XRReferenceSpaceType} The reference space type.
  37768. */
  37769. getReferenceSpaceType() {
  37770. return this._referenceSpaceType;
  37771. }
  37772. /**
  37773. * Sets the reference space type.
  37774. *
  37775. * This method can not be used during a XR session.
  37776. *
  37777. * @param {XRReferenceSpaceType} type - The reference space type.
  37778. */
  37779. setReferenceSpaceType( type ) {
  37780. this._referenceSpaceType = type;
  37781. if ( this.isPresenting === true ) {
  37782. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  37783. }
  37784. }
  37785. /**
  37786. * Returns the XR reference space.
  37787. *
  37788. * @return {XRReferenceSpace} The XR reference space.
  37789. */
  37790. getReferenceSpace() {
  37791. return this._customReferenceSpace || this._referenceSpace;
  37792. }
  37793. /**
  37794. * Sets a custom XR reference space.
  37795. *
  37796. * @param {XRReferenceSpace} space - The XR reference space.
  37797. */
  37798. setReferenceSpace( space ) {
  37799. this._customReferenceSpace = space;
  37800. }
  37801. /**
  37802. * Returns the XR camera.
  37803. *
  37804. * @return {ArrayCamera} The XR camera.
  37805. */
  37806. getCamera() {
  37807. return this._cameraXR;
  37808. }
  37809. /**
  37810. * Returns the environment blend mode from the current XR session.
  37811. *
  37812. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  37813. */
  37814. getEnvironmentBlendMode() {
  37815. if ( this._session !== null ) {
  37816. return this._session.environmentBlendMode;
  37817. }
  37818. }
  37819. /**
  37820. * Returns the current XR binding.
  37821. *
  37822. * Creates a new binding if needed and the browser is
  37823. * capable of doing so.
  37824. *
  37825. * @return {?XRWebGLBinding} The XR binding. Returns `null` if one cannot be created.
  37826. */
  37827. getBinding() {
  37828. if ( this._glBinding === null && this._supportsGlBinding ) {
  37829. this._glBinding = new XRWebGLBinding( this._session, this._gl );
  37830. }
  37831. return this._glBinding;
  37832. }
  37833. /**
  37834. * Returns the current XR frame.
  37835. *
  37836. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  37837. */
  37838. getFrame() {
  37839. return this._xrFrame;
  37840. }
  37841. /**
  37842. * Returns `true` if the engine renders to a multiview target.
  37843. *
  37844. * @return {boolean} Whether the engine renders to a multiview render target or not.
  37845. */
  37846. useMultiview() {
  37847. return this._useMultiview;
  37848. }
  37849. /**
  37850. * This method can be used in XR applications to create a quadratic layer that presents a separate
  37851. * rendered scene.
  37852. *
  37853. * @param {number} width - The width of the layer plane in world units.
  37854. * @param {number} height - The height of the layer plane in world units.
  37855. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  37856. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  37857. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  37858. * @param {number} pixelheight - The height of the layer's render target in pixels.
  37859. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  37860. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  37861. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  37862. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  37863. */
  37864. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  37865. const geometry = new PlaneGeometry( width, height );
  37866. const renderTarget = new XRRenderTarget(
  37867. pixelwidth,
  37868. pixelheight,
  37869. {
  37870. format: RGBAFormat,
  37871. type: UnsignedByteType,
  37872. depthTexture: new DepthTexture(
  37873. pixelwidth,
  37874. pixelheight,
  37875. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  37876. undefined,
  37877. undefined,
  37878. undefined,
  37879. undefined,
  37880. undefined,
  37881. undefined,
  37882. attributes.stencil ? DepthStencilFormat : DepthFormat
  37883. ),
  37884. stencilBuffer: attributes.stencil,
  37885. resolveDepthBuffer: false,
  37886. resolveStencilBuffer: false
  37887. } );
  37888. renderTarget._autoAllocateDepthBuffer = true;
  37889. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  37890. material.map = renderTarget.texture;
  37891. material.map.offset.y = 1;
  37892. material.map.repeat.y = -1;
  37893. const plane = new Mesh( geometry, material );
  37894. plane.position.copy( translation );
  37895. plane.quaternion.copy( quaternion );
  37896. const layer = {
  37897. type: 'quad',
  37898. width: width,
  37899. height: height,
  37900. translation: translation,
  37901. quaternion: quaternion,
  37902. pixelwidth: pixelwidth,
  37903. pixelheight: pixelheight,
  37904. plane: plane,
  37905. material: material,
  37906. rendercall: rendercall,
  37907. renderTarget: renderTarget };
  37908. this._layers.push( layer );
  37909. if ( this._session !== null ) {
  37910. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  37911. layer.plane.material.blending = CustomBlending;
  37912. layer.plane.material.blendEquation = AddEquation;
  37913. layer.plane.material.blendSrc = ZeroFactor;
  37914. layer.plane.material.blendDst = ZeroFactor;
  37915. layer.xrlayer = this._createXRLayer( layer );
  37916. const xrlayers = this._session.renderState.layers;
  37917. xrlayers.unshift( layer.xrlayer );
  37918. this._session.updateRenderState( { layers: xrlayers } );
  37919. } else {
  37920. renderTarget.isXRRenderTarget = false;
  37921. }
  37922. return plane;
  37923. }
  37924. /**
  37925. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  37926. * rendered scene.
  37927. *
  37928. * @param {number} radius - The radius of the cylinder in world units.
  37929. * @param {number} centralAngle - The central angle of the cylinder in radians.
  37930. * @param {number} aspectratio - The aspect ratio.
  37931. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  37932. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  37933. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  37934. * @param {number} pixelheight - The height of the layer's render target in pixels.
  37935. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  37936. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  37937. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  37938. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  37939. */
  37940. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  37941. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  37942. const renderTarget = new XRRenderTarget(
  37943. pixelwidth,
  37944. pixelheight,
  37945. {
  37946. format: RGBAFormat,
  37947. type: UnsignedByteType,
  37948. depthTexture: new DepthTexture(
  37949. pixelwidth,
  37950. pixelheight,
  37951. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  37952. undefined,
  37953. undefined,
  37954. undefined,
  37955. undefined,
  37956. undefined,
  37957. undefined,
  37958. attributes.stencil ? DepthStencilFormat : DepthFormat
  37959. ),
  37960. stencilBuffer: attributes.stencil,
  37961. resolveDepthBuffer: false,
  37962. resolveStencilBuffer: false
  37963. } );
  37964. renderTarget._autoAllocateDepthBuffer = true;
  37965. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  37966. material.map = renderTarget.texture;
  37967. material.map.offset.y = 1;
  37968. material.map.repeat.y = -1;
  37969. const plane = new Mesh( geometry, material );
  37970. plane.position.copy( translation );
  37971. plane.quaternion.copy( quaternion );
  37972. const layer = {
  37973. type: 'cylinder',
  37974. radius: radius,
  37975. centralAngle: centralAngle,
  37976. aspectratio: aspectratio,
  37977. translation: translation,
  37978. quaternion: quaternion,
  37979. pixelwidth: pixelwidth,
  37980. pixelheight: pixelheight,
  37981. plane: plane,
  37982. material: material,
  37983. rendercall: rendercall,
  37984. renderTarget: renderTarget };
  37985. this._layers.push( layer );
  37986. if ( this._session !== null ) {
  37987. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  37988. layer.plane.material.blending = CustomBlending;
  37989. layer.plane.material.blendEquation = AddEquation;
  37990. layer.plane.material.blendSrc = ZeroFactor;
  37991. layer.plane.material.blendDst = ZeroFactor;
  37992. layer.xrlayer = this._createXRLayer( layer );
  37993. const xrlayers = this._session.renderState.layers;
  37994. xrlayers.unshift( layer.xrlayer );
  37995. this._session.updateRenderState( { layers: xrlayers } );
  37996. } else {
  37997. renderTarget.isXRRenderTarget = false;
  37998. }
  37999. return plane;
  38000. }
  38001. /**
  38002. * Renders the XR layers that have been previously added to the scene.
  38003. *
  38004. * This method is usually called in your animation loop before rendering
  38005. * the actual scene via `renderer.render( scene, camera );`.
  38006. */
  38007. renderLayers( ) {
  38008. const translationObject = new Vector3();
  38009. const quaternionObject = new Quaternion();
  38010. const renderer = this._renderer;
  38011. const wasPresenting = this.isPresenting;
  38012. const rendererOutputTarget = renderer.getOutputRenderTarget();
  38013. const rendererFramebufferTarget = renderer._frameBufferTarget;
  38014. this.isPresenting = false;
  38015. const rendererSize = new Vector2();
  38016. renderer.getSize( rendererSize );
  38017. const rendererQuad = renderer._quad;
  38018. for ( const layer of this._layers ) {
  38019. layer.renderTarget.isXRRenderTarget = this._session !== null;
  38020. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  38021. if ( layer.renderTarget.isXRRenderTarget && this._sessionUsesLayers ) {
  38022. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  38023. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  38024. renderer.backend.setXRRenderTargetTextures(
  38025. layer.renderTarget,
  38026. glSubImage.colorTexture,
  38027. undefined );
  38028. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  38029. renderer.setOutputRenderTarget( layer.renderTarget );
  38030. renderer.setRenderTarget( null );
  38031. renderer._frameBufferTarget = null;
  38032. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  38033. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  38034. if ( ! frameBufferTarget ) {
  38035. renderer._quad = new QuadMesh( new NodeMaterial() );
  38036. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  38037. } else {
  38038. renderer._frameBufferTarget = frameBufferTarget;
  38039. renderer._quad = quad;
  38040. }
  38041. layer.rendercall();
  38042. renderer._frameBufferTarget = null;
  38043. } else {
  38044. renderer.setRenderTarget( layer.renderTarget );
  38045. layer.rendercall();
  38046. }
  38047. }
  38048. renderer.setRenderTarget( null );
  38049. renderer.setOutputRenderTarget( rendererOutputTarget );
  38050. renderer._frameBufferTarget = rendererFramebufferTarget;
  38051. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  38052. renderer._quad = rendererQuad;
  38053. this.isPresenting = wasPresenting;
  38054. }
  38055. /**
  38056. * Returns the current XR session.
  38057. *
  38058. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  38059. */
  38060. getSession() {
  38061. return this._session;
  38062. }
  38063. /**
  38064. * After a XR session has been requested usually with one of the `*Button` modules, it
  38065. * is injected into the renderer with this method. This method triggers the start of
  38066. * the actual XR rendering.
  38067. *
  38068. * @async
  38069. * @param {XRSession} session - The XR session to set.
  38070. * @return {Promise} A Promise that resolves when the session has been set.
  38071. */
  38072. async setSession( session ) {
  38073. const renderer = this._renderer;
  38074. const backend = renderer.backend;
  38075. this._gl = renderer.getContext();
  38076. const gl = this._gl;
  38077. const attributes = gl.getContextAttributes();
  38078. this._session = session;
  38079. if ( session !== null ) {
  38080. 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.' );
  38081. session.addEventListener( 'select', this._onSessionEvent );
  38082. session.addEventListener( 'selectstart', this._onSessionEvent );
  38083. session.addEventListener( 'selectend', this._onSessionEvent );
  38084. session.addEventListener( 'squeeze', this._onSessionEvent );
  38085. session.addEventListener( 'squeezestart', this._onSessionEvent );
  38086. session.addEventListener( 'squeezeend', this._onSessionEvent );
  38087. session.addEventListener( 'end', this._onSessionEnd );
  38088. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  38089. await backend.makeXRCompatible();
  38090. this._currentPixelRatio = renderer.getPixelRatio();
  38091. renderer.getSize( this._currentSize );
  38092. this._currentAnimationContext = renderer._animation.getContext();
  38093. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  38094. renderer._animation.stop();
  38095. //
  38096. if ( this._supportsLayers === true ) {
  38097. // default path using XRProjectionLayer
  38098. let depthFormat = null;
  38099. let depthType = null;
  38100. let glDepthFormat = null;
  38101. if ( renderer.depth ) {
  38102. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  38103. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  38104. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  38105. }
  38106. const projectionlayerInit = {
  38107. colorFormat: gl.RGBA8,
  38108. depthFormat: glDepthFormat,
  38109. scaleFactor: this._framebufferScaleFactor,
  38110. clearOnAccess: false
  38111. };
  38112. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  38113. projectionlayerInit.textureType = 'texture-array';
  38114. this._useMultiview = true;
  38115. }
  38116. this._glBinding = this.getBinding();
  38117. const glProjLayer = this._glBinding.createProjectionLayer( projectionlayerInit );
  38118. const layersArray = [ glProjLayer ];
  38119. this._glProjLayer = glProjLayer;
  38120. renderer.setPixelRatio( 1 );
  38121. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  38122. const depth = this._useMultiview ? 2 : 1;
  38123. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  38124. this._xrRenderTarget = new XRRenderTarget(
  38125. glProjLayer.textureWidth,
  38126. glProjLayer.textureHeight,
  38127. {
  38128. format: RGBAFormat,
  38129. type: UnsignedByteType,
  38130. colorSpace: renderer.outputColorSpace,
  38131. depthTexture: depthTexture,
  38132. stencilBuffer: renderer.stencil,
  38133. samples: attributes.antialias ? 4 : 0,
  38134. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  38135. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  38136. depth: this._useMultiview ? 2 : 1,
  38137. multiview: this._useMultiview
  38138. } );
  38139. this._xrRenderTarget._hasExternalTextures = true;
  38140. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  38141. this._sessionUsesLayers = session.enabledFeatures.includes( 'layers' );
  38142. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  38143. if ( this._sessionUsesLayers ) {
  38144. // switch layers to native
  38145. for ( const layer of this._layers ) {
  38146. // change material so it "punches" out a hole to show the XR Layer.
  38147. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  38148. layer.plane.material.blending = CustomBlending;
  38149. layer.plane.material.blendEquation = AddEquation;
  38150. layer.plane.material.blendSrc = ZeroFactor;
  38151. layer.plane.material.blendDst = ZeroFactor;
  38152. layer.xrlayer = this._createXRLayer( layer );
  38153. layersArray.unshift( layer.xrlayer );
  38154. }
  38155. }
  38156. session.updateRenderState( { layers: layersArray } );
  38157. } else {
  38158. // fallback to XRWebGLLayer
  38159. const layerInit = {
  38160. antialias: renderer.samples > 0,
  38161. alpha: true,
  38162. depth: renderer.depth,
  38163. stencil: renderer.stencil,
  38164. framebufferScaleFactor: this.getFramebufferScaleFactor()
  38165. };
  38166. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  38167. this._glBaseLayer = glBaseLayer;
  38168. session.updateRenderState( { baseLayer: glBaseLayer } );
  38169. renderer.setPixelRatio( 1 );
  38170. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  38171. this._xrRenderTarget = new XRRenderTarget(
  38172. glBaseLayer.framebufferWidth,
  38173. glBaseLayer.framebufferHeight,
  38174. {
  38175. format: RGBAFormat,
  38176. type: UnsignedByteType,
  38177. colorSpace: renderer.outputColorSpace,
  38178. stencilBuffer: renderer.stencil,
  38179. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  38180. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  38181. }
  38182. );
  38183. this._xrRenderTarget._isOpaqueFramebuffer = true;
  38184. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  38185. }
  38186. //
  38187. this.setFoveation( this.getFoveation() );
  38188. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  38189. renderer._animation.setContext( session );
  38190. renderer._animation.start();
  38191. this.isPresenting = true;
  38192. this.dispatchEvent( { type: 'sessionstart' } );
  38193. }
  38194. }
  38195. /**
  38196. * This method is called by the renderer per frame and updates the XR camera
  38197. * and it sub cameras based on the given camera. The given camera is the "user"
  38198. * camera created on application level and used for non-XR rendering.
  38199. *
  38200. * @param {PerspectiveCamera} camera - The camera.
  38201. */
  38202. updateCamera( camera ) {
  38203. const session = this._session;
  38204. if ( session === null ) return;
  38205. const depthNear = camera.near;
  38206. const depthFar = camera.far;
  38207. const cameraXR = this._cameraXR;
  38208. const cameraL = this._cameraL;
  38209. const cameraR = this._cameraR;
  38210. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  38211. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  38212. cameraXR.isMultiViewCamera = this._useMultiview;
  38213. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  38214. // Note that the new renderState won't apply until the next frame. See #18320
  38215. session.updateRenderState( {
  38216. depthNear: cameraXR.near,
  38217. depthFar: cameraXR.far
  38218. } );
  38219. this._currentDepthNear = cameraXR.near;
  38220. this._currentDepthFar = cameraXR.far;
  38221. }
  38222. // inherit camera layers and enable eye layers (1 = left, 2 = right)
  38223. cameraXR.layers.mask = camera.layers.mask | 0b110;
  38224. cameraL.layers.mask = cameraXR.layers.mask & 0b011;
  38225. cameraR.layers.mask = cameraXR.layers.mask & 0b101;
  38226. const parent = camera.parent;
  38227. const cameras = cameraXR.cameras;
  38228. updateCamera( cameraXR, parent );
  38229. for ( let i = 0; i < cameras.length; i ++ ) {
  38230. updateCamera( cameras[ i ], parent );
  38231. }
  38232. // update projection matrix for proper view frustum culling
  38233. if ( cameras.length === 2 ) {
  38234. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  38235. } else {
  38236. // assume single camera setup (AR)
  38237. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  38238. }
  38239. // update user camera and its children
  38240. updateUserCamera( camera, cameraXR, parent );
  38241. }
  38242. /**
  38243. * Returns a WebXR controller for the given controller index.
  38244. *
  38245. * @private
  38246. * @param {number} index - The controller index.
  38247. * @return {WebXRController} The XR controller.
  38248. */
  38249. _getController( index ) {
  38250. let controller = this._controllers[ index ];
  38251. if ( controller === undefined ) {
  38252. controller = new WebXRController();
  38253. this._controllers[ index ] = controller;
  38254. }
  38255. return controller;
  38256. }
  38257. }
  38258. /**
  38259. * Assumes 2 cameras that are parallel and share an X-axis, and that
  38260. * the cameras' projection and world matrices have already been set.
  38261. * And that near and far planes are identical for both cameras.
  38262. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  38263. *
  38264. * @param {ArrayCamera} camera - The camera to update.
  38265. * @param {PerspectiveCamera} cameraL - The left camera.
  38266. * @param {PerspectiveCamera} cameraR - The right camera.
  38267. */
  38268. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  38269. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  38270. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  38271. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  38272. const projL = cameraL.projectionMatrix.elements;
  38273. const projR = cameraR.projectionMatrix.elements;
  38274. // VR systems will have identical far and near planes, and
  38275. // most likely identical top and bottom frustum extents.
  38276. // Use the left camera for these values.
  38277. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  38278. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  38279. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  38280. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  38281. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  38282. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  38283. const left = near * leftFov;
  38284. const right = near * rightFov;
  38285. // Calculate the new camera's position offset from the
  38286. // left camera. xOffset should be roughly half `ipd`.
  38287. const zOffset = ipd / ( - leftFov + rightFov );
  38288. const xOffset = zOffset * - leftFov;
  38289. // TODO: Better way to apply this offset?
  38290. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  38291. camera.translateX( xOffset );
  38292. camera.translateZ( zOffset );
  38293. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  38294. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  38295. // Check if the projection uses an infinite far plane.
  38296. if ( projL[ 10 ] === -1 ) {
  38297. // Use the projection matrix from the left eye.
  38298. // The camera offset is sufficient to include the view volumes
  38299. // of both eyes (assuming symmetric projections).
  38300. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  38301. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  38302. } else {
  38303. // Find the union of the frustum values of the cameras and scale
  38304. // the values so that the near plane's position does not change in world space,
  38305. // although must now be relative to the new union camera.
  38306. const near2 = near + zOffset;
  38307. const far2 = far + zOffset;
  38308. const left2 = left - xOffset;
  38309. const right2 = right + ( ipd - xOffset );
  38310. const top2 = topFov * far / far2 * near2;
  38311. const bottom2 = bottomFov * far / far2 * near2;
  38312. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  38313. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  38314. }
  38315. }
  38316. /**
  38317. * Updates the world matrices for the given camera based on the parent 3D object.
  38318. *
  38319. * @inner
  38320. * @param {Camera} camera - The camera to update.
  38321. * @param {Object3D} parent - The parent 3D object.
  38322. */
  38323. function updateCamera( camera, parent ) {
  38324. if ( parent === null ) {
  38325. camera.matrixWorld.copy( camera.matrix );
  38326. } else {
  38327. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  38328. }
  38329. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  38330. }
  38331. /**
  38332. * Updates the given camera with the transformation of the XR camera and parent object.
  38333. *
  38334. * @inner
  38335. * @param {Camera} camera - The camera to update.
  38336. * @param {ArrayCamera} cameraXR - The XR camera.
  38337. * @param {Object3D} parent - The parent 3D object.
  38338. */
  38339. function updateUserCamera( camera, cameraXR, parent ) {
  38340. if ( parent === null ) {
  38341. camera.matrix.copy( cameraXR.matrixWorld );
  38342. } else {
  38343. camera.matrix.copy( parent.matrixWorld );
  38344. camera.matrix.invert();
  38345. camera.matrix.multiply( cameraXR.matrixWorld );
  38346. }
  38347. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  38348. camera.updateMatrixWorld( true );
  38349. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  38350. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  38351. if ( camera.isPerspectiveCamera ) {
  38352. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  38353. camera.zoom = 1;
  38354. }
  38355. }
  38356. function onSessionEvent( event ) {
  38357. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  38358. if ( controllerIndex === -1 ) {
  38359. return;
  38360. }
  38361. const controller = this._controllers[ controllerIndex ];
  38362. if ( controller !== undefined ) {
  38363. const referenceSpace = this.getReferenceSpace();
  38364. controller.update( event.inputSource, event.frame, referenceSpace );
  38365. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  38366. }
  38367. }
  38368. function onSessionEnd() {
  38369. const session = this._session;
  38370. const renderer = this._renderer;
  38371. session.removeEventListener( 'select', this._onSessionEvent );
  38372. session.removeEventListener( 'selectstart', this._onSessionEvent );
  38373. session.removeEventListener( 'selectend', this._onSessionEvent );
  38374. session.removeEventListener( 'squeeze', this._onSessionEvent );
  38375. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  38376. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  38377. session.removeEventListener( 'end', this._onSessionEnd );
  38378. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  38379. for ( let i = 0; i < this._controllers.length; i ++ ) {
  38380. const inputSource = this._controllerInputSources[ i ];
  38381. if ( inputSource === null ) continue;
  38382. this._controllerInputSources[ i ] = null;
  38383. this._controllers[ i ].disconnect( inputSource );
  38384. }
  38385. this._currentDepthNear = null;
  38386. this._currentDepthFar = null;
  38387. // restore framebuffer/rendering state
  38388. renderer._resetXRState();
  38389. this._session = null;
  38390. this._xrRenderTarget = null;
  38391. // switch layers back to emulated
  38392. if ( this._sessionUsesLayers === true ) {
  38393. for ( const layer of this._layers ) {
  38394. // Recreate layer render target to reset state
  38395. layer.renderTarget = new XRRenderTarget(
  38396. layer.pixelwidth,
  38397. layer.pixelheight,
  38398. {
  38399. format: RGBAFormat,
  38400. type: UnsignedByteType,
  38401. depthTexture: new DepthTexture(
  38402. layer.pixelwidth,
  38403. layer.pixelheight,
  38404. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  38405. undefined,
  38406. undefined,
  38407. undefined,
  38408. undefined,
  38409. undefined,
  38410. undefined,
  38411. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  38412. ),
  38413. stencilBuffer: layer.stencilBuffer,
  38414. resolveDepthBuffer: false,
  38415. resolveStencilBuffer: false
  38416. } );
  38417. layer.renderTarget.isXRRenderTarget = false;
  38418. layer.plane.material = layer.material;
  38419. layer.material.map = layer.renderTarget.texture;
  38420. layer.material.map.offset.y = 1;
  38421. layer.material.map.repeat.y = -1;
  38422. delete layer.xrlayer;
  38423. }
  38424. }
  38425. //
  38426. this.isPresenting = false;
  38427. this._useMultiview = false;
  38428. renderer._animation.stop();
  38429. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  38430. renderer._animation.setContext( this._currentAnimationContext );
  38431. renderer._animation.start();
  38432. renderer.setPixelRatio( this._currentPixelRatio );
  38433. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  38434. this.dispatchEvent( { type: 'sessionend' } );
  38435. }
  38436. function onInputSourcesChange( event ) {
  38437. const controllers = this._controllers;
  38438. const controllerInputSources = this._controllerInputSources;
  38439. // Notify disconnected
  38440. for ( let i = 0; i < event.removed.length; i ++ ) {
  38441. const inputSource = event.removed[ i ];
  38442. const index = controllerInputSources.indexOf( inputSource );
  38443. if ( index >= 0 ) {
  38444. controllerInputSources[ index ] = null;
  38445. controllers[ index ].disconnect( inputSource );
  38446. }
  38447. }
  38448. // Notify connected
  38449. for ( let i = 0; i < event.added.length; i ++ ) {
  38450. const inputSource = event.added[ i ];
  38451. let controllerIndex = controllerInputSources.indexOf( inputSource );
  38452. if ( controllerIndex === -1 ) {
  38453. // Assign input source a controller that currently has no input source
  38454. for ( let i = 0; i < controllers.length; i ++ ) {
  38455. if ( i >= controllerInputSources.length ) {
  38456. controllerInputSources.push( inputSource );
  38457. controllerIndex = i;
  38458. break;
  38459. } else if ( controllerInputSources[ i ] === null ) {
  38460. controllerInputSources[ i ] = inputSource;
  38461. controllerIndex = i;
  38462. break;
  38463. }
  38464. }
  38465. // If all controllers do currently receive input we ignore new ones
  38466. if ( controllerIndex === -1 ) break;
  38467. }
  38468. const controller = controllers[ controllerIndex ];
  38469. if ( controller ) {
  38470. controller.connect( inputSource );
  38471. }
  38472. }
  38473. }
  38474. // Creation method for native WebXR layers
  38475. function createXRLayer( layer ) {
  38476. if ( layer.type === 'quad' ) {
  38477. return this._glBinding.createQuadLayer( {
  38478. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  38479. width: layer.width / 2,
  38480. height: layer.height / 2,
  38481. space: this._referenceSpace,
  38482. viewPixelWidth: layer.pixelwidth,
  38483. viewPixelHeight: layer.pixelheight,
  38484. clearOnAccess: false
  38485. } );
  38486. } else {
  38487. return this._glBinding.createCylinderLayer( {
  38488. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  38489. radius: layer.radius,
  38490. centralAngle: layer.centralAngle,
  38491. aspectRatio: layer.aspectRatio,
  38492. space: this._referenceSpace,
  38493. viewPixelWidth: layer.pixelwidth,
  38494. viewPixelHeight: layer.pixelheight,
  38495. clearOnAccess: false
  38496. } );
  38497. }
  38498. }
  38499. // Animation Loop
  38500. function onAnimationFrame( time, frame ) {
  38501. if ( frame === undefined ) return;
  38502. const cameraXR = this._cameraXR;
  38503. const renderer = this._renderer;
  38504. const backend = renderer.backend;
  38505. const glBaseLayer = this._glBaseLayer;
  38506. const referenceSpace = this.getReferenceSpace();
  38507. const pose = frame.getViewerPose( referenceSpace );
  38508. this._xrFrame = frame;
  38509. if ( pose !== null ) {
  38510. const views = pose.views;
  38511. if ( this._glBaseLayer !== null ) {
  38512. backend.setXRTarget( glBaseLayer.framebuffer );
  38513. }
  38514. let cameraXRNeedsUpdate = false;
  38515. // check if it's necessary to rebuild cameraXR's camera list
  38516. if ( views.length !== cameraXR.cameras.length ) {
  38517. cameraXR.cameras.length = 0;
  38518. cameraXRNeedsUpdate = true;
  38519. }
  38520. for ( let i = 0; i < views.length; i ++ ) {
  38521. const view = views[ i ];
  38522. let viewport;
  38523. if ( this._supportsLayers === true ) {
  38524. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  38525. viewport = glSubImage.viewport;
  38526. // For side-by-side projection, we only produce a single texture for both eyes.
  38527. if ( i === 0 ) {
  38528. backend.setXRRenderTargetTextures(
  38529. this._xrRenderTarget,
  38530. glSubImage.colorTexture,
  38531. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  38532. );
  38533. }
  38534. } else {
  38535. viewport = glBaseLayer.getViewport( view );
  38536. }
  38537. let camera = this._cameras[ i ];
  38538. if ( camera === undefined ) {
  38539. camera = new PerspectiveCamera();
  38540. camera.layers.enable( i );
  38541. camera.viewport = new Vector4();
  38542. this._cameras[ i ] = camera;
  38543. }
  38544. camera.matrix.fromArray( view.transform.matrix );
  38545. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  38546. camera.projectionMatrix.fromArray( view.projectionMatrix );
  38547. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  38548. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  38549. if ( i === 0 ) {
  38550. cameraXR.matrix.copy( camera.matrix );
  38551. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  38552. }
  38553. if ( cameraXRNeedsUpdate === true ) {
  38554. cameraXR.cameras.push( camera );
  38555. }
  38556. }
  38557. renderer.setOutputRenderTarget( this._xrRenderTarget );
  38558. }
  38559. //
  38560. for ( let i = 0; i < this._controllers.length; i ++ ) {
  38561. const inputSource = this._controllerInputSources[ i ];
  38562. const controller = this._controllers[ i ];
  38563. if ( inputSource !== null && controller !== undefined ) {
  38564. controller.update( inputSource, frame, referenceSpace );
  38565. }
  38566. }
  38567. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  38568. if ( frame.detectedPlanes ) {
  38569. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  38570. }
  38571. this._xrFrame = null;
  38572. }
  38573. const _scene = /*@__PURE__*/ new Scene();
  38574. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  38575. const _screen = /*@__PURE__*/ new Vector4();
  38576. const _frustum = /*@__PURE__*/ new Frustum();
  38577. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  38578. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  38579. const _vector4 = /*@__PURE__*/ new Vector4();
  38580. /**
  38581. * Base class for renderers.
  38582. */
  38583. class Renderer {
  38584. /**
  38585. * Renderer options.
  38586. *
  38587. * @typedef {Object} Renderer~Options
  38588. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  38589. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  38590. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  38591. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  38592. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  38593. * @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
  38594. * to overwrite the default.
  38595. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  38596. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  38597. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  38598. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  38599. */
  38600. /**
  38601. * Constructs a new renderer.
  38602. *
  38603. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  38604. * @param {Renderer~Options} [parameters] - The configuration parameter.
  38605. */
  38606. constructor( backend, parameters = {} ) {
  38607. /**
  38608. * This flag can be used for type testing.
  38609. *
  38610. * @type {boolean}
  38611. * @readonly
  38612. * @default true
  38613. */
  38614. this.isRenderer = true;
  38615. //
  38616. const {
  38617. logarithmicDepthBuffer = false,
  38618. alpha = true,
  38619. depth = true,
  38620. stencil = false,
  38621. antialias = false,
  38622. samples = 0,
  38623. getFallback = null,
  38624. colorBufferType = HalfFloatType,
  38625. multiview = false
  38626. } = parameters;
  38627. /**
  38628. * A reference to the canvas element the renderer is drawing to.
  38629. * This value of this property will automatically be created by
  38630. * the renderer.
  38631. *
  38632. * @type {HTMLCanvasElement|OffscreenCanvas}
  38633. */
  38634. this.domElement = backend.getDomElement();
  38635. /**
  38636. * A reference to the current backend.
  38637. *
  38638. * @type {Backend}
  38639. */
  38640. this.backend = backend;
  38641. /**
  38642. * The number of MSAA samples.
  38643. *
  38644. * @type {number}
  38645. * @default 0
  38646. */
  38647. this.samples = samples || ( antialias === true ) ? 4 : 0;
  38648. /**
  38649. * Whether the renderer should automatically clear the current rendering target
  38650. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  38651. * or the current bound render target (custom framebuffer).
  38652. *
  38653. * @type {boolean}
  38654. * @default true
  38655. */
  38656. this.autoClear = true;
  38657. /**
  38658. * When `autoClear` is set to `true`, this property defines whether the renderer
  38659. * should clear the color buffer.
  38660. *
  38661. * @type {boolean}
  38662. * @default true
  38663. */
  38664. this.autoClearColor = true;
  38665. /**
  38666. * When `autoClear` is set to `true`, this property defines whether the renderer
  38667. * should clear the depth buffer.
  38668. *
  38669. * @type {boolean}
  38670. * @default true
  38671. */
  38672. this.autoClearDepth = true;
  38673. /**
  38674. * When `autoClear` is set to `true`, this property defines whether the renderer
  38675. * should clear the stencil buffer.
  38676. *
  38677. * @type {boolean}
  38678. * @default true
  38679. */
  38680. this.autoClearStencil = true;
  38681. /**
  38682. * Whether the default framebuffer should be transparent or opaque.
  38683. *
  38684. * @type {boolean}
  38685. * @default true
  38686. */
  38687. this.alpha = alpha;
  38688. /**
  38689. * Whether logarithmic depth buffer is enabled or not.
  38690. *
  38691. * @type {boolean}
  38692. * @default false
  38693. */
  38694. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  38695. /**
  38696. * Defines the output color space of the renderer.
  38697. *
  38698. * @type {string}
  38699. * @default SRGBColorSpace
  38700. */
  38701. this.outputColorSpace = SRGBColorSpace;
  38702. /**
  38703. * Defines the tone mapping of the renderer.
  38704. *
  38705. * @type {number}
  38706. * @default NoToneMapping
  38707. */
  38708. this.toneMapping = NoToneMapping;
  38709. /**
  38710. * Defines the tone mapping exposure.
  38711. *
  38712. * @type {number}
  38713. * @default 1
  38714. */
  38715. this.toneMappingExposure = 1.0;
  38716. /**
  38717. * Whether the renderer should sort its render lists or not.
  38718. *
  38719. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  38720. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  38721. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  38722. * e.g. manually determining each object's rendering order.
  38723. *
  38724. * @type {boolean}
  38725. * @default true
  38726. */
  38727. this.sortObjects = true;
  38728. /**
  38729. * Whether the default framebuffer should have a depth buffer or not.
  38730. *
  38731. * @type {boolean}
  38732. * @default true
  38733. */
  38734. this.depth = depth;
  38735. /**
  38736. * Whether the default framebuffer should have a stencil buffer or not.
  38737. *
  38738. * @type {boolean}
  38739. * @default false
  38740. */
  38741. this.stencil = stencil;
  38742. /**
  38743. * Holds a series of statistical information about the GPU memory
  38744. * and the rendering process. Useful for debugging and monitoring.
  38745. *
  38746. * @type {Info}
  38747. */
  38748. this.info = new Info();
  38749. /**
  38750. * Stores override nodes for specific transformations or calculations.
  38751. * These nodes can be used to replace default behavior in the rendering pipeline.
  38752. *
  38753. * @type {Object}
  38754. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  38755. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  38756. */
  38757. this.overrideNodes = {
  38758. modelViewMatrix: null,
  38759. modelNormalViewMatrix: null
  38760. };
  38761. /**
  38762. * The node library defines how certain library objects like materials, lights
  38763. * or tone mapping functions are mapped to node types. This is required since
  38764. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  38765. * be part of the scene graph, they are internally represented as nodes for
  38766. * further processing.
  38767. *
  38768. * @type {NodeLibrary}
  38769. */
  38770. this.library = new NodeLibrary();
  38771. /**
  38772. * A map-like data structure for managing lights.
  38773. *
  38774. * @type {Lighting}
  38775. */
  38776. this.lighting = new Lighting();
  38777. // internals
  38778. /**
  38779. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  38780. *
  38781. * @private
  38782. * @type {?Function}
  38783. */
  38784. this._getFallback = getFallback;
  38785. /**
  38786. * The renderer's pixel ratio.
  38787. *
  38788. * @private
  38789. * @type {number}
  38790. * @default 1
  38791. */
  38792. this._pixelRatio = 1;
  38793. /**
  38794. * The width of the renderer's default framebuffer in logical pixel unit.
  38795. *
  38796. * @private
  38797. * @type {number}
  38798. */
  38799. this._width = this.domElement.width;
  38800. /**
  38801. * The height of the renderer's default framebuffer in logical pixel unit.
  38802. *
  38803. * @private
  38804. * @type {number}
  38805. */
  38806. this._height = this.domElement.height;
  38807. /**
  38808. * The viewport of the renderer in logical pixel unit.
  38809. *
  38810. * @private
  38811. * @type {Vector4}
  38812. */
  38813. this._viewport = new Vector4( 0, 0, this._width, this._height );
  38814. /**
  38815. * The scissor rectangle of the renderer in logical pixel unit.
  38816. *
  38817. * @private
  38818. * @type {Vector4}
  38819. */
  38820. this._scissor = new Vector4( 0, 0, this._width, this._height );
  38821. /**
  38822. * Whether the scissor test should be enabled or not.
  38823. *
  38824. * @private
  38825. * @type {boolean}
  38826. */
  38827. this._scissorTest = false;
  38828. /**
  38829. * A reference to a renderer module for managing shader attributes.
  38830. *
  38831. * @private
  38832. * @type {?Attributes}
  38833. * @default null
  38834. */
  38835. this._attributes = null;
  38836. /**
  38837. * A reference to a renderer module for managing geometries.
  38838. *
  38839. * @private
  38840. * @type {?Geometries}
  38841. * @default null
  38842. */
  38843. this._geometries = null;
  38844. /**
  38845. * A reference to a renderer module for managing node related logic.
  38846. *
  38847. * @private
  38848. * @type {?Nodes}
  38849. * @default null
  38850. */
  38851. this._nodes = null;
  38852. /**
  38853. * A reference to a renderer module for managing the internal animation loop.
  38854. *
  38855. * @private
  38856. * @type {?Animation}
  38857. * @default null
  38858. */
  38859. this._animation = null;
  38860. /**
  38861. * A reference to a renderer module for managing shader program bindings.
  38862. *
  38863. * @private
  38864. * @type {?Bindings}
  38865. * @default null
  38866. */
  38867. this._bindings = null;
  38868. /**
  38869. * A reference to a renderer module for managing render objects.
  38870. *
  38871. * @private
  38872. * @type {?RenderObjects}
  38873. * @default null
  38874. */
  38875. this._objects = null;
  38876. /**
  38877. * A reference to a renderer module for managing render and compute pipelines.
  38878. *
  38879. * @private
  38880. * @type {?Pipelines}
  38881. * @default null
  38882. */
  38883. this._pipelines = null;
  38884. /**
  38885. * A reference to a renderer module for managing render bundles.
  38886. *
  38887. * @private
  38888. * @type {?RenderBundles}
  38889. * @default null
  38890. */
  38891. this._bundles = null;
  38892. /**
  38893. * A reference to a renderer module for managing render lists.
  38894. *
  38895. * @private
  38896. * @type {?RenderLists}
  38897. * @default null
  38898. */
  38899. this._renderLists = null;
  38900. /**
  38901. * A reference to a renderer module for managing render contexts.
  38902. *
  38903. * @private
  38904. * @type {?RenderContexts}
  38905. * @default null
  38906. */
  38907. this._renderContexts = null;
  38908. /**
  38909. * A reference to a renderer module for managing textures.
  38910. *
  38911. * @private
  38912. * @type {?Textures}
  38913. * @default null
  38914. */
  38915. this._textures = null;
  38916. /**
  38917. * A reference to a renderer module for backgrounds.
  38918. *
  38919. * @private
  38920. * @type {?Background}
  38921. * @default null
  38922. */
  38923. this._background = null;
  38924. /**
  38925. * This fullscreen quad is used for internal render passes
  38926. * like the tone mapping and color space output pass.
  38927. *
  38928. * @private
  38929. * @type {QuadMesh}
  38930. */
  38931. this._quad = new QuadMesh( new NodeMaterial() );
  38932. this._quad.material.name = 'Renderer_output';
  38933. /**
  38934. * A reference to the current render context.
  38935. *
  38936. * @private
  38937. * @type {?RenderContext}
  38938. * @default null
  38939. */
  38940. this._currentRenderContext = null;
  38941. /**
  38942. * A custom sort function for the opaque render list.
  38943. *
  38944. * @private
  38945. * @type {?Function}
  38946. * @default null
  38947. */
  38948. this._opaqueSort = null;
  38949. /**
  38950. * A custom sort function for the transparent render list.
  38951. *
  38952. * @private
  38953. * @type {?Function}
  38954. * @default null
  38955. */
  38956. this._transparentSort = null;
  38957. /**
  38958. * The framebuffer target.
  38959. *
  38960. * @private
  38961. * @type {?RenderTarget}
  38962. * @default null
  38963. */
  38964. this._frameBufferTarget = null;
  38965. const alphaClear = this.alpha === true ? 0 : 1;
  38966. /**
  38967. * The clear color value.
  38968. *
  38969. * @private
  38970. * @type {Color4}
  38971. */
  38972. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  38973. /**
  38974. * The clear depth value.
  38975. *
  38976. * @private
  38977. * @type {number}
  38978. * @default 1
  38979. */
  38980. this._clearDepth = 1;
  38981. /**
  38982. * The clear stencil value.
  38983. *
  38984. * @private
  38985. * @type {number}
  38986. * @default 0
  38987. */
  38988. this._clearStencil = 0;
  38989. /**
  38990. * The current render target.
  38991. *
  38992. * @private
  38993. * @type {?RenderTarget}
  38994. * @default null
  38995. */
  38996. this._renderTarget = null;
  38997. /**
  38998. * The active cube face.
  38999. *
  39000. * @private
  39001. * @type {number}
  39002. * @default 0
  39003. */
  39004. this._activeCubeFace = 0;
  39005. /**
  39006. * The active mipmap level.
  39007. *
  39008. * @private
  39009. * @type {number}
  39010. * @default 0
  39011. */
  39012. this._activeMipmapLevel = 0;
  39013. /**
  39014. * The current output render target.
  39015. *
  39016. * @private
  39017. * @type {?RenderTarget}
  39018. * @default null
  39019. */
  39020. this._outputRenderTarget = null;
  39021. /**
  39022. * The MRT setting.
  39023. *
  39024. * @private
  39025. * @type {?MRTNode}
  39026. * @default null
  39027. */
  39028. this._mrt = null;
  39029. /**
  39030. * This function defines how a render object is going
  39031. * to be rendered.
  39032. *
  39033. * @private
  39034. * @type {?Function}
  39035. * @default null
  39036. */
  39037. this._renderObjectFunction = null;
  39038. /**
  39039. * Used to keep track of the current render object function.
  39040. *
  39041. * @private
  39042. * @type {?Function}
  39043. * @default null
  39044. */
  39045. this._currentRenderObjectFunction = null;
  39046. /**
  39047. * Used to keep track of the current render bundle.
  39048. *
  39049. * @private
  39050. * @type {?RenderBundle}
  39051. * @default null
  39052. */
  39053. this._currentRenderBundle = null;
  39054. /**
  39055. * Next to `_renderObjectFunction()`, this function provides another hook
  39056. * for influencing the render process of a render object. It is meant for internal
  39057. * use and only relevant for `compileAsync()` right now. Instead of using
  39058. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  39059. * a different function might be used which performs no draw but just the node
  39060. * and pipeline updates.
  39061. *
  39062. * @private
  39063. * @type {?Function}
  39064. * @default null
  39065. */
  39066. this._handleObjectFunction = this._renderObjectDirect;
  39067. /**
  39068. * Indicates whether the device has been lost or not. In WebGL terms, the device
  39069. * lost is considered as a context lost. When this is set to `true`, rendering
  39070. * isn't possible anymore.
  39071. *
  39072. * @private
  39073. * @type {boolean}
  39074. * @default false
  39075. */
  39076. this._isDeviceLost = false;
  39077. /**
  39078. * A callback function that defines what should happen when a device/context lost occurs.
  39079. *
  39080. * @type {Function}
  39081. */
  39082. this.onDeviceLost = this._onDeviceLost;
  39083. /**
  39084. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  39085. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  39086. * This will reduce rendering quality though.
  39087. *
  39088. * @private
  39089. * @type {number}
  39090. * @default HalfFloatType
  39091. */
  39092. this._colorBufferType = colorBufferType;
  39093. /**
  39094. * Whether the renderer has been initialized or not.
  39095. *
  39096. * @private
  39097. * @type {boolean}
  39098. * @default false
  39099. */
  39100. this._initialized = false;
  39101. /**
  39102. * A reference to the promise which initializes the renderer.
  39103. *
  39104. * @private
  39105. * @type {?Promise<this>}
  39106. * @default null
  39107. */
  39108. this._initPromise = null;
  39109. /**
  39110. * An array of compilation promises which are used in `compileAsync()`.
  39111. *
  39112. * @private
  39113. * @type {?Array<Promise>}
  39114. * @default null
  39115. */
  39116. this._compilationPromises = null;
  39117. /**
  39118. * Whether the renderer should render transparent render objects or not.
  39119. *
  39120. * @type {boolean}
  39121. * @default true
  39122. */
  39123. this.transparent = true;
  39124. /**
  39125. * Whether the renderer should render opaque render objects or not.
  39126. *
  39127. * @type {boolean}
  39128. * @default true
  39129. */
  39130. this.opaque = true;
  39131. /**
  39132. * Shadow map configuration
  39133. * @typedef {Object} ShadowMapConfig
  39134. * @property {boolean} enabled - Whether to globally enable shadows or not.
  39135. * @property {number} type - The shadow map type.
  39136. */
  39137. /**
  39138. * The renderer's shadow configuration.
  39139. *
  39140. * @type {ShadowMapConfig}
  39141. */
  39142. this.shadowMap = {
  39143. enabled: false,
  39144. type: PCFShadowMap
  39145. };
  39146. /**
  39147. * XR configuration.
  39148. * @typedef {Object} XRConfig
  39149. * @property {boolean} enabled - Whether to globally enable XR or not.
  39150. */
  39151. /**
  39152. * The renderer's XR manager.
  39153. *
  39154. * @type {XRManager}
  39155. */
  39156. this.xr = new XRManager( this, multiview );
  39157. /**
  39158. * Debug configuration.
  39159. * @typedef {Object} DebugConfig
  39160. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  39161. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  39162. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  39163. */
  39164. /**
  39165. * The renderer's debug configuration.
  39166. *
  39167. * @type {DebugConfig}
  39168. */
  39169. this.debug = {
  39170. checkShaderErrors: true,
  39171. onShaderError: null,
  39172. getShaderAsync: async ( scene, camera, object ) => {
  39173. await this.compileAsync( scene, camera );
  39174. const renderList = this._renderLists.get( scene, camera );
  39175. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  39176. const material = scene.overrideMaterial || object.material;
  39177. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  39178. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  39179. return { fragmentShader, vertexShader };
  39180. }
  39181. };
  39182. }
  39183. /**
  39184. * Initializes the renderer so it is ready for usage.
  39185. *
  39186. * @async
  39187. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  39188. */
  39189. async init() {
  39190. if ( this._initialized ) {
  39191. throw new Error( 'Renderer: Backend has already been initialized.' );
  39192. }
  39193. if ( this._initPromise !== null ) {
  39194. return this._initPromise;
  39195. }
  39196. this._initPromise = new Promise( async ( resolve, reject ) => {
  39197. let backend = this.backend;
  39198. try {
  39199. await backend.init( this );
  39200. } catch ( error ) {
  39201. if ( this._getFallback !== null ) {
  39202. // try the fallback
  39203. try {
  39204. this.backend = backend = this._getFallback( error );
  39205. await backend.init( this );
  39206. } catch ( error ) {
  39207. reject( error );
  39208. return;
  39209. }
  39210. } else {
  39211. reject( error );
  39212. return;
  39213. }
  39214. }
  39215. this._nodes = new Nodes( this, backend );
  39216. this._animation = new Animation( this._nodes, this.info );
  39217. this._attributes = new Attributes( backend );
  39218. this._background = new Background( this, this._nodes );
  39219. this._geometries = new Geometries( this._attributes, this.info );
  39220. this._textures = new Textures( this, backend, this.info );
  39221. this._pipelines = new Pipelines( backend, this._nodes );
  39222. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  39223. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  39224. this._renderLists = new RenderLists( this.lighting );
  39225. this._bundles = new RenderBundles();
  39226. this._renderContexts = new RenderContexts();
  39227. //
  39228. this._animation.start();
  39229. this._initialized = true;
  39230. resolve( this );
  39231. } );
  39232. return this._initPromise;
  39233. }
  39234. /**
  39235. * The coordinate system of the renderer. The value of this property
  39236. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  39237. * `THREE.WebGPUCoordinateSystem`.
  39238. *
  39239. * @readonly
  39240. * @type {number}
  39241. */
  39242. get coordinateSystem() {
  39243. return this.backend.coordinateSystem;
  39244. }
  39245. /**
  39246. * Compiles all materials in the given scene. This can be useful to avoid a
  39247. * phenomenon which is called "shader compilation stutter", which occurs when
  39248. * rendering an object with a new shader for the first time.
  39249. *
  39250. * If you want to add a 3D object to an existing scene, use the third optional
  39251. * parameter for applying the target scene. Note that the (target) scene's lighting
  39252. * and environment must be configured before calling this method.
  39253. *
  39254. * @async
  39255. * @param {Object3D} scene - The scene or 3D object to precompile.
  39256. * @param {Camera} camera - The camera that is used to render the scene.
  39257. * @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.
  39258. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  39259. */
  39260. async compileAsync( scene, camera, targetScene = null ) {
  39261. if ( this._isDeviceLost === true ) return;
  39262. if ( this._initialized === false ) await this.init();
  39263. // preserve render tree
  39264. const nodeFrame = this._nodes.nodeFrame;
  39265. const previousRenderId = nodeFrame.renderId;
  39266. const previousRenderContext = this._currentRenderContext;
  39267. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  39268. const previousCompilationPromises = this._compilationPromises;
  39269. //
  39270. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  39271. if ( targetScene === null ) targetScene = scene;
  39272. const renderTarget = this._renderTarget;
  39273. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  39274. const activeMipmapLevel = this._activeMipmapLevel;
  39275. const compilationPromises = [];
  39276. this._currentRenderContext = renderContext;
  39277. this._currentRenderObjectFunction = this.renderObject;
  39278. this._handleObjectFunction = this._createObjectPipeline;
  39279. this._compilationPromises = compilationPromises;
  39280. nodeFrame.renderId ++;
  39281. //
  39282. nodeFrame.update();
  39283. //
  39284. renderContext.depth = this.depth;
  39285. renderContext.stencil = this.stencil;
  39286. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  39287. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  39288. //
  39289. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  39290. //
  39291. const renderList = this._renderLists.get( scene, camera );
  39292. renderList.begin();
  39293. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  39294. // include lights from target scene
  39295. if ( targetScene !== scene ) {
  39296. targetScene.traverseVisible( function ( object ) {
  39297. if ( object.isLight && object.layers.test( camera.layers ) ) {
  39298. renderList.pushLight( object );
  39299. }
  39300. } );
  39301. }
  39302. renderList.finish();
  39303. //
  39304. if ( renderTarget !== null ) {
  39305. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  39306. const renderTargetData = this._textures.get( renderTarget );
  39307. renderContext.textures = renderTargetData.textures;
  39308. renderContext.depthTexture = renderTargetData.depthTexture;
  39309. } else {
  39310. renderContext.textures = null;
  39311. renderContext.depthTexture = null;
  39312. }
  39313. //
  39314. this._background.update( sceneRef, renderList, renderContext );
  39315. // process render lists
  39316. const opaqueObjects = renderList.opaque;
  39317. const transparentObjects = renderList.transparent;
  39318. const transparentDoublePassObjects = renderList.transparentDoublePass;
  39319. const lightsNode = renderList.lightsNode;
  39320. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  39321. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  39322. // restore render tree
  39323. nodeFrame.renderId = previousRenderId;
  39324. this._currentRenderContext = previousRenderContext;
  39325. this._currentRenderObjectFunction = previousRenderObjectFunction;
  39326. this._compilationPromises = previousCompilationPromises;
  39327. this._handleObjectFunction = this._renderObjectDirect;
  39328. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  39329. await Promise.all( compilationPromises );
  39330. }
  39331. /**
  39332. * Renders the scene in an async fashion.
  39333. *
  39334. * @async
  39335. * @param {Object3D} scene - The scene or 3D object to render.
  39336. * @param {Camera} camera - The camera.
  39337. * @return {Promise} A Promise that resolves when the render has been finished.
  39338. */
  39339. async renderAsync( scene, camera ) {
  39340. if ( this._initialized === false ) await this.init();
  39341. this._renderScene( scene, camera );
  39342. }
  39343. /**
  39344. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  39345. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  39346. *
  39347. * @async
  39348. * @return {Promise} A Promise that resolves when synchronization has been finished.
  39349. */
  39350. async waitForGPU() {
  39351. await this.backend.waitForGPU();
  39352. }
  39353. /**
  39354. * Enables or disables high precision for model-view and normal-view matrices.
  39355. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  39356. *
  39357. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  39358. *
  39359. * @param {boolean} value - Whether to enable or disable high precision.
  39360. * @type {boolean}
  39361. */
  39362. set highPrecision( value ) {
  39363. if ( value === true ) {
  39364. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  39365. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  39366. } else if ( this.highPrecision ) {
  39367. this.overrideNodes.modelViewMatrix = null;
  39368. this.overrideNodes.modelNormalViewMatrix = null;
  39369. }
  39370. }
  39371. /**
  39372. * Returns whether high precision is enabled or not.
  39373. *
  39374. * @return {boolean} Whether high precision is enabled or not.
  39375. * @type {boolean}
  39376. */
  39377. get highPrecision() {
  39378. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  39379. }
  39380. /**
  39381. * Sets the given MRT configuration.
  39382. *
  39383. * @param {MRTNode} mrt - The MRT node to set.
  39384. * @return {Renderer} A reference to this renderer.
  39385. */
  39386. setMRT( mrt ) {
  39387. this._mrt = mrt;
  39388. return this;
  39389. }
  39390. /**
  39391. * Returns the MRT configuration.
  39392. *
  39393. * @return {MRTNode} The MRT configuration.
  39394. */
  39395. getMRT() {
  39396. return this._mrt;
  39397. }
  39398. /**
  39399. * Returns the color buffer type.
  39400. *
  39401. * @return {number} The color buffer type.
  39402. */
  39403. getColorBufferType() {
  39404. return this._colorBufferType;
  39405. }
  39406. /**
  39407. * Default implementation of the device lost callback.
  39408. *
  39409. * @private
  39410. * @param {Object} info - Information about the context lost.
  39411. */
  39412. _onDeviceLost( info ) {
  39413. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  39414. if ( info.reason ) {
  39415. errorMessage += `\nReason: ${info.reason}`;
  39416. }
  39417. console.error( errorMessage );
  39418. this._isDeviceLost = true;
  39419. }
  39420. /**
  39421. * Renders the given render bundle.
  39422. *
  39423. * @private
  39424. * @param {Object} bundle - Render bundle data.
  39425. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  39426. * @param {LightsNode} lightsNode - The lights node.
  39427. */
  39428. _renderBundle( bundle, sceneRef, lightsNode ) {
  39429. const { bundleGroup, camera, renderList } = bundle;
  39430. const renderContext = this._currentRenderContext;
  39431. //
  39432. const renderBundle = this._bundles.get( bundleGroup, camera );
  39433. const renderBundleData = this.backend.get( renderBundle );
  39434. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  39435. //
  39436. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  39437. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  39438. renderBundleData.renderContexts.add( renderContext );
  39439. if ( renderBundleNeedsUpdate ) {
  39440. this.backend.beginBundle( renderContext );
  39441. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  39442. renderBundleData.renderObjects = [];
  39443. }
  39444. this._currentRenderBundle = renderBundle;
  39445. const {
  39446. transparentDoublePass: transparentDoublePassObjects,
  39447. transparent: transparentObjects,
  39448. opaque: opaqueObjects
  39449. } = renderList;
  39450. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  39451. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  39452. this._currentRenderBundle = null;
  39453. //
  39454. this.backend.finishBundle( renderContext, renderBundle );
  39455. renderBundleData.version = bundleGroup.version;
  39456. } else {
  39457. const { renderObjects } = renderBundleData;
  39458. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  39459. const renderObject = renderObjects[ i ];
  39460. if ( this._nodes.needsRefresh( renderObject ) ) {
  39461. this._nodes.updateBefore( renderObject );
  39462. this._nodes.updateForRender( renderObject );
  39463. this._bindings.updateForRender( renderObject );
  39464. this._nodes.updateAfter( renderObject );
  39465. }
  39466. }
  39467. }
  39468. this.backend.addBundle( renderContext, renderBundle );
  39469. }
  39470. /**
  39471. * Renders the scene or 3D object with the given camera. This method can only be called
  39472. * if the renderer has been initialized.
  39473. *
  39474. * The target of the method is the default framebuffer (meaning the canvas)
  39475. * or alternatively a render target when specified via `setRenderTarget()`.
  39476. *
  39477. * @param {Object3D} scene - The scene or 3D object to render.
  39478. * @param {Camera} camera - The camera to render the scene with.
  39479. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  39480. * Only returned when the renderer has not been initialized.
  39481. */
  39482. render( scene, camera ) {
  39483. if ( this._initialized === false ) {
  39484. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  39485. return this.renderAsync( scene, camera );
  39486. }
  39487. this._renderScene( scene, camera );
  39488. }
  39489. /**
  39490. * Returns an internal render target which is used when computing the output tone mapping
  39491. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  39492. * pass and not inline to achieve more correct results.
  39493. *
  39494. * @private
  39495. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  39496. */
  39497. _getFrameBufferTarget() {
  39498. const { currentToneMapping, currentColorSpace } = this;
  39499. const useToneMapping = currentToneMapping !== NoToneMapping;
  39500. const useColorSpace = currentColorSpace !== ColorManagement.workingColorSpace;
  39501. if ( useToneMapping === false && useColorSpace === false ) return null;
  39502. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  39503. const { depth, stencil } = this;
  39504. let frameBufferTarget = this._frameBufferTarget;
  39505. if ( frameBufferTarget === null ) {
  39506. frameBufferTarget = new RenderTarget( width, height, {
  39507. depthBuffer: depth,
  39508. stencilBuffer: stencil,
  39509. type: this._colorBufferType,
  39510. format: RGBAFormat,
  39511. colorSpace: ColorManagement.workingColorSpace,
  39512. generateMipmaps: false,
  39513. minFilter: LinearFilter,
  39514. magFilter: LinearFilter,
  39515. samples: this.samples
  39516. } );
  39517. frameBufferTarget.isPostProcessingRenderTarget = true;
  39518. this._frameBufferTarget = frameBufferTarget;
  39519. }
  39520. const outputRenderTarget = this.getOutputRenderTarget();
  39521. frameBufferTarget.depthBuffer = depth;
  39522. frameBufferTarget.stencilBuffer = stencil;
  39523. if ( outputRenderTarget !== null ) {
  39524. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  39525. } else {
  39526. frameBufferTarget.setSize( width, height, 1 );
  39527. }
  39528. frameBufferTarget.viewport.copy( this._viewport );
  39529. frameBufferTarget.scissor.copy( this._scissor );
  39530. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  39531. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  39532. frameBufferTarget.scissorTest = this._scissorTest;
  39533. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  39534. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  39535. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  39536. return frameBufferTarget;
  39537. }
  39538. /**
  39539. * Renders the scene or 3D object with the given camera.
  39540. *
  39541. * @private
  39542. * @param {Object3D} scene - The scene or 3D object to render.
  39543. * @param {Camera} camera - The camera to render the scene with.
  39544. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  39545. * @return {RenderContext} The current render context.
  39546. */
  39547. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  39548. if ( this._isDeviceLost === true ) return;
  39549. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  39550. // preserve render tree
  39551. const nodeFrame = this._nodes.nodeFrame;
  39552. const previousRenderId = nodeFrame.renderId;
  39553. const previousRenderContext = this._currentRenderContext;
  39554. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  39555. //
  39556. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  39557. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  39558. const activeCubeFace = this._activeCubeFace;
  39559. const activeMipmapLevel = this._activeMipmapLevel;
  39560. //
  39561. let renderTarget;
  39562. if ( frameBufferTarget !== null ) {
  39563. renderTarget = frameBufferTarget;
  39564. this.setRenderTarget( renderTarget );
  39565. } else {
  39566. renderTarget = outputRenderTarget;
  39567. }
  39568. //
  39569. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  39570. this._currentRenderContext = renderContext;
  39571. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  39572. //
  39573. this.info.calls ++;
  39574. this.info.render.calls ++;
  39575. this.info.render.frameCalls ++;
  39576. nodeFrame.renderId = this.info.calls;
  39577. //
  39578. const coordinateSystem = this.coordinateSystem;
  39579. const xr = this.xr;
  39580. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  39581. camera.coordinateSystem = coordinateSystem;
  39582. camera.updateProjectionMatrix();
  39583. if ( camera.isArrayCamera ) {
  39584. for ( const subCamera of camera.cameras ) {
  39585. subCamera.coordinateSystem = coordinateSystem;
  39586. subCamera.updateProjectionMatrix();
  39587. }
  39588. }
  39589. }
  39590. //
  39591. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  39592. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  39593. if ( xr.enabled === true && xr.isPresenting === true ) {
  39594. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  39595. camera = xr.getCamera(); // use XR camera for rendering
  39596. }
  39597. //
  39598. let viewport = this._viewport;
  39599. let scissor = this._scissor;
  39600. let pixelRatio = this._pixelRatio;
  39601. if ( renderTarget !== null ) {
  39602. viewport = renderTarget.viewport;
  39603. scissor = renderTarget.scissor;
  39604. pixelRatio = 1;
  39605. }
  39606. this.getDrawingBufferSize( _drawingBufferSize );
  39607. _screen.set( 0, 0, _drawingBufferSize.width, _drawingBufferSize.height );
  39608. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  39609. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  39610. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  39611. renderContext.viewportValue.width >>= activeMipmapLevel;
  39612. renderContext.viewportValue.height >>= activeMipmapLevel;
  39613. renderContext.viewportValue.minDepth = minDepth;
  39614. renderContext.viewportValue.maxDepth = maxDepth;
  39615. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  39616. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  39617. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  39618. renderContext.scissorValue.width >>= activeMipmapLevel;
  39619. renderContext.scissorValue.height >>= activeMipmapLevel;
  39620. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  39621. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  39622. //
  39623. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  39624. //
  39625. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  39626. if ( ! camera.isArrayCamera ) {
  39627. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  39628. frustum.setFromProjectionMatrix( _projScreenMatrix, camera.coordinateSystem, camera.reversedDepth );
  39629. }
  39630. const renderList = this._renderLists.get( scene, camera );
  39631. renderList.begin();
  39632. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  39633. renderList.finish();
  39634. if ( this.sortObjects === true ) {
  39635. renderList.sort( this._opaqueSort, this._transparentSort );
  39636. }
  39637. //
  39638. if ( renderTarget !== null ) {
  39639. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  39640. const renderTargetData = this._textures.get( renderTarget );
  39641. renderContext.textures = renderTargetData.textures;
  39642. renderContext.depthTexture = renderTargetData.depthTexture;
  39643. renderContext.width = renderTargetData.width;
  39644. renderContext.height = renderTargetData.height;
  39645. renderContext.renderTarget = renderTarget;
  39646. renderContext.depth = renderTarget.depthBuffer;
  39647. renderContext.stencil = renderTarget.stencilBuffer;
  39648. } else {
  39649. renderContext.textures = null;
  39650. renderContext.depthTexture = null;
  39651. renderContext.width = _drawingBufferSize.width;
  39652. renderContext.height = _drawingBufferSize.height;
  39653. renderContext.depth = this.depth;
  39654. renderContext.stencil = this.stencil;
  39655. }
  39656. renderContext.width >>= activeMipmapLevel;
  39657. renderContext.height >>= activeMipmapLevel;
  39658. renderContext.activeCubeFace = activeCubeFace;
  39659. renderContext.activeMipmapLevel = activeMipmapLevel;
  39660. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  39661. //
  39662. renderContext.scissorValue.max( _vector4.set( 0, 0, 0, 0 ) );
  39663. if ( renderContext.scissorValue.x + renderContext.scissorValue.width > renderContext.width ) {
  39664. renderContext.scissorValue.width = Math.max( renderContext.width - renderContext.scissorValue.x, 0 );
  39665. }
  39666. if ( renderContext.scissorValue.y + renderContext.scissorValue.height > renderContext.height ) {
  39667. renderContext.scissorValue.height = Math.max( renderContext.height - renderContext.scissorValue.y, 0 );
  39668. }
  39669. //
  39670. this._background.update( sceneRef, renderList, renderContext );
  39671. //
  39672. renderContext.camera = camera;
  39673. this.backend.beginRender( renderContext );
  39674. // process render lists
  39675. const {
  39676. bundles,
  39677. lightsNode,
  39678. transparentDoublePass: transparentDoublePassObjects,
  39679. transparent: transparentObjects,
  39680. opaque: opaqueObjects
  39681. } = renderList;
  39682. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  39683. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  39684. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  39685. // finish render pass
  39686. this.backend.finishRender( renderContext );
  39687. // restore render tree
  39688. nodeFrame.renderId = previousRenderId;
  39689. this._currentRenderContext = previousRenderContext;
  39690. this._currentRenderObjectFunction = previousRenderObjectFunction;
  39691. //
  39692. if ( frameBufferTarget !== null ) {
  39693. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  39694. this._renderOutput( renderTarget );
  39695. }
  39696. //
  39697. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  39698. //
  39699. return renderContext;
  39700. }
  39701. _setXRLayerSize( width, height ) {
  39702. this._width = width;
  39703. this._height = height;
  39704. this.setViewport( 0, 0, width, height );
  39705. }
  39706. /**
  39707. * The output pass performs tone mapping and color space conversion.
  39708. *
  39709. * @private
  39710. * @param {RenderTarget} renderTarget - The current render target.
  39711. */
  39712. _renderOutput( renderTarget ) {
  39713. const quad = this._quad;
  39714. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  39715. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  39716. quad.material.needsUpdate = true;
  39717. }
  39718. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  39719. const currentAutoClear = this.autoClear;
  39720. const currentXR = this.xr.enabled;
  39721. this.autoClear = false;
  39722. this.xr.enabled = false;
  39723. this._renderScene( quad, quad.camera, false );
  39724. this.autoClear = currentAutoClear;
  39725. this.xr.enabled = currentXR;
  39726. }
  39727. /**
  39728. * Returns the maximum available anisotropy for texture filtering.
  39729. *
  39730. * @return {number} The maximum available anisotropy.
  39731. */
  39732. getMaxAnisotropy() {
  39733. return this.backend.getMaxAnisotropy();
  39734. }
  39735. /**
  39736. * Returns the active cube face.
  39737. *
  39738. * @return {number} The active cube face.
  39739. */
  39740. getActiveCubeFace() {
  39741. return this._activeCubeFace;
  39742. }
  39743. /**
  39744. * Returns the active mipmap level.
  39745. *
  39746. * @return {number} The active mipmap level.
  39747. */
  39748. getActiveMipmapLevel() {
  39749. return this._activeMipmapLevel;
  39750. }
  39751. /**
  39752. * Applications are advised to always define the animation loop
  39753. * with this method and not manually with `requestAnimationFrame()`
  39754. * for best compatibility.
  39755. *
  39756. * @async
  39757. * @param {?Function} callback - The application's animation loop.
  39758. * @return {Promise} A Promise that resolves when the set has been executed.
  39759. */
  39760. async setAnimationLoop( callback ) {
  39761. if ( this._initialized === false ) await this.init();
  39762. this._animation.setAnimationLoop( callback );
  39763. }
  39764. /**
  39765. * Can be used to transfer buffer data from a storage buffer attribute
  39766. * from the GPU to the CPU in context of compute shaders.
  39767. *
  39768. * @async
  39769. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  39770. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  39771. */
  39772. async getArrayBufferAsync( attribute ) {
  39773. return await this.backend.getArrayBufferAsync( attribute );
  39774. }
  39775. /**
  39776. * Returns the rendering context.
  39777. *
  39778. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  39779. */
  39780. getContext() {
  39781. return this.backend.getContext();
  39782. }
  39783. /**
  39784. * Returns the pixel ratio.
  39785. *
  39786. * @return {number} The pixel ratio.
  39787. */
  39788. getPixelRatio() {
  39789. return this._pixelRatio;
  39790. }
  39791. /**
  39792. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  39793. *
  39794. * @param {Vector2} target - The method writes the result in this target object.
  39795. * @return {Vector2} The drawing buffer size.
  39796. */
  39797. getDrawingBufferSize( target ) {
  39798. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  39799. }
  39800. /**
  39801. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  39802. *
  39803. * @param {Vector2} target - The method writes the result in this target object.
  39804. * @return {Vector2} The renderer's size in logical pixels.
  39805. */
  39806. getSize( target ) {
  39807. return target.set( this._width, this._height );
  39808. }
  39809. /**
  39810. * Sets the given pixel ratio and resizes the canvas if necessary.
  39811. *
  39812. * @param {number} [value=1] - The pixel ratio.
  39813. */
  39814. setPixelRatio( value = 1 ) {
  39815. if ( this._pixelRatio === value ) return;
  39816. this._pixelRatio = value;
  39817. this.setSize( this._width, this._height, false );
  39818. }
  39819. /**
  39820. * This method allows to define the drawing buffer size by specifying
  39821. * width, height and pixel ratio all at once. The size of the drawing
  39822. * buffer is computed with this formula:
  39823. * ```js
  39824. * size.x = width * pixelRatio;
  39825. * size.y = height * pixelRatio;
  39826. * ```
  39827. *
  39828. * @param {number} width - The width in logical pixels.
  39829. * @param {number} height - The height in logical pixels.
  39830. * @param {number} pixelRatio - The pixel ratio.
  39831. */
  39832. setDrawingBufferSize( width, height, pixelRatio ) {
  39833. // Renderer can't be resized while presenting in XR.
  39834. if ( this.xr && this.xr.isPresenting ) return;
  39835. this._width = width;
  39836. this._height = height;
  39837. this._pixelRatio = pixelRatio;
  39838. this.domElement.width = Math.floor( width * pixelRatio );
  39839. this.domElement.height = Math.floor( height * pixelRatio );
  39840. this.setViewport( 0, 0, width, height );
  39841. if ( this._initialized ) this.backend.updateSize();
  39842. }
  39843. /**
  39844. * Sets the size of the renderer.
  39845. *
  39846. * @param {number} width - The width in logical pixels.
  39847. * @param {number} height - The height in logical pixels.
  39848. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  39849. */
  39850. setSize( width, height, updateStyle = true ) {
  39851. // Renderer can't be resized while presenting in XR.
  39852. if ( this.xr && this.xr.isPresenting ) return;
  39853. this._width = width;
  39854. this._height = height;
  39855. this.domElement.width = Math.floor( width * this._pixelRatio );
  39856. this.domElement.height = Math.floor( height * this._pixelRatio );
  39857. if ( updateStyle === true ) {
  39858. this.domElement.style.width = width + 'px';
  39859. this.domElement.style.height = height + 'px';
  39860. }
  39861. this.setViewport( 0, 0, width, height );
  39862. if ( this._initialized ) this.backend.updateSize();
  39863. }
  39864. /**
  39865. * Defines a manual sort function for the opaque render list.
  39866. * Pass `null` to use the default sort.
  39867. *
  39868. * @param {Function} method - The sort function.
  39869. */
  39870. setOpaqueSort( method ) {
  39871. this._opaqueSort = method;
  39872. }
  39873. /**
  39874. * Defines a manual sort function for the transparent render list.
  39875. * Pass `null` to use the default sort.
  39876. *
  39877. * @param {Function} method - The sort function.
  39878. */
  39879. setTransparentSort( method ) {
  39880. this._transparentSort = method;
  39881. }
  39882. /**
  39883. * Returns the scissor rectangle.
  39884. *
  39885. * @param {Vector4} target - The method writes the result in this target object.
  39886. * @return {Vector4} The scissor rectangle.
  39887. */
  39888. getScissor( target ) {
  39889. const scissor = this._scissor;
  39890. target.x = scissor.x;
  39891. target.y = scissor.y;
  39892. target.width = scissor.width;
  39893. target.height = scissor.height;
  39894. return target;
  39895. }
  39896. /**
  39897. * Defines the scissor rectangle.
  39898. *
  39899. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  39900. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  39901. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  39902. * @param {number} width - The width of the scissor box in logical pixel unit.
  39903. * @param {number} height - The height of the scissor box in logical pixel unit.
  39904. */
  39905. setScissor( x, y, width, height ) {
  39906. const scissor = this._scissor;
  39907. if ( x.isVector4 ) {
  39908. scissor.copy( x );
  39909. } else {
  39910. scissor.set( x, y, width, height );
  39911. }
  39912. }
  39913. /**
  39914. * Returns the scissor test value.
  39915. *
  39916. * @return {boolean} Whether the scissor test should be enabled or not.
  39917. */
  39918. getScissorTest() {
  39919. return this._scissorTest;
  39920. }
  39921. /**
  39922. * Defines the scissor test.
  39923. *
  39924. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  39925. */
  39926. setScissorTest( boolean ) {
  39927. this._scissorTest = boolean;
  39928. this.backend.setScissorTest( boolean );
  39929. }
  39930. /**
  39931. * Returns the viewport definition.
  39932. *
  39933. * @param {Vector4} target - The method writes the result in this target object.
  39934. * @return {Vector4} The viewport definition.
  39935. */
  39936. getViewport( target ) {
  39937. return target.copy( this._viewport );
  39938. }
  39939. /**
  39940. * Defines the viewport.
  39941. *
  39942. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39943. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  39944. * @param {number} width - The width of the viewport in logical pixel unit.
  39945. * @param {number} height - The height of the viewport in logical pixel unit.
  39946. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  39947. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  39948. */
  39949. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  39950. const viewport = this._viewport;
  39951. if ( x.isVector4 ) {
  39952. viewport.copy( x );
  39953. } else {
  39954. viewport.set( x, y, width, height );
  39955. }
  39956. viewport.minDepth = minDepth;
  39957. viewport.maxDepth = maxDepth;
  39958. }
  39959. /**
  39960. * Returns the clear color.
  39961. *
  39962. * @param {Color} target - The method writes the result in this target object.
  39963. * @return {Color} The clear color.
  39964. */
  39965. getClearColor( target ) {
  39966. return target.copy( this._clearColor );
  39967. }
  39968. /**
  39969. * Defines the clear color and optionally the clear alpha.
  39970. *
  39971. * @param {Color} color - The clear color.
  39972. * @param {number} [alpha=1] - The clear alpha.
  39973. */
  39974. setClearColor( color, alpha = 1 ) {
  39975. this._clearColor.set( color );
  39976. this._clearColor.a = alpha;
  39977. }
  39978. /**
  39979. * Returns the clear alpha.
  39980. *
  39981. * @return {number} The clear alpha.
  39982. */
  39983. getClearAlpha() {
  39984. return this._clearColor.a;
  39985. }
  39986. /**
  39987. * Defines the clear alpha.
  39988. *
  39989. * @param {number} alpha - The clear alpha.
  39990. */
  39991. setClearAlpha( alpha ) {
  39992. this._clearColor.a = alpha;
  39993. }
  39994. /**
  39995. * Returns the clear depth.
  39996. *
  39997. * @return {number} The clear depth.
  39998. */
  39999. getClearDepth() {
  40000. return this._clearDepth;
  40001. }
  40002. /**
  40003. * Defines the clear depth.
  40004. *
  40005. * @param {number} depth - The clear depth.
  40006. */
  40007. setClearDepth( depth ) {
  40008. this._clearDepth = depth;
  40009. }
  40010. /**
  40011. * Returns the clear stencil.
  40012. *
  40013. * @return {number} The clear stencil.
  40014. */
  40015. getClearStencil() {
  40016. return this._clearStencil;
  40017. }
  40018. /**
  40019. * Defines the clear stencil.
  40020. *
  40021. * @param {number} stencil - The clear stencil.
  40022. */
  40023. setClearStencil( stencil ) {
  40024. this._clearStencil = stencil;
  40025. }
  40026. /**
  40027. * This method performs an occlusion query for the given 3D object.
  40028. * It returns `true` if the given 3D object is fully occluded by other
  40029. * 3D objects in the scene.
  40030. *
  40031. * @param {Object3D} object - The 3D object to test.
  40032. * @return {boolean} Whether the 3D object is fully occluded or not.
  40033. */
  40034. isOccluded( object ) {
  40035. const renderContext = this._currentRenderContext;
  40036. return renderContext && this.backend.isOccluded( renderContext, object );
  40037. }
  40038. /**
  40039. * Performs a manual clear operation. This method ignores `autoClear` properties.
  40040. *
  40041. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  40042. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  40043. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  40044. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40045. * Only returned when the renderer has not been initialized.
  40046. */
  40047. clear( color = true, depth = true, stencil = true ) {
  40048. if ( this._initialized === false ) {
  40049. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  40050. return this.clearAsync( color, depth, stencil );
  40051. }
  40052. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  40053. let renderContext = null;
  40054. if ( renderTarget !== null ) {
  40055. this._textures.updateRenderTarget( renderTarget );
  40056. const renderTargetData = this._textures.get( renderTarget );
  40057. renderContext = this._renderContexts.getForClear( renderTarget );
  40058. renderContext.textures = renderTargetData.textures;
  40059. renderContext.depthTexture = renderTargetData.depthTexture;
  40060. renderContext.width = renderTargetData.width;
  40061. renderContext.height = renderTargetData.height;
  40062. renderContext.renderTarget = renderTarget;
  40063. renderContext.depth = renderTarget.depthBuffer;
  40064. renderContext.stencil = renderTarget.stencilBuffer;
  40065. // #30329
  40066. renderContext.clearColorValue = this.backend.getClearColor();
  40067. renderContext.activeCubeFace = this.getActiveCubeFace();
  40068. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  40069. }
  40070. this.backend.clear( color, depth, stencil, renderContext );
  40071. if ( renderTarget !== null && this._renderTarget === null ) {
  40072. this._renderOutput( renderTarget );
  40073. }
  40074. }
  40075. /**
  40076. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  40077. *
  40078. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40079. * Only returned when the renderer has not been initialized.
  40080. */
  40081. clearColor() {
  40082. return this.clear( true, false, false );
  40083. }
  40084. /**
  40085. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  40086. *
  40087. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40088. * Only returned when the renderer has not been initialized.
  40089. */
  40090. clearDepth() {
  40091. return this.clear( false, true, false );
  40092. }
  40093. /**
  40094. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  40095. *
  40096. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40097. * Only returned when the renderer has not been initialized.
  40098. */
  40099. clearStencil() {
  40100. return this.clear( false, false, true );
  40101. }
  40102. /**
  40103. * Async version of {@link Renderer#clear}.
  40104. *
  40105. * @async
  40106. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  40107. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  40108. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  40109. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40110. */
  40111. async clearAsync( color = true, depth = true, stencil = true ) {
  40112. if ( this._initialized === false ) await this.init();
  40113. this.clear( color, depth, stencil );
  40114. }
  40115. /**
  40116. * Async version of {@link Renderer#clearColor}.
  40117. *
  40118. * @async
  40119. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40120. */
  40121. async clearColorAsync() {
  40122. this.clearAsync( true, false, false );
  40123. }
  40124. /**
  40125. * Async version of {@link Renderer#clearDepth}.
  40126. *
  40127. * @async
  40128. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40129. */
  40130. async clearDepthAsync() {
  40131. this.clearAsync( false, true, false );
  40132. }
  40133. /**
  40134. * Async version of {@link Renderer#clearStencil}.
  40135. *
  40136. * @async
  40137. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  40138. */
  40139. async clearStencilAsync() {
  40140. this.clearAsync( false, false, true );
  40141. }
  40142. /**
  40143. * The current tone mapping of the renderer. When not producing screen output,
  40144. * the tone mapping is always `NoToneMapping`.
  40145. *
  40146. * @type {number}
  40147. */
  40148. get currentToneMapping() {
  40149. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  40150. }
  40151. /**
  40152. * The current color space of the renderer. When not producing screen output,
  40153. * the color space is always the working color space.
  40154. *
  40155. * @type {string}
  40156. */
  40157. get currentColorSpace() {
  40158. return this.isOutputTarget ? this.outputColorSpace : ColorManagement.workingColorSpace;
  40159. }
  40160. /**
  40161. * Returns `true` if the rendering settings are set to screen output.
  40162. *
  40163. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  40164. */
  40165. get isOutputTarget() {
  40166. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  40167. }
  40168. /**
  40169. * Frees all internal resources of the renderer. Call this method if the renderer
  40170. * is no longer in use by your app.
  40171. */
  40172. dispose() {
  40173. if ( this._initialized === true ) {
  40174. this.info.dispose();
  40175. this.backend.dispose();
  40176. this._animation.dispose();
  40177. this._objects.dispose();
  40178. this._pipelines.dispose();
  40179. this._nodes.dispose();
  40180. this._bindings.dispose();
  40181. this._renderLists.dispose();
  40182. this._renderContexts.dispose();
  40183. this._textures.dispose();
  40184. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  40185. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  40186. if ( queryPool !== null ) queryPool.dispose();
  40187. } );
  40188. }
  40189. this.setRenderTarget( null );
  40190. this.setAnimationLoop( null );
  40191. }
  40192. /**
  40193. * Sets the given render target. Calling this method means the renderer does not
  40194. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  40195. * Use `null` as the first argument to reset the state.
  40196. *
  40197. * @param {?RenderTarget} renderTarget - The render target to set.
  40198. * @param {number} [activeCubeFace=0] - The active cube face.
  40199. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  40200. */
  40201. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  40202. this._renderTarget = renderTarget;
  40203. this._activeCubeFace = activeCubeFace;
  40204. this._activeMipmapLevel = activeMipmapLevel;
  40205. }
  40206. /**
  40207. * Returns the current render target.
  40208. *
  40209. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  40210. */
  40211. getRenderTarget() {
  40212. return this._renderTarget;
  40213. }
  40214. /**
  40215. * Sets the output render target for the renderer.
  40216. *
  40217. * @param {Object} renderTarget - The render target to set as the output target.
  40218. */
  40219. setOutputRenderTarget( renderTarget ) {
  40220. this._outputRenderTarget = renderTarget;
  40221. }
  40222. /**
  40223. * Returns the current output target.
  40224. *
  40225. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  40226. */
  40227. getOutputRenderTarget() {
  40228. return this._outputRenderTarget;
  40229. }
  40230. /**
  40231. * Resets the renderer to the initial state before WebXR started.
  40232. *
  40233. */
  40234. _resetXRState() {
  40235. this.backend.setXRTarget( null );
  40236. this.setOutputRenderTarget( null );
  40237. this.setRenderTarget( null );
  40238. this._frameBufferTarget.dispose();
  40239. this._frameBufferTarget = null;
  40240. }
  40241. /**
  40242. * Callback for {@link Renderer#setRenderObjectFunction}.
  40243. *
  40244. * @callback renderObjectFunction
  40245. * @param {Object3D} object - The 3D object.
  40246. * @param {Scene} scene - The scene the 3D object belongs to.
  40247. * @param {Camera} camera - The camera the object should be rendered with.
  40248. * @param {BufferGeometry} geometry - The object's geometry.
  40249. * @param {Material} material - The object's material.
  40250. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  40251. * @param {LightsNode} lightsNode - The current lights node.
  40252. * @param {ClippingContext} clippingContext - The clipping context.
  40253. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  40254. */
  40255. /**
  40256. * Sets the given render object function. Calling this method overwrites the default implementation
  40257. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  40258. * if you want to modify the way objects are rendered. For example you can define things like "every
  40259. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  40260. * The custom function must always call `renderObject()` in its implementation.
  40261. *
  40262. * Use `null` as the first argument to reset the state.
  40263. *
  40264. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  40265. */
  40266. setRenderObjectFunction( renderObjectFunction ) {
  40267. this._renderObjectFunction = renderObjectFunction;
  40268. }
  40269. /**
  40270. * Returns the current render object function.
  40271. *
  40272. * @return {?Function} The current render object function. Returns `null` if no function is set.
  40273. */
  40274. getRenderObjectFunction() {
  40275. return this._renderObjectFunction;
  40276. }
  40277. /**
  40278. * Execute a single or an array of compute nodes. This method can only be called
  40279. * if the renderer has been initialized.
  40280. *
  40281. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  40282. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  40283. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  40284. */
  40285. compute( computeNodes, dispatchSizeOrCount = null ) {
  40286. if ( this._isDeviceLost === true ) return;
  40287. if ( this._initialized === false ) {
  40288. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  40289. return this.computeAsync( computeNodes );
  40290. }
  40291. //
  40292. const nodeFrame = this._nodes.nodeFrame;
  40293. const previousRenderId = nodeFrame.renderId;
  40294. //
  40295. this.info.calls ++;
  40296. this.info.compute.calls ++;
  40297. this.info.compute.frameCalls ++;
  40298. nodeFrame.renderId = this.info.calls;
  40299. //
  40300. const backend = this.backend;
  40301. const pipelines = this._pipelines;
  40302. const bindings = this._bindings;
  40303. const nodes = this._nodes;
  40304. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  40305. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  40306. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  40307. }
  40308. backend.beginCompute( computeNodes );
  40309. for ( const computeNode of computeList ) {
  40310. // onInit
  40311. if ( pipelines.has( computeNode ) === false ) {
  40312. const dispose = () => {
  40313. computeNode.removeEventListener( 'dispose', dispose );
  40314. pipelines.delete( computeNode );
  40315. bindings.delete( computeNode );
  40316. nodes.delete( computeNode );
  40317. };
  40318. computeNode.addEventListener( 'dispose', dispose );
  40319. //
  40320. const onInitFn = computeNode.onInitFunction;
  40321. if ( onInitFn !== null ) {
  40322. onInitFn.call( computeNode, { renderer: this } );
  40323. }
  40324. }
  40325. nodes.updateForCompute( computeNode );
  40326. bindings.updateForCompute( computeNode );
  40327. const computeBindings = bindings.getForCompute( computeNode );
  40328. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  40329. backend.compute( computeNodes, computeNode, computeBindings, computePipeline, dispatchSizeOrCount );
  40330. }
  40331. backend.finishCompute( computeNodes );
  40332. //
  40333. nodeFrame.renderId = previousRenderId;
  40334. }
  40335. /**
  40336. * Execute a single or an array of compute nodes.
  40337. *
  40338. * @async
  40339. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  40340. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  40341. * @return {Promise} A Promise that resolve when the compute has finished.
  40342. */
  40343. async computeAsync( computeNodes, dispatchSizeOrCount = null ) {
  40344. if ( this._initialized === false ) await this.init();
  40345. this.compute( computeNodes, dispatchSizeOrCount );
  40346. }
  40347. /**
  40348. * Checks if the given feature is supported by the selected backend.
  40349. *
  40350. * @async
  40351. * @param {string} name - The feature's name.
  40352. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  40353. */
  40354. async hasFeatureAsync( name ) {
  40355. if ( this._initialized === false ) await this.init();
  40356. return this.backend.hasFeature( name );
  40357. }
  40358. async resolveTimestampsAsync( type = 'render' ) {
  40359. if ( this._initialized === false ) await this.init();
  40360. return this.backend.resolveTimestampsAsync( type );
  40361. }
  40362. /**
  40363. * Checks if the given feature is supported by the selected backend. If the
  40364. * renderer has not been initialized, this method always returns `false`.
  40365. *
  40366. * @param {string} name - The feature's name.
  40367. * @return {boolean} Whether the feature is supported or not.
  40368. */
  40369. hasFeature( name ) {
  40370. if ( this._initialized === false ) {
  40371. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  40372. return false;
  40373. }
  40374. return this.backend.hasFeature( name );
  40375. }
  40376. /**
  40377. * Returns `true` when the renderer has been initialized.
  40378. *
  40379. * @return {boolean} Whether the renderer has been initialized or not.
  40380. */
  40381. hasInitialized() {
  40382. return this._initialized;
  40383. }
  40384. /**
  40385. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  40386. * (which can cause noticeable lags due to decode and GPU upload overhead).
  40387. *
  40388. * @async
  40389. * @param {Texture} texture - The texture.
  40390. * @return {Promise} A Promise that resolves when the texture has been initialized.
  40391. */
  40392. async initTextureAsync( texture ) {
  40393. if ( this._initialized === false ) await this.init();
  40394. this._textures.updateTexture( texture );
  40395. }
  40396. /**
  40397. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  40398. * (which can cause noticeable lags due to decode and GPU upload overhead).
  40399. *
  40400. * This method can only be used if the renderer has been initialized.
  40401. *
  40402. * @param {Texture} texture - The texture.
  40403. */
  40404. initTexture( texture ) {
  40405. if ( this._initialized === false ) {
  40406. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  40407. }
  40408. this._textures.updateTexture( texture );
  40409. }
  40410. /**
  40411. * Copies the current bound framebuffer into the given texture.
  40412. *
  40413. * @param {FramebufferTexture} framebufferTexture - The texture.
  40414. * @param {?(Vector2|Vector4)} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  40415. */
  40416. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  40417. if ( rectangle !== null ) {
  40418. if ( rectangle.isVector2 ) {
  40419. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  40420. } else if ( rectangle.isVector4 ) {
  40421. rectangle = _vector4.copy( rectangle ).floor();
  40422. } else {
  40423. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  40424. return;
  40425. }
  40426. } else {
  40427. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  40428. }
  40429. //
  40430. let renderContext = this._currentRenderContext;
  40431. let renderTarget;
  40432. if ( renderContext !== null ) {
  40433. renderTarget = renderContext.renderTarget;
  40434. } else {
  40435. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  40436. if ( renderTarget !== null ) {
  40437. this._textures.updateRenderTarget( renderTarget );
  40438. renderContext = this._textures.get( renderTarget );
  40439. }
  40440. }
  40441. //
  40442. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  40443. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  40444. }
  40445. /**
  40446. * Copies data of the given source texture into a destination texture.
  40447. *
  40448. * @param {Texture} srcTexture - The source texture.
  40449. * @param {Texture} dstTexture - The destination texture.
  40450. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  40451. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  40452. * @param {number} [srcLevel=0] - The source mip level to copy from.
  40453. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  40454. */
  40455. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  40456. this._textures.updateTexture( srcTexture );
  40457. this._textures.updateTexture( dstTexture );
  40458. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  40459. }
  40460. /**
  40461. * Reads pixel data from the given render target.
  40462. *
  40463. * @async
  40464. * @param {RenderTarget} renderTarget - The render target to read from.
  40465. * @param {number} x - The `x` coordinate of the copy region's origin.
  40466. * @param {number} y - The `y` coordinate of the copy region's origin.
  40467. * @param {number} width - The width of the copy region.
  40468. * @param {number} height - The height of the copy region.
  40469. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  40470. * @param {number} [faceIndex=0] - The active cube face index.
  40471. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  40472. */
  40473. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  40474. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  40475. }
  40476. /**
  40477. * Analyzes the given 3D object's hierarchy and builds render lists from the
  40478. * processed hierarchy.
  40479. *
  40480. * @param {Object3D} object - The 3D object to process (usually a scene).
  40481. * @param {Camera} camera - The camera the object is rendered with.
  40482. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  40483. * @param {RenderList} renderList - The current render list.
  40484. * @param {ClippingContext} clippingContext - The current clipping context.
  40485. */
  40486. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  40487. if ( object.visible === false ) return;
  40488. const visible = object.layers.test( camera.layers );
  40489. if ( visible ) {
  40490. if ( object.isGroup ) {
  40491. groupOrder = object.renderOrder;
  40492. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  40493. } else if ( object.isLOD ) {
  40494. if ( object.autoUpdate === true ) object.update( camera );
  40495. } else if ( object.isLight ) {
  40496. renderList.pushLight( object );
  40497. } else if ( object.isSprite ) {
  40498. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  40499. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  40500. if ( this.sortObjects === true ) {
  40501. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  40502. }
  40503. const { geometry, material } = object;
  40504. if ( material.visible ) {
  40505. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  40506. }
  40507. }
  40508. } else if ( object.isLineLoop ) {
  40509. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  40510. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  40511. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  40512. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  40513. const { geometry, material } = object;
  40514. if ( this.sortObjects === true ) {
  40515. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  40516. _vector4
  40517. .copy( geometry.boundingSphere.center )
  40518. .applyMatrix4( object.matrixWorld )
  40519. .applyMatrix4( _projScreenMatrix );
  40520. }
  40521. if ( Array.isArray( material ) ) {
  40522. const groups = geometry.groups;
  40523. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  40524. const group = groups[ i ];
  40525. const groupMaterial = material[ group.materialIndex ];
  40526. if ( groupMaterial && groupMaterial.visible ) {
  40527. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  40528. }
  40529. }
  40530. } else if ( material.visible ) {
  40531. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  40532. }
  40533. }
  40534. }
  40535. }
  40536. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  40537. const baseRenderList = renderList;
  40538. // replace render list
  40539. renderList = this._renderLists.get( object, camera );
  40540. renderList.begin();
  40541. baseRenderList.pushBundle( {
  40542. bundleGroup: object,
  40543. camera,
  40544. renderList,
  40545. } );
  40546. renderList.finish();
  40547. }
  40548. const children = object.children;
  40549. for ( let i = 0, l = children.length; i < l; i ++ ) {
  40550. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  40551. }
  40552. }
  40553. /**
  40554. * Renders the given render bundles.
  40555. *
  40556. * @private
  40557. * @param {Array<Object>} bundles - Array with render bundle data.
  40558. * @param {Scene} sceneRef - The scene the render bundles belong to.
  40559. * @param {LightsNode} lightsNode - The current lights node.
  40560. */
  40561. _renderBundles( bundles, sceneRef, lightsNode ) {
  40562. for ( const bundle of bundles ) {
  40563. this._renderBundle( bundle, sceneRef, lightsNode );
  40564. }
  40565. }
  40566. /**
  40567. * Renders the transparent objects from the given render lists.
  40568. *
  40569. * @private
  40570. * @param {Array<Object>} renderList - The transparent render list.
  40571. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  40572. * @param {Camera} camera - The camera the render list should be rendered with.
  40573. * @param {Scene} scene - The scene the render list belongs to.
  40574. * @param {LightsNode} lightsNode - The current lights node.
  40575. */
  40576. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  40577. if ( doublePassList.length > 0 ) {
  40578. // render back side
  40579. for ( const { material } of doublePassList ) {
  40580. material.side = BackSide;
  40581. }
  40582. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  40583. // render front side
  40584. for ( const { material } of doublePassList ) {
  40585. material.side = FrontSide;
  40586. }
  40587. this._renderObjects( renderList, camera, scene, lightsNode );
  40588. // restore
  40589. for ( const { material } of doublePassList ) {
  40590. material.side = DoubleSide;
  40591. }
  40592. } else {
  40593. this._renderObjects( renderList, camera, scene, lightsNode );
  40594. }
  40595. }
  40596. /**
  40597. * Renders the objects from the given render list.
  40598. *
  40599. * @private
  40600. * @param {Array<Object>} renderList - The render list.
  40601. * @param {Camera} camera - The camera the render list should be rendered with.
  40602. * @param {Scene} scene - The scene the render list belongs to.
  40603. * @param {LightsNode} lightsNode - The current lights node.
  40604. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  40605. */
  40606. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  40607. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  40608. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  40609. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  40610. }
  40611. }
  40612. /**
  40613. * This method represents the default render object function that manages the render lifecycle
  40614. * of the object.
  40615. *
  40616. * @param {Object3D} object - The 3D object.
  40617. * @param {Scene} scene - The scene the 3D object belongs to.
  40618. * @param {Camera} camera - The camera the object should be rendered with.
  40619. * @param {BufferGeometry} geometry - The object's geometry.
  40620. * @param {Material} material - The object's material.
  40621. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  40622. * @param {LightsNode} lightsNode - The current lights node.
  40623. * @param {?ClippingContext} clippingContext - The clipping context.
  40624. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  40625. */
  40626. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  40627. let overridePositionNode;
  40628. let overrideColorNode;
  40629. let overrideDepthNode;
  40630. //
  40631. object.onBeforeRender( this, scene, camera, geometry, material, group );
  40632. //
  40633. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  40634. const overrideMaterial = scene.overrideMaterial;
  40635. if ( material.positionNode && material.positionNode.isNode ) {
  40636. overridePositionNode = overrideMaterial.positionNode;
  40637. overrideMaterial.positionNode = material.positionNode;
  40638. }
  40639. overrideMaterial.alphaTest = material.alphaTest;
  40640. overrideMaterial.alphaMap = material.alphaMap;
  40641. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  40642. if ( overrideMaterial.isShadowPassMaterial ) {
  40643. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  40644. if ( material.depthNode && material.depthNode.isNode ) {
  40645. overrideDepthNode = overrideMaterial.depthNode;
  40646. overrideMaterial.depthNode = material.depthNode;
  40647. }
  40648. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  40649. overrideColorNode = overrideMaterial.colorNode;
  40650. overrideMaterial.colorNode = material.castShadowNode;
  40651. }
  40652. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  40653. overridePositionNode = overrideMaterial.positionNode;
  40654. overrideMaterial.positionNode = material.castShadowPositionNode;
  40655. }
  40656. }
  40657. material = overrideMaterial;
  40658. }
  40659. //
  40660. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  40661. material.side = BackSide;
  40662. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  40663. material.side = FrontSide;
  40664. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  40665. material.side = DoubleSide;
  40666. } else {
  40667. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  40668. }
  40669. //
  40670. if ( overridePositionNode !== undefined ) {
  40671. scene.overrideMaterial.positionNode = overridePositionNode;
  40672. }
  40673. if ( overrideDepthNode !== undefined ) {
  40674. scene.overrideMaterial.depthNode = overrideDepthNode;
  40675. }
  40676. if ( overrideColorNode !== undefined ) {
  40677. scene.overrideMaterial.colorNode = overrideColorNode;
  40678. }
  40679. //
  40680. object.onAfterRender( this, scene, camera, geometry, material, group );
  40681. }
  40682. /**
  40683. * This method represents the default `_handleObjectFunction` implementation which creates
  40684. * a render object from the given data and performs the draw command with the selected backend.
  40685. *
  40686. * @private
  40687. * @param {Object3D} object - The 3D object.
  40688. * @param {Material} material - The object's material.
  40689. * @param {Scene} scene - The scene the 3D object belongs to.
  40690. * @param {Camera} camera - The camera the object should be rendered with.
  40691. * @param {LightsNode} lightsNode - The current lights node.
  40692. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  40693. * @param {ClippingContext} clippingContext - The clipping context.
  40694. * @param {string} [passId] - An optional ID for identifying the pass.
  40695. */
  40696. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  40697. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  40698. renderObject.drawRange = object.geometry.drawRange;
  40699. renderObject.group = group;
  40700. //
  40701. const needsRefresh = this._nodes.needsRefresh( renderObject );
  40702. if ( needsRefresh ) {
  40703. this._nodes.updateBefore( renderObject );
  40704. this._geometries.updateForRender( renderObject );
  40705. this._nodes.updateForRender( renderObject );
  40706. this._bindings.updateForRender( renderObject );
  40707. }
  40708. this._pipelines.updateForRender( renderObject );
  40709. //
  40710. if ( this._currentRenderBundle !== null ) {
  40711. const renderBundleData = this.backend.get( this._currentRenderBundle );
  40712. renderBundleData.renderObjects.push( renderObject );
  40713. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  40714. }
  40715. this.backend.draw( renderObject, this.info );
  40716. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  40717. }
  40718. /**
  40719. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  40720. * Used in `compileAsync()`.
  40721. *
  40722. * @private
  40723. * @param {Object3D} object - The 3D object.
  40724. * @param {Material} material - The object's material.
  40725. * @param {Scene} scene - The scene the 3D object belongs to.
  40726. * @param {Camera} camera - The camera the object should be rendered with.
  40727. * @param {LightsNode} lightsNode - The current lights node.
  40728. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  40729. * @param {ClippingContext} clippingContext - The clipping context.
  40730. * @param {string} [passId] - An optional ID for identifying the pass.
  40731. */
  40732. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  40733. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  40734. renderObject.drawRange = object.geometry.drawRange;
  40735. renderObject.group = group;
  40736. //
  40737. this._nodes.updateBefore( renderObject );
  40738. this._geometries.updateForRender( renderObject );
  40739. this._nodes.updateForRender( renderObject );
  40740. this._bindings.updateForRender( renderObject );
  40741. this._pipelines.getForRender( renderObject, this._compilationPromises );
  40742. this._nodes.updateAfter( renderObject );
  40743. }
  40744. /**
  40745. * Alias for `compileAsync()`.
  40746. *
  40747. * @method
  40748. * @param {Object3D} scene - The scene or 3D object to precompile.
  40749. * @param {Camera} camera - The camera that is used to render the scene.
  40750. * @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.
  40751. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  40752. */
  40753. get compile() {
  40754. return this.compileAsync;
  40755. }
  40756. }
  40757. /**
  40758. * A binding represents the connection between a resource (like a texture, sampler
  40759. * or uniform buffer) and the resource definition in a shader stage.
  40760. *
  40761. * This module is an abstract base class for all concrete bindings types.
  40762. *
  40763. * @abstract
  40764. * @private
  40765. */
  40766. class Binding {
  40767. /**
  40768. * Constructs a new binding.
  40769. *
  40770. * @param {string} [name=''] - The binding's name.
  40771. */
  40772. constructor( name = '' ) {
  40773. /**
  40774. * The binding's name.
  40775. *
  40776. * @type {string}
  40777. */
  40778. this.name = name;
  40779. /**
  40780. * A bitmask that defines in what shader stages the
  40781. * binding's resource is accessible.
  40782. *
  40783. * @type {number}
  40784. */
  40785. this.visibility = 0;
  40786. }
  40787. /**
  40788. * Makes sure binding's resource is visible for the given shader stage.
  40789. *
  40790. * @param {number} visibility - The shader stage.
  40791. */
  40792. setVisibility( visibility ) {
  40793. this.visibility |= visibility;
  40794. }
  40795. /**
  40796. * Clones the binding.
  40797. *
  40798. * @return {Binding} The cloned binding.
  40799. */
  40800. clone() {
  40801. return Object.assign( new this.constructor(), this );
  40802. }
  40803. }
  40804. /**
  40805. * This function is usually called with the length in bytes of an array buffer.
  40806. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  40807. *
  40808. * @function
  40809. * @param {number} floatLength - The buffer length.
  40810. * @return {number} The padded length.
  40811. */
  40812. function getFloatLength( floatLength ) {
  40813. // ensure chunk size alignment (STD140 layout)
  40814. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  40815. }
  40816. /**
  40817. * Represents a buffer binding type.
  40818. *
  40819. * @private
  40820. * @abstract
  40821. * @augments Binding
  40822. */
  40823. class Buffer extends Binding {
  40824. /**
  40825. * Constructs a new buffer.
  40826. *
  40827. * @param {string} name - The buffer's name.
  40828. * @param {TypedArray} [buffer=null] - The buffer.
  40829. */
  40830. constructor( name, buffer = null ) {
  40831. super( name );
  40832. /**
  40833. * This flag can be used for type testing.
  40834. *
  40835. * @type {boolean}
  40836. * @readonly
  40837. * @default true
  40838. */
  40839. this.isBuffer = true;
  40840. /**
  40841. * The bytes per element.
  40842. *
  40843. * @type {number}
  40844. */
  40845. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  40846. /**
  40847. * A reference to the internal buffer.
  40848. *
  40849. * @private
  40850. * @type {TypedArray}
  40851. */
  40852. this._buffer = buffer;
  40853. }
  40854. /**
  40855. * The buffer's byte length.
  40856. *
  40857. * @type {number}
  40858. * @readonly
  40859. */
  40860. get byteLength() {
  40861. return getFloatLength( this._buffer.byteLength );
  40862. }
  40863. /**
  40864. * A reference to the internal buffer.
  40865. *
  40866. * @type {Float32Array}
  40867. * @readonly
  40868. */
  40869. get buffer() {
  40870. return this._buffer;
  40871. }
  40872. /**
  40873. * Updates the binding.
  40874. *
  40875. * @return {boolean} Whether the buffer has been updated and must be
  40876. * uploaded to the GPU.
  40877. */
  40878. update() {
  40879. return true;
  40880. }
  40881. }
  40882. /**
  40883. * Represents a uniform buffer binding type.
  40884. *
  40885. * @private
  40886. * @augments Buffer
  40887. */
  40888. class UniformBuffer extends Buffer {
  40889. /**
  40890. * Constructs a new uniform buffer.
  40891. *
  40892. * @param {string} name - The buffer's name.
  40893. * @param {TypedArray} [buffer=null] - The buffer.
  40894. */
  40895. constructor( name, buffer = null ) {
  40896. super( name, buffer );
  40897. /**
  40898. * This flag can be used for type testing.
  40899. *
  40900. * @type {boolean}
  40901. * @readonly
  40902. * @default true
  40903. */
  40904. this.isUniformBuffer = true;
  40905. }
  40906. }
  40907. let _id$4 = 0;
  40908. /**
  40909. * A special form of uniform buffer binding type.
  40910. * It's buffer value is managed by a node object.
  40911. *
  40912. * @private
  40913. * @augments UniformBuffer
  40914. */
  40915. class NodeUniformBuffer extends UniformBuffer {
  40916. /**
  40917. * Constructs a new node-based uniform buffer.
  40918. *
  40919. * @param {BufferNode} nodeUniform - The uniform buffer node.
  40920. * @param {UniformGroupNode} groupNode - The uniform group node.
  40921. */
  40922. constructor( nodeUniform, groupNode ) {
  40923. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  40924. /**
  40925. * The uniform buffer node.
  40926. *
  40927. * @type {BufferNode}
  40928. */
  40929. this.nodeUniform = nodeUniform;
  40930. /**
  40931. * The uniform group node.
  40932. *
  40933. * @type {UniformGroupNode}
  40934. */
  40935. this.groupNode = groupNode;
  40936. }
  40937. /**
  40938. * The uniform buffer.
  40939. *
  40940. * @type {Float32Array}
  40941. */
  40942. get buffer() {
  40943. return this.nodeUniform.value;
  40944. }
  40945. }
  40946. /**
  40947. * This class represents a uniform buffer binding but with
  40948. * an API that allows to maintain individual uniform objects.
  40949. *
  40950. * @private
  40951. * @augments UniformBuffer
  40952. */
  40953. class UniformsGroup extends UniformBuffer {
  40954. /**
  40955. * Constructs a new uniforms group.
  40956. *
  40957. * @param {string} name - The group's name.
  40958. */
  40959. constructor( name ) {
  40960. super( name );
  40961. /**
  40962. * This flag can be used for type testing.
  40963. *
  40964. * @type {boolean}
  40965. * @readonly
  40966. * @default true
  40967. */
  40968. this.isUniformsGroup = true;
  40969. /**
  40970. * An array with the raw uniform values.
  40971. *
  40972. * @private
  40973. * @type {?Array<number>}
  40974. * @default null
  40975. */
  40976. this._values = null;
  40977. /**
  40978. * An array of uniform objects.
  40979. *
  40980. * The order of uniforms in this array must match the order of uniforms in the shader.
  40981. *
  40982. * @type {Array<Uniform>}
  40983. */
  40984. this.uniforms = [];
  40985. }
  40986. /**
  40987. * Adds a uniform to this group.
  40988. *
  40989. * @param {Uniform} uniform - The uniform to add.
  40990. * @return {UniformsGroup} A reference to this group.
  40991. */
  40992. addUniform( uniform ) {
  40993. this.uniforms.push( uniform );
  40994. return this;
  40995. }
  40996. /**
  40997. * Removes a uniform from this group.
  40998. *
  40999. * @param {Uniform} uniform - The uniform to remove.
  41000. * @return {UniformsGroup} A reference to this group.
  41001. */
  41002. removeUniform( uniform ) {
  41003. const index = this.uniforms.indexOf( uniform );
  41004. if ( index !== -1 ) {
  41005. this.uniforms.splice( index, 1 );
  41006. }
  41007. return this;
  41008. }
  41009. /**
  41010. * An array with the raw uniform values.
  41011. *
  41012. * @type {Array<number>}
  41013. */
  41014. get values() {
  41015. if ( this._values === null ) {
  41016. this._values = Array.from( this.buffer );
  41017. }
  41018. return this._values;
  41019. }
  41020. /**
  41021. * A Float32 array buffer with the uniform values.
  41022. *
  41023. * @type {Float32Array}
  41024. */
  41025. get buffer() {
  41026. let buffer = this._buffer;
  41027. if ( buffer === null ) {
  41028. const byteLength = this.byteLength;
  41029. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  41030. this._buffer = buffer;
  41031. }
  41032. return buffer;
  41033. }
  41034. /**
  41035. * The byte length of the buffer with correct buffer alignment.
  41036. *
  41037. * @type {number}
  41038. */
  41039. get byteLength() {
  41040. const bytesPerElement = this.bytesPerElement;
  41041. let offset = 0; // global buffer offset in bytes
  41042. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  41043. const uniform = this.uniforms[ i ];
  41044. const boundary = uniform.boundary;
  41045. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  41046. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  41047. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  41048. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  41049. offset += chunkPadding;
  41050. // Check for chunk overflow
  41051. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  41052. // Add padding to the end of the chunk
  41053. offset += ( GPU_CHUNK_BYTES - chunkStart );
  41054. }
  41055. uniform.offset = offset / bytesPerElement;
  41056. offset += itemSize;
  41057. }
  41058. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  41059. }
  41060. /**
  41061. * Updates this group by updating each uniform object of
  41062. * the internal uniform list. The uniform objects check if their
  41063. * values has actually changed so this method only returns
  41064. * `true` if there is a real value change.
  41065. *
  41066. * @return {boolean} Whether the uniforms have been updated and
  41067. * must be uploaded to the GPU.
  41068. */
  41069. update() {
  41070. let updated = false;
  41071. for ( const uniform of this.uniforms ) {
  41072. if ( this.updateByType( uniform ) === true ) {
  41073. updated = true;
  41074. }
  41075. }
  41076. return updated;
  41077. }
  41078. /**
  41079. * Updates a given uniform by calling an update method matching
  41080. * the uniforms type.
  41081. *
  41082. * @param {Uniform} uniform - The uniform to update.
  41083. * @return {boolean} Whether the uniform has been updated or not.
  41084. */
  41085. updateByType( uniform ) {
  41086. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  41087. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  41088. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  41089. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  41090. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  41091. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  41092. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  41093. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  41094. }
  41095. /**
  41096. * Updates a given Number uniform.
  41097. *
  41098. * @param {NumberUniform} uniform - The Number uniform.
  41099. * @return {boolean} Whether the uniform has been updated or not.
  41100. */
  41101. updateNumber( uniform ) {
  41102. let updated = false;
  41103. const a = this.values;
  41104. const v = uniform.getValue();
  41105. const offset = uniform.offset;
  41106. const type = uniform.getType();
  41107. if ( a[ offset ] !== v ) {
  41108. const b = this._getBufferForType( type );
  41109. b[ offset ] = a[ offset ] = v;
  41110. updated = true;
  41111. }
  41112. return updated;
  41113. }
  41114. /**
  41115. * Updates a given Vector2 uniform.
  41116. *
  41117. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  41118. * @return {boolean} Whether the uniform has been updated or not.
  41119. */
  41120. updateVector2( uniform ) {
  41121. let updated = false;
  41122. const a = this.values;
  41123. const v = uniform.getValue();
  41124. const offset = uniform.offset;
  41125. const type = uniform.getType();
  41126. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  41127. const b = this._getBufferForType( type );
  41128. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  41129. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  41130. updated = true;
  41131. }
  41132. return updated;
  41133. }
  41134. /**
  41135. * Updates a given Vector3 uniform.
  41136. *
  41137. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  41138. * @return {boolean} Whether the uniform has been updated or not.
  41139. */
  41140. updateVector3( uniform ) {
  41141. let updated = false;
  41142. const a = this.values;
  41143. const v = uniform.getValue();
  41144. const offset = uniform.offset;
  41145. const type = uniform.getType();
  41146. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  41147. const b = this._getBufferForType( type );
  41148. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  41149. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  41150. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  41151. updated = true;
  41152. }
  41153. return updated;
  41154. }
  41155. /**
  41156. * Updates a given Vector4 uniform.
  41157. *
  41158. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  41159. * @return {boolean} Whether the uniform has been updated or not.
  41160. */
  41161. updateVector4( uniform ) {
  41162. let updated = false;
  41163. const a = this.values;
  41164. const v = uniform.getValue();
  41165. const offset = uniform.offset;
  41166. const type = uniform.getType();
  41167. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  41168. const b = this._getBufferForType( type );
  41169. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  41170. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  41171. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  41172. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  41173. updated = true;
  41174. }
  41175. return updated;
  41176. }
  41177. /**
  41178. * Updates a given Color uniform.
  41179. *
  41180. * @param {ColorUniform} uniform - The Color uniform.
  41181. * @return {boolean} Whether the uniform has been updated or not.
  41182. */
  41183. updateColor( uniform ) {
  41184. let updated = false;
  41185. const a = this.values;
  41186. const c = uniform.getValue();
  41187. const offset = uniform.offset;
  41188. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  41189. const b = this.buffer;
  41190. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  41191. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  41192. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  41193. updated = true;
  41194. }
  41195. return updated;
  41196. }
  41197. /**
  41198. * Updates a given Matrix3 uniform.
  41199. *
  41200. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  41201. * @return {boolean} Whether the uniform has been updated or not.
  41202. */
  41203. updateMatrix3( uniform ) {
  41204. let updated = false;
  41205. const a = this.values;
  41206. const e = uniform.getValue().elements;
  41207. const offset = uniform.offset;
  41208. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  41209. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  41210. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  41211. const b = this.buffer;
  41212. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  41213. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  41214. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  41215. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  41216. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  41217. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  41218. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  41219. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  41220. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  41221. updated = true;
  41222. }
  41223. return updated;
  41224. }
  41225. /**
  41226. * Updates a given Matrix4 uniform.
  41227. *
  41228. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  41229. * @return {boolean} Whether the uniform has been updated or not.
  41230. */
  41231. updateMatrix4( uniform ) {
  41232. let updated = false;
  41233. const a = this.values;
  41234. const e = uniform.getValue().elements;
  41235. const offset = uniform.offset;
  41236. if ( arraysEqual( a, e, offset ) === false ) {
  41237. const b = this.buffer;
  41238. b.set( e, offset );
  41239. setArray( a, e, offset );
  41240. updated = true;
  41241. }
  41242. return updated;
  41243. }
  41244. /**
  41245. * Returns a typed array that matches the given data type.
  41246. *
  41247. * @param {string} type - The data type.
  41248. * @return {TypedArray} The typed array.
  41249. */
  41250. _getBufferForType( type ) {
  41251. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  41252. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  41253. return this.buffer;
  41254. }
  41255. }
  41256. /**
  41257. * Sets the values of the second array to the first array.
  41258. *
  41259. * @private
  41260. * @param {TypedArray} a - The first array.
  41261. * @param {TypedArray} b - The second array.
  41262. * @param {number} offset - An index offset for the first array.
  41263. */
  41264. function setArray( a, b, offset ) {
  41265. for ( let i = 0, l = b.length; i < l; i ++ ) {
  41266. a[ offset + i ] = b[ i ];
  41267. }
  41268. }
  41269. /**
  41270. * Returns `true` if the given arrays are equal.
  41271. *
  41272. * @private
  41273. * @param {TypedArray} a - The first array.
  41274. * @param {TypedArray} b - The second array.
  41275. * @param {number} offset - An index offset for the first array.
  41276. * @return {boolean} Whether the given arrays are equal or not.
  41277. */
  41278. function arraysEqual( a, b, offset ) {
  41279. for ( let i = 0, l = b.length; i < l; i ++ ) {
  41280. if ( a[ offset + i ] !== b[ i ] ) return false;
  41281. }
  41282. return true;
  41283. }
  41284. let _id$3 = 0;
  41285. /**
  41286. * A special form of uniforms group that represents
  41287. * the individual uniforms as node-based uniforms.
  41288. *
  41289. * @private
  41290. * @augments UniformsGroup
  41291. */
  41292. class NodeUniformsGroup extends UniformsGroup {
  41293. /**
  41294. * Constructs a new node-based uniforms group.
  41295. *
  41296. * @param {string} name - The group's name.
  41297. * @param {UniformGroupNode} groupNode - The uniform group node.
  41298. */
  41299. constructor( name, groupNode ) {
  41300. super( name );
  41301. /**
  41302. * The group's ID.
  41303. *
  41304. * @type {number}
  41305. */
  41306. this.id = _id$3 ++;
  41307. /**
  41308. * The uniform group node.
  41309. *
  41310. * @type {UniformGroupNode}
  41311. */
  41312. this.groupNode = groupNode;
  41313. /**
  41314. * This flag can be used for type testing.
  41315. *
  41316. * @type {boolean}
  41317. * @readonly
  41318. * @default true
  41319. */
  41320. this.isNodeUniformsGroup = true;
  41321. }
  41322. }
  41323. /**
  41324. * Represents a sampler binding type.
  41325. *
  41326. * @private
  41327. * @augments Binding
  41328. */
  41329. class Sampler extends Binding {
  41330. /**
  41331. * Constructs a new sampler.
  41332. *
  41333. * @param {string} name - The samplers's name.
  41334. * @param {?Texture} texture - The texture this binding is referring to.
  41335. */
  41336. constructor( name, texture ) {
  41337. super( name );
  41338. /**
  41339. * The texture the sampler is referring to.
  41340. *
  41341. * @type {?Texture}
  41342. */
  41343. this.texture = texture;
  41344. /**
  41345. * The binding's version.
  41346. *
  41347. * @type {number}
  41348. */
  41349. this.version = texture ? texture.version : 0;
  41350. /**
  41351. * The binding's generation which is an additional version
  41352. * qualifier.
  41353. *
  41354. * @type {?number}
  41355. * @default null
  41356. */
  41357. this.generation = null;
  41358. /**
  41359. * This flag can be used for type testing.
  41360. *
  41361. * @type {boolean}
  41362. * @readonly
  41363. * @default true
  41364. */
  41365. this.isSampler = true;
  41366. }
  41367. /**
  41368. * Sets the texture of this sampler.
  41369. * @param {?Texture} value - The texture to set.
  41370. */
  41371. set texture( value ) {
  41372. if ( this._texture === value ) return;
  41373. const onDispose = () => {
  41374. this._texture = null;
  41375. this.generation = null;
  41376. this.version = 0;
  41377. };
  41378. if ( this._texture ) {
  41379. this._texture.removeEventListener( 'dispose', onDispose );
  41380. }
  41381. this._texture = value;
  41382. this.generation = null;
  41383. this.version = 0;
  41384. if ( this._texture ) {
  41385. this._texture.addEventListener( 'dispose', onDispose );
  41386. }
  41387. }
  41388. /**
  41389. * Gets the texture of this sampler.
  41390. * @return {?Texture} The texture.
  41391. */
  41392. get texture() {
  41393. return this._texture;
  41394. }
  41395. /**
  41396. * Updates the binding.
  41397. *
  41398. * @return {boolean} Whether the texture has been updated and must be
  41399. * uploaded to the GPU.
  41400. */
  41401. update() {
  41402. const { texture, version } = this;
  41403. if ( version !== texture.version ) {
  41404. this.version = texture.version;
  41405. return true;
  41406. }
  41407. return false;
  41408. }
  41409. clone() {
  41410. const clonedSampler = super.clone();
  41411. // fix dispose handler for cloned instances
  41412. // TODO: Find better solution, see #31747
  41413. clonedSampler._texture = null;
  41414. clonedSampler.texture = this.texture;
  41415. return clonedSampler;
  41416. }
  41417. }
  41418. let _id$2 = 0;
  41419. /**
  41420. * Represents a sampled texture binding type.
  41421. *
  41422. * @private
  41423. * @augments Sampler
  41424. */
  41425. class SampledTexture extends Sampler {
  41426. /**
  41427. * Constructs a new sampled texture.
  41428. *
  41429. * @param {string} name - The sampled texture's name.
  41430. * @param {?Texture} texture - The texture this binding is referring to.
  41431. */
  41432. constructor( name, texture ) {
  41433. super( name, texture );
  41434. /**
  41435. * This identifier.
  41436. *
  41437. * @type {number}
  41438. */
  41439. this.id = _id$2 ++;
  41440. /**
  41441. * Whether the texture is a storage texture or not.
  41442. *
  41443. * @type {boolean}
  41444. * @default false
  41445. */
  41446. this.store = false;
  41447. /**
  41448. * This flag can be used for type testing.
  41449. *
  41450. * @type {boolean}
  41451. * @readonly
  41452. * @default true
  41453. */
  41454. this.isSampledTexture = true;
  41455. }
  41456. }
  41457. /**
  41458. * A special form of sampled texture binding type.
  41459. * It's texture value is managed by a node object.
  41460. *
  41461. * @private
  41462. * @augments SampledTexture
  41463. */
  41464. class NodeSampledTexture extends SampledTexture {
  41465. /**
  41466. * Constructs a new node-based sampled texture.
  41467. *
  41468. * @param {string} name - The textures's name.
  41469. * @param {TextureNode} textureNode - The texture node.
  41470. * @param {UniformGroupNode} groupNode - The uniform group node.
  41471. * @param {?string} [access=null] - The access type.
  41472. */
  41473. constructor( name, textureNode, groupNode, access = null ) {
  41474. super( name, textureNode ? textureNode.value : null );
  41475. /**
  41476. * The texture node.
  41477. *
  41478. * @type {TextureNode}
  41479. */
  41480. this.textureNode = textureNode;
  41481. /**
  41482. * The uniform group node.
  41483. *
  41484. * @type {UniformGroupNode}
  41485. */
  41486. this.groupNode = groupNode;
  41487. /**
  41488. * The access type.
  41489. *
  41490. * @type {?string}
  41491. * @default null
  41492. */
  41493. this.access = access;
  41494. }
  41495. /**
  41496. * Updates the binding.
  41497. *
  41498. * @return {boolean} Whether the texture has been updated and must be
  41499. * uploaded to the GPU.
  41500. */
  41501. update() {
  41502. const { textureNode } = this;
  41503. if ( this.texture !== textureNode.value ) {
  41504. this.texture = textureNode.value;
  41505. return true;
  41506. }
  41507. return super.update();
  41508. }
  41509. }
  41510. /**
  41511. * A special form of sampled cube texture binding type.
  41512. * It's texture value is managed by a node object.
  41513. *
  41514. * @private
  41515. * @augments NodeSampledTexture
  41516. */
  41517. class NodeSampledCubeTexture extends NodeSampledTexture {
  41518. /**
  41519. * Constructs a new node-based sampled cube texture.
  41520. *
  41521. * @param {string} name - The textures's name.
  41522. * @param {TextureNode} textureNode - The texture node.
  41523. * @param {UniformGroupNode} groupNode - The uniform group node.
  41524. * @param {?string} [access=null] - The access type.
  41525. */
  41526. constructor( name, textureNode, groupNode, access = null ) {
  41527. super( name, textureNode, groupNode, access );
  41528. /**
  41529. * This flag can be used for type testing.
  41530. *
  41531. * @type {boolean}
  41532. * @readonly
  41533. * @default true
  41534. */
  41535. this.isSampledCubeTexture = true;
  41536. }
  41537. }
  41538. /**
  41539. * A special form of sampled 3D texture binding type.
  41540. * It's texture value is managed by a node object.
  41541. *
  41542. * @private
  41543. * @augments NodeSampledTexture
  41544. */
  41545. class NodeSampledTexture3D extends NodeSampledTexture {
  41546. /**
  41547. * Constructs a new node-based sampled 3D texture.
  41548. *
  41549. * @param {string} name - The textures's name.
  41550. * @param {TextureNode} textureNode - The texture node.
  41551. * @param {UniformGroupNode} groupNode - The uniform group node.
  41552. * @param {?string} [access=null] - The access type.
  41553. */
  41554. constructor( name, textureNode, groupNode, access = null ) {
  41555. super( name, textureNode, groupNode, access );
  41556. /**
  41557. * This flag can be used for type testing.
  41558. *
  41559. * @type {boolean}
  41560. * @readonly
  41561. * @default true
  41562. */
  41563. this.isSampledTexture3D = true;
  41564. }
  41565. }
  41566. const glslMethods = {
  41567. textureDimensions: 'textureSize',
  41568. equals: 'equal',
  41569. bitcast_float_int: 'floatBitsToInt',
  41570. bitcast_int_float: 'intBitsToFloat',
  41571. bitcast_uint_float: 'uintBitsToFloat',
  41572. bitcast_float_uint: 'floatBitsToUint',
  41573. };
  41574. const precisionLib = {
  41575. low: 'lowp',
  41576. medium: 'mediump',
  41577. high: 'highp'
  41578. };
  41579. const supports$1 = {
  41580. swizzleAssign: true,
  41581. storageBuffer: false
  41582. };
  41583. const interpolationTypeMap = {
  41584. perspective: 'smooth',
  41585. linear: 'noperspective'
  41586. };
  41587. const interpolationModeMap = {
  41588. 'centroid': 'centroid'
  41589. };
  41590. const defaultPrecisions = `
  41591. precision highp float;
  41592. precision highp int;
  41593. precision highp sampler2D;
  41594. precision highp sampler3D;
  41595. precision highp samplerCube;
  41596. precision highp sampler2DArray;
  41597. precision highp usampler2D;
  41598. precision highp usampler3D;
  41599. precision highp usamplerCube;
  41600. precision highp usampler2DArray;
  41601. precision highp isampler2D;
  41602. precision highp isampler3D;
  41603. precision highp isamplerCube;
  41604. precision highp isampler2DArray;
  41605. precision lowp sampler2DShadow;
  41606. precision lowp sampler2DArrayShadow;
  41607. precision lowp samplerCubeShadow;
  41608. `;
  41609. /**
  41610. * A node builder targeting GLSL.
  41611. *
  41612. * This module generates GLSL shader code from node materials and also
  41613. * generates the respective bindings and vertex buffer definitions. These
  41614. * data are later used by the renderer to create render and compute pipelines
  41615. * for render objects.
  41616. *
  41617. * @augments NodeBuilder
  41618. */
  41619. class GLSLNodeBuilder extends NodeBuilder {
  41620. /**
  41621. * Constructs a new GLSL node builder renderer.
  41622. *
  41623. * @param {Object3D} object - The 3D object.
  41624. * @param {Renderer} renderer - The renderer.
  41625. */
  41626. constructor( object, renderer ) {
  41627. super( object, renderer, new GLSLNodeParser() );
  41628. /**
  41629. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  41630. * another dictionary which manages UBOs per group ('render','frame','object').
  41631. *
  41632. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  41633. */
  41634. this.uniformGroups = {};
  41635. /**
  41636. * An array that holds objects defining the varying and attribute data in
  41637. * context of Transform Feedback.
  41638. *
  41639. * @type {Array<Object<string,AttributeNode|string>>}
  41640. */
  41641. this.transforms = [];
  41642. /**
  41643. * A dictionary that holds for each shader stage a Map of used extensions.
  41644. *
  41645. * @type {Object<string,Map<string,Object>>}
  41646. */
  41647. this.extensions = {};
  41648. /**
  41649. * A dictionary that holds for each shader stage an Array of used builtins.
  41650. *
  41651. * @type {Object<string,Array<string>>}
  41652. */
  41653. this.builtins = { vertex: [], fragment: [], compute: [] };
  41654. }
  41655. /**
  41656. * Checks if the given texture requires a manual conversion to the working color space.
  41657. *
  41658. * @param {Texture} texture - The texture to check.
  41659. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  41660. */
  41661. needsToWorkingColorSpace( texture ) {
  41662. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  41663. }
  41664. /**
  41665. * Returns the native shader method name for a given generic name.
  41666. *
  41667. * @param {string} method - The method name to resolve.
  41668. * @return {string} The resolved GLSL method name.
  41669. */
  41670. getMethod( method ) {
  41671. return glslMethods[ method ] || method;
  41672. }
  41673. /**
  41674. * Returns the bitcast method name for a given input and outputType.
  41675. *
  41676. * @param {string} type - The output type to bitcast to.
  41677. * @param {string} inputType - The input type of the.
  41678. * @return {string} The resolved WGSL bitcast invocation.
  41679. */
  41680. getBitcastMethod( type, inputType ) {
  41681. return glslMethods[ `bitcast_${ inputType }_${ type }` ];
  41682. }
  41683. /**
  41684. * Returns the native snippet for a ternary operation.
  41685. *
  41686. * @param {string} condSnippet - The condition determining which expression gets resolved.
  41687. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  41688. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  41689. * @return {string} The resolved method name.
  41690. */
  41691. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  41692. return `${condSnippet} ? ${ifSnippet} : ${elseSnippet}`;
  41693. }
  41694. /**
  41695. * Returns the output struct name. Not relevant for GLSL.
  41696. *
  41697. * @return {string}
  41698. */
  41699. getOutputStructName() {
  41700. return '';
  41701. }
  41702. /**
  41703. * Builds the given shader node.
  41704. *
  41705. * @param {ShaderNodeInternal} shaderNode - The shader node.
  41706. * @return {string} The GLSL function code.
  41707. */
  41708. buildFunctionCode( shaderNode ) {
  41709. const layout = shaderNode.layout;
  41710. const flowData = this.flowShaderNode( shaderNode );
  41711. const parameters = [];
  41712. for ( const input of layout.inputs ) {
  41713. parameters.push( this.getType( input.type ) + ' ' + input.name );
  41714. }
  41715. //
  41716. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  41717. ${ flowData.vars }
  41718. ${ flowData.code }
  41719. return ${ flowData.result };
  41720. }`;
  41721. //
  41722. return code;
  41723. }
  41724. /**
  41725. * Setups the Pixel Buffer Object (PBO) for the given storage
  41726. * buffer node.
  41727. *
  41728. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  41729. */
  41730. setupPBO( storageBufferNode ) {
  41731. const attribute = storageBufferNode.value;
  41732. if ( attribute.pbo === undefined ) {
  41733. const originalArray = attribute.array;
  41734. const numElements = attribute.count * attribute.itemSize;
  41735. const { itemSize } = attribute;
  41736. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  41737. let format = isInteger ? RedIntegerFormat : RedFormat;
  41738. if ( itemSize === 2 ) {
  41739. format = isInteger ? RGIntegerFormat : RGFormat;
  41740. } else if ( itemSize === 3 ) {
  41741. format = isInteger ? RGBIntegerFormat : RGBFormat;
  41742. } else if ( itemSize === 4 ) {
  41743. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  41744. }
  41745. const typeMap = {
  41746. Float32Array: FloatType,
  41747. Uint8Array: UnsignedByteType,
  41748. Uint16Array: UnsignedShortType,
  41749. Uint32Array: UnsignedIntType,
  41750. Int8Array: ByteType,
  41751. Int16Array: ShortType,
  41752. Int32Array: IntType,
  41753. Uint8ClampedArray: UnsignedByteType,
  41754. };
  41755. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  41756. let height = Math.ceil( ( numElements / itemSize ) / width );
  41757. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  41758. const newSize = width * height * itemSize;
  41759. const newArray = new originalArray.constructor( newSize );
  41760. newArray.set( originalArray, 0 );
  41761. attribute.array = newArray;
  41762. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  41763. pboTexture.needsUpdate = true;
  41764. pboTexture.isPBOTexture = true;
  41765. const pbo = new TextureNode( pboTexture, null, null );
  41766. pbo.setPrecision( 'high' );
  41767. attribute.pboNode = pbo;
  41768. attribute.pbo = pbo.value;
  41769. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  41770. }
  41771. }
  41772. /**
  41773. * Returns a GLSL snippet that represents the property name of the given node.
  41774. *
  41775. * @param {Node} node - The node.
  41776. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  41777. * @return {string} The property name.
  41778. */
  41779. getPropertyName( node, shaderStage = this.shaderStage ) {
  41780. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  41781. return shaderStage.charAt( 0 ) + '_' + node.name;
  41782. }
  41783. return super.getPropertyName( node, shaderStage );
  41784. }
  41785. /**
  41786. * Setups the Pixel Buffer Object (PBO) for the given storage
  41787. * buffer node.
  41788. *
  41789. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  41790. * @return {string} The property name.
  41791. */
  41792. generatePBO( storageArrayElementNode ) {
  41793. const { node, indexNode } = storageArrayElementNode;
  41794. const attribute = node.value;
  41795. if ( this.renderer.backend.has( attribute ) ) {
  41796. const attributeData = this.renderer.backend.get( attribute );
  41797. attributeData.pbo = attribute.pbo;
  41798. }
  41799. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.nodeName );
  41800. const textureName = this.getPropertyName( nodeUniform );
  41801. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  41802. const indexSnippet = indexNode.build( this, 'uint' );
  41803. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  41804. let propertyName = elementNodeData.propertyName;
  41805. if ( propertyName === undefined ) {
  41806. // property element
  41807. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  41808. propertyName = this.getPropertyName( nodeVar );
  41809. // property size
  41810. const bufferNodeData = this.getDataFromNode( node );
  41811. let propertySizeName = bufferNodeData.propertySizeName;
  41812. if ( propertySizeName === undefined ) {
  41813. propertySizeName = propertyName + 'Size';
  41814. this.getVarFromNode( node, propertySizeName, 'uint' );
  41815. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  41816. bufferNodeData.propertySizeName = propertySizeName;
  41817. }
  41818. //
  41819. const { itemSize } = attribute;
  41820. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  41821. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  41822. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, null, '0' );
  41823. //
  41824. let prefix = 'vec4';
  41825. if ( attribute.pbo.type === UnsignedIntType ) {
  41826. prefix = 'uvec4';
  41827. } else if ( attribute.pbo.type === IntType ) {
  41828. prefix = 'ivec4';
  41829. }
  41830. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  41831. elementNodeData.propertyName = propertyName;
  41832. }
  41833. return propertyName;
  41834. }
  41835. /**
  41836. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  41837. *
  41838. * @param {?Texture} texture - The texture.
  41839. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41840. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41841. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  41842. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  41843. * @param {string} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  41844. * @return {string} The GLSL snippet.
  41845. */
  41846. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, offsetSnippet, levelSnippet = '0' ) {
  41847. let snippet;
  41848. if ( depthSnippet ) {
  41849. if ( offsetSnippet ) {
  41850. snippet = `texelFetchOffset( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet }, ${ offsetSnippet } )`;
  41851. } else {
  41852. snippet = `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  41853. }
  41854. } else {
  41855. if ( offsetSnippet ) {
  41856. snippet = `texelFetchOffset( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  41857. } else {
  41858. snippet = `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  41859. }
  41860. }
  41861. if ( texture !== null && texture.isDepthTexture ) {
  41862. snippet += '.x';
  41863. }
  41864. return snippet;
  41865. }
  41866. /**
  41867. * Generates the GLSL snippet for sampling/loading the given texture.
  41868. *
  41869. * @param {Texture} texture - The texture.
  41870. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41871. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41872. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  41873. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  41874. * @return {string} The GLSL snippet.
  41875. */
  41876. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet ) {
  41877. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  41878. if ( texture.isDepthTexture ) {
  41879. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } ).x`;
  41880. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  41881. }
  41882. if ( offsetSnippet ) return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet } )`;
  41883. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  41884. }
  41885. /**
  41886. * Generates the GLSL snippet when sampling textures with explicit mip level.
  41887. *
  41888. * @param {Texture} texture - The texture.
  41889. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41890. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41891. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  41892. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  41893. * @return {string} The GLSL snippet.
  41894. */
  41895. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, offsetSnippet ) {
  41896. if ( offsetSnippet ) {
  41897. return `textureLodOffset( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  41898. }
  41899. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  41900. }
  41901. /**
  41902. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  41903. *
  41904. * @param {Texture} texture - The texture.
  41905. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41906. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41907. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  41908. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  41909. * @return {string} The GLSL snippet.
  41910. */
  41911. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, offsetSnippet ) {
  41912. if ( offsetSnippet ) {
  41913. return `textureOffset( ${ textureProperty }, ${ uvSnippet }, ${ offsetSnippet }, ${ biasSnippet } )`;
  41914. }
  41915. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  41916. }
  41917. /**
  41918. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  41919. *
  41920. * @param {Texture} texture - The texture.
  41921. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41922. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41923. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  41924. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  41925. * @return {string} The GLSL snippet.
  41926. */
  41927. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, offsetSnippet ) {
  41928. if ( offsetSnippet ) {
  41929. return `textureGradOffset( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  41930. }
  41931. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  41932. }
  41933. /**
  41934. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  41935. * against a reference value.
  41936. *
  41937. * @param {Texture} texture - The texture.
  41938. * @param {string} textureProperty - The name of the texture uniform in the shader.
  41939. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  41940. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  41941. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  41942. * @param {?string} offsetSnippet - A GLSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  41943. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  41944. * @return {string} The GLSL snippet.
  41945. */
  41946. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  41947. if ( shaderStage === 'fragment' ) {
  41948. if ( depthSnippet ) {
  41949. if ( offsetSnippet ) {
  41950. return `textureOffset( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  41951. }
  41952. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  41953. }
  41954. if ( offsetSnippet ) {
  41955. return `textureOffset( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ), ${ offsetSnippet } )`;
  41956. }
  41957. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  41958. } else {
  41959. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  41960. }
  41961. }
  41962. /**
  41963. * Returns the variables of the given shader stage as a GLSL string.
  41964. *
  41965. * @param {string} shaderStage - The shader stage.
  41966. * @return {string} The GLSL snippet that defines the variables.
  41967. */
  41968. getVars( shaderStage ) {
  41969. const snippets = [];
  41970. const vars = this.vars[ shaderStage ];
  41971. if ( vars !== undefined ) {
  41972. for ( const variable of vars ) {
  41973. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  41974. }
  41975. }
  41976. return snippets.join( '\n\t' );
  41977. }
  41978. /**
  41979. * Returns the uniforms of the given shader stage as a GLSL string.
  41980. *
  41981. * @param {string} shaderStage - The shader stage.
  41982. * @return {string} The GLSL snippet that defines the uniforms.
  41983. */
  41984. getUniforms( shaderStage ) {
  41985. const uniforms = this.uniforms[ shaderStage ];
  41986. const bindingSnippets = [];
  41987. const uniformGroups = {};
  41988. for ( const uniform of uniforms ) {
  41989. let snippet = null;
  41990. let group = false;
  41991. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  41992. const texture = uniform.node.value;
  41993. let typePrefix = '';
  41994. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  41995. if ( texture.type === UnsignedIntType ) {
  41996. typePrefix = 'u';
  41997. } else if ( texture.type === IntType ) {
  41998. typePrefix = 'i';
  41999. }
  42000. }
  42001. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  42002. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  42003. } else if ( texture.compareFunction ) {
  42004. if ( texture.isArrayTexture === true ) {
  42005. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  42006. } else {
  42007. snippet = `sampler2DShadow ${ uniform.name };`;
  42008. }
  42009. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  42010. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  42011. } else {
  42012. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  42013. }
  42014. } else if ( uniform.type === 'cubeTexture' ) {
  42015. snippet = `samplerCube ${ uniform.name };`;
  42016. } else if ( uniform.type === 'buffer' ) {
  42017. const bufferNode = uniform.node;
  42018. const bufferType = this.getType( bufferNode.bufferType );
  42019. const bufferCount = bufferNode.bufferCount;
  42020. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  42021. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  42022. } else {
  42023. const vectorType = this.getVectorType( uniform.type );
  42024. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  42025. group = true;
  42026. }
  42027. const precision = uniform.node.precision;
  42028. if ( precision !== null ) {
  42029. snippet = precisionLib[ precision ] + ' ' + snippet;
  42030. }
  42031. if ( group ) {
  42032. snippet = '\t' + snippet;
  42033. const groupName = uniform.groupNode.name;
  42034. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  42035. groupSnippets.push( snippet );
  42036. } else {
  42037. snippet = 'uniform ' + snippet;
  42038. bindingSnippets.push( snippet );
  42039. }
  42040. }
  42041. let output = '';
  42042. for ( const name in uniformGroups ) {
  42043. const groupSnippets = uniformGroups[ name ];
  42044. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  42045. }
  42046. output += bindingSnippets.join( '\n' );
  42047. return output;
  42048. }
  42049. /**
  42050. * Returns the type for a given buffer attribute.
  42051. *
  42052. * @param {BufferAttribute} attribute - The buffer attribute.
  42053. * @return {string} The type.
  42054. */
  42055. getTypeFromAttribute( attribute ) {
  42056. let nodeType = super.getTypeFromAttribute( attribute );
  42057. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  42058. let dataAttribute = attribute;
  42059. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  42060. const array = dataAttribute.array;
  42061. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  42062. nodeType = nodeType.slice( 1 );
  42063. }
  42064. }
  42065. return nodeType;
  42066. }
  42067. /**
  42068. * Returns the shader attributes of the given shader stage as a GLSL string.
  42069. *
  42070. * @param {string} shaderStage - The shader stage.
  42071. * @return {string} The GLSL snippet that defines the shader attributes.
  42072. */
  42073. getAttributes( shaderStage ) {
  42074. let snippet = '';
  42075. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  42076. const attributes = this.getAttributesArray();
  42077. let location = 0;
  42078. for ( const attribute of attributes ) {
  42079. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  42080. }
  42081. }
  42082. return snippet;
  42083. }
  42084. /**
  42085. * Returns the members of the given struct type node as a GLSL string.
  42086. *
  42087. * @param {StructTypeNode} struct - The struct type node.
  42088. * @return {string} The GLSL snippet that defines the struct members.
  42089. */
  42090. getStructMembers( struct ) {
  42091. const snippets = [];
  42092. for ( const member of struct.members ) {
  42093. snippets.push( `\t${ member.type } ${ member.name };` );
  42094. }
  42095. return snippets.join( '\n' );
  42096. }
  42097. /**
  42098. * Returns the structs of the given shader stage as a GLSL string.
  42099. *
  42100. * @param {string} shaderStage - The shader stage.
  42101. * @return {string} The GLSL snippet that defines the structs.
  42102. */
  42103. getStructs( shaderStage ) {
  42104. const snippets = [];
  42105. const structs = this.structs[ shaderStage ];
  42106. const outputSnippet = [];
  42107. for ( const struct of structs ) {
  42108. if ( struct.output ) {
  42109. for ( const member of struct.members ) {
  42110. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  42111. }
  42112. } else {
  42113. let snippet = 'struct ' + struct.name + ' {\n';
  42114. snippet += this.getStructMembers( struct );
  42115. snippet += '\n};\n';
  42116. snippets.push( snippet );
  42117. }
  42118. }
  42119. if ( outputSnippet.length === 0 ) {
  42120. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  42121. }
  42122. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  42123. }
  42124. /**
  42125. * Returns the varyings of the given shader stage as a GLSL string.
  42126. *
  42127. * @param {string} shaderStage - The shader stage.
  42128. * @return {string} The GLSL snippet that defines the varyings.
  42129. */
  42130. getVaryings( shaderStage ) {
  42131. let snippet = '';
  42132. const varyings = this.varyings;
  42133. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  42134. for ( const varying of varyings ) {
  42135. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  42136. const type = this.getType( varying.type );
  42137. if ( varying.needsInterpolation ) {
  42138. if ( varying.interpolationType ) {
  42139. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  42140. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  42141. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  42142. } else {
  42143. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  42144. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  42145. }
  42146. } else {
  42147. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  42148. }
  42149. }
  42150. } else if ( shaderStage === 'fragment' ) {
  42151. for ( const varying of varyings ) {
  42152. if ( varying.needsInterpolation ) {
  42153. const type = this.getType( varying.type );
  42154. if ( varying.interpolationType ) {
  42155. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  42156. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  42157. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  42158. } else {
  42159. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  42160. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  42161. }
  42162. }
  42163. }
  42164. }
  42165. for ( const builtin of this.builtins[ shaderStage ] ) {
  42166. snippet += `${builtin};\n`;
  42167. }
  42168. return snippet;
  42169. }
  42170. /**
  42171. * Returns the vertex index builtin.
  42172. *
  42173. * @return {string} The vertex index.
  42174. */
  42175. getVertexIndex() {
  42176. return 'uint( gl_VertexID )';
  42177. }
  42178. /**
  42179. * Returns the instance index builtin.
  42180. *
  42181. * @return {string} The instance index.
  42182. */
  42183. getInstanceIndex() {
  42184. return 'uint( gl_InstanceID )';
  42185. }
  42186. /**
  42187. * Returns the invocation local index builtin.
  42188. *
  42189. * @return {string} The invocation local index.
  42190. */
  42191. getInvocationLocalIndex() {
  42192. const workgroupSize = this.object.workgroupSize;
  42193. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  42194. return `uint( gl_InstanceID ) % ${size}u`;
  42195. }
  42196. /**
  42197. * Returns the draw index builtin.
  42198. *
  42199. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  42200. */
  42201. getDrawIndex() {
  42202. const extensions = this.renderer.backend.extensions;
  42203. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  42204. return 'uint( gl_DrawID )';
  42205. }
  42206. return null;
  42207. }
  42208. /**
  42209. * Returns the front facing builtin.
  42210. *
  42211. * @return {string} The front facing builtin.
  42212. */
  42213. getFrontFacing() {
  42214. return 'gl_FrontFacing';
  42215. }
  42216. /**
  42217. * Returns the frag coord builtin.
  42218. *
  42219. * @return {string} The frag coord builtin.
  42220. */
  42221. getFragCoord() {
  42222. return 'gl_FragCoord.xy';
  42223. }
  42224. /**
  42225. * Returns the frag depth builtin.
  42226. *
  42227. * @return {string} The frag depth builtin.
  42228. */
  42229. getFragDepth() {
  42230. return 'gl_FragDepth';
  42231. }
  42232. /**
  42233. * Enables the given extension.
  42234. *
  42235. * @param {string} name - The extension name.
  42236. * @param {string} behavior - The extension behavior.
  42237. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  42238. */
  42239. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  42240. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  42241. if ( map.has( name ) === false ) {
  42242. map.set( name, {
  42243. name,
  42244. behavior
  42245. } );
  42246. }
  42247. }
  42248. /**
  42249. * Returns the enabled extensions of the given shader stage as a GLSL string.
  42250. *
  42251. * @param {string} shaderStage - The shader stage.
  42252. * @return {string} The GLSL snippet that defines the enabled extensions.
  42253. */
  42254. getExtensions( shaderStage ) {
  42255. const snippets = [];
  42256. if ( shaderStage === 'vertex' ) {
  42257. const ext = this.renderer.backend.extensions;
  42258. const isBatchedMesh = this.object.isBatchedMesh;
  42259. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  42260. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  42261. }
  42262. }
  42263. const extensions = this.extensions[ shaderStage ];
  42264. if ( extensions !== undefined ) {
  42265. for ( const { name, behavior } of extensions.values() ) {
  42266. snippets.push( `#extension ${name} : ${behavior}` );
  42267. }
  42268. }
  42269. return snippets.join( '\n' );
  42270. }
  42271. /**
  42272. * Returns the clip distances builtin.
  42273. *
  42274. * @return {string} The clip distances builtin.
  42275. */
  42276. getClipDistance() {
  42277. return 'gl_ClipDistance';
  42278. }
  42279. /**
  42280. * Whether the requested feature is available or not.
  42281. *
  42282. * @param {string} name - The requested feature.
  42283. * @return {boolean} Whether the requested feature is supported or not.
  42284. */
  42285. isAvailable( name ) {
  42286. let result = supports$1[ name ];
  42287. if ( result === undefined ) {
  42288. let extensionName;
  42289. result = false;
  42290. switch ( name ) {
  42291. case 'float32Filterable':
  42292. extensionName = 'OES_texture_float_linear';
  42293. break;
  42294. case 'clipDistance':
  42295. extensionName = 'WEBGL_clip_cull_distance';
  42296. break;
  42297. }
  42298. if ( extensionName !== undefined ) {
  42299. const extensions = this.renderer.backend.extensions;
  42300. if ( extensions.has( extensionName ) ) {
  42301. extensions.get( extensionName );
  42302. result = true;
  42303. }
  42304. }
  42305. supports$1[ name ] = result;
  42306. }
  42307. return result;
  42308. }
  42309. /**
  42310. * Whether to flip texture data along its vertical axis or not.
  42311. *
  42312. * @return {boolean} Returns always `true` in context of GLSL.
  42313. */
  42314. isFlipY() {
  42315. return true;
  42316. }
  42317. /**
  42318. * Enables hardware clipping.
  42319. *
  42320. * @param {string} planeCount - The clipping plane count.
  42321. */
  42322. enableHardwareClipping( planeCount ) {
  42323. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  42324. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  42325. }
  42326. /**
  42327. * Enables multiview.
  42328. */
  42329. enableMultiview() {
  42330. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  42331. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  42332. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  42333. }
  42334. /**
  42335. * Registers a transform in context of Transform Feedback.
  42336. *
  42337. * @param {string} varyingName - The varying name.
  42338. * @param {AttributeNode} attributeNode - The attribute node.
  42339. */
  42340. registerTransform( varyingName, attributeNode ) {
  42341. this.transforms.push( { varyingName, attributeNode } );
  42342. }
  42343. /**
  42344. * Returns the transforms of the given shader stage as a GLSL string.
  42345. *
  42346. * @param {string} shaderStage - The shader stage.
  42347. * @return {string} The GLSL snippet that defines the transforms.
  42348. */
  42349. getTransforms( /* shaderStage */ ) {
  42350. const transforms = this.transforms;
  42351. let snippet = '';
  42352. for ( let i = 0; i < transforms.length; i ++ ) {
  42353. const transform = transforms[ i ];
  42354. const attributeName = this.getPropertyName( transform.attributeNode );
  42355. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  42356. }
  42357. return snippet;
  42358. }
  42359. /**
  42360. * Returns a GLSL struct based on the given name and variables.
  42361. *
  42362. * @private
  42363. * @param {string} name - The struct name.
  42364. * @param {string} vars - The struct variables.
  42365. * @return {string} The GLSL snippet representing a struct.
  42366. */
  42367. _getGLSLUniformStruct( name, vars ) {
  42368. return `
  42369. layout( std140 ) uniform ${name} {
  42370. ${vars}
  42371. };`;
  42372. }
  42373. /**
  42374. * Returns a GLSL vertex shader based on the given shader data.
  42375. *
  42376. * @private
  42377. * @param {Object} shaderData - The shader data.
  42378. * @return {string} The vertex shader.
  42379. */
  42380. _getGLSLVertexCode( shaderData ) {
  42381. return `#version 300 es
  42382. ${ this.getSignature() }
  42383. // extensions
  42384. ${shaderData.extensions}
  42385. // precision
  42386. ${ defaultPrecisions }
  42387. // uniforms
  42388. ${shaderData.uniforms}
  42389. // varyings
  42390. ${shaderData.varyings}
  42391. // attributes
  42392. ${shaderData.attributes}
  42393. // codes
  42394. ${shaderData.codes}
  42395. void main() {
  42396. // vars
  42397. ${shaderData.vars}
  42398. // transforms
  42399. ${shaderData.transforms}
  42400. // flow
  42401. ${shaderData.flow}
  42402. gl_PointSize = 1.0;
  42403. }
  42404. `;
  42405. }
  42406. /**
  42407. * Returns a GLSL fragment shader based on the given shader data.
  42408. *
  42409. * @private
  42410. * @param {Object} shaderData - The shader data.
  42411. * @return {string} The vertex shader.
  42412. */
  42413. _getGLSLFragmentCode( shaderData ) {
  42414. return `#version 300 es
  42415. ${ this.getSignature() }
  42416. // extensions
  42417. ${shaderData.extensions}
  42418. // precision
  42419. ${ defaultPrecisions }
  42420. // uniforms
  42421. ${shaderData.uniforms}
  42422. // varyings
  42423. ${shaderData.varyings}
  42424. // codes
  42425. ${shaderData.codes}
  42426. // structs
  42427. ${shaderData.structs}
  42428. void main() {
  42429. // vars
  42430. ${shaderData.vars}
  42431. // flow
  42432. ${shaderData.flow}
  42433. }
  42434. `;
  42435. }
  42436. /**
  42437. * Controls the code build of the shader stages.
  42438. */
  42439. buildCode() {
  42440. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  42441. this.sortBindingGroups();
  42442. for ( const shaderStage in shadersData ) {
  42443. let flow = '// code\n\n';
  42444. flow += this.flowCode[ shaderStage ];
  42445. const flowNodes = this.flowNodes[ shaderStage ];
  42446. const mainNode = flowNodes[ flowNodes.length - 1 ];
  42447. for ( const node of flowNodes ) {
  42448. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  42449. const slotName = node.name;
  42450. if ( slotName ) {
  42451. if ( flow.length > 0 ) flow += '\n';
  42452. flow += `\t// flow -> ${ slotName }\n\t`;
  42453. }
  42454. flow += `${ flowSlotData.code }\n\t`;
  42455. if ( node === mainNode && shaderStage !== 'compute' ) {
  42456. flow += '// result\n\t';
  42457. if ( shaderStage === 'vertex' ) {
  42458. flow += 'gl_Position = ';
  42459. flow += `${ flowSlotData.result };`;
  42460. } else if ( shaderStage === 'fragment' ) {
  42461. if ( ! node.outputNode.isOutputStructNode ) {
  42462. flow += 'fragColor = ';
  42463. flow += `${ flowSlotData.result };`;
  42464. }
  42465. }
  42466. }
  42467. }
  42468. const stageData = shadersData[ shaderStage ];
  42469. stageData.extensions = this.getExtensions( shaderStage );
  42470. stageData.uniforms = this.getUniforms( shaderStage );
  42471. stageData.attributes = this.getAttributes( shaderStage );
  42472. stageData.varyings = this.getVaryings( shaderStage );
  42473. stageData.vars = this.getVars( shaderStage );
  42474. stageData.structs = this.getStructs( shaderStage );
  42475. stageData.codes = this.getCodes( shaderStage );
  42476. stageData.transforms = this.getTransforms( shaderStage );
  42477. stageData.flow = flow;
  42478. }
  42479. if ( this.material !== null ) {
  42480. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  42481. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  42482. } else {
  42483. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  42484. }
  42485. }
  42486. /**
  42487. * This method is one of the more important ones since it's responsible
  42488. * for generating a matching binding instance for the given uniform node.
  42489. *
  42490. * These bindings are later used in the renderer to create bind groups
  42491. * and layouts.
  42492. *
  42493. * @param {UniformNode} node - The uniform node.
  42494. * @param {string} type - The node data type.
  42495. * @param {string} shaderStage - The shader stage.
  42496. * @param {?string} [name=null] - An optional uniform name.
  42497. * @return {NodeUniform} The node uniform object.
  42498. */
  42499. getUniformFromNode( node, type, shaderStage, name = null ) {
  42500. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  42501. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  42502. let uniformGPU = nodeData.uniformGPU;
  42503. if ( uniformGPU === undefined ) {
  42504. const group = node.groupNode;
  42505. const groupName = group.name;
  42506. const bindings = this.getBindGroupArray( groupName, shaderStage );
  42507. if ( type === 'texture' ) {
  42508. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  42509. bindings.push( uniformGPU );
  42510. } else if ( type === 'cubeTexture' ) {
  42511. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  42512. bindings.push( uniformGPU );
  42513. } else if ( type === 'texture3D' ) {
  42514. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  42515. bindings.push( uniformGPU );
  42516. } else if ( type === 'buffer' ) {
  42517. node.name = `NodeBuffer_${ node.id }`;
  42518. uniformNode.name = `buffer${ node.id }`;
  42519. const buffer = new NodeUniformBuffer( node, group );
  42520. buffer.name = node.name;
  42521. bindings.push( buffer );
  42522. uniformGPU = buffer;
  42523. } else {
  42524. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  42525. let uniformsGroup = uniformsStage[ groupName ];
  42526. if ( uniformsGroup === undefined ) {
  42527. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  42528. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  42529. uniformsStage[ groupName ] = uniformsGroup;
  42530. bindings.push( uniformsGroup );
  42531. }
  42532. uniformGPU = this.getNodeUniform( uniformNode, type );
  42533. uniformsGroup.addUniform( uniformGPU );
  42534. }
  42535. nodeData.uniformGPU = uniformGPU;
  42536. }
  42537. return uniformNode;
  42538. }
  42539. }
  42540. let _vector2 = null;
  42541. let _color4 = null;
  42542. /**
  42543. * Most of the rendering related logic is implemented in the
  42544. * {@link Renderer} module and related management components.
  42545. * Sometimes it is required though to execute commands which are
  42546. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  42547. * This abstract base class defines an interface that encapsulates
  42548. * all backend-related logic. Derived classes for each backend must
  42549. * implement the interface.
  42550. *
  42551. * @abstract
  42552. * @private
  42553. */
  42554. class Backend {
  42555. /**
  42556. * Constructs a new backend.
  42557. *
  42558. * @param {Object} parameters - An object holding parameters for the backend.
  42559. */
  42560. constructor( parameters = {} ) {
  42561. /**
  42562. * The parameters of the backend.
  42563. *
  42564. * @type {Object}
  42565. */
  42566. this.parameters = Object.assign( {}, parameters );
  42567. /**
  42568. * This weak map holds backend-specific data of objects
  42569. * like textures, attributes or render targets.
  42570. *
  42571. * @type {WeakMap<Object, Object>}
  42572. */
  42573. this.data = new WeakMap();
  42574. /**
  42575. * A reference to the renderer.
  42576. *
  42577. * @type {?Renderer}
  42578. * @default null
  42579. */
  42580. this.renderer = null;
  42581. /**
  42582. * A reference to the canvas element the renderer is drawing to.
  42583. *
  42584. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  42585. * @default null
  42586. */
  42587. this.domElement = null;
  42588. /**
  42589. * A reference to the timestamp query pool.
  42590. *
  42591. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  42592. */
  42593. this.timestampQueryPool = {
  42594. 'render': null,
  42595. 'compute': null
  42596. };
  42597. /**
  42598. * Whether to track timestamps with a Timestamp Query API or not.
  42599. *
  42600. * @type {boolean}
  42601. * @default false
  42602. */
  42603. this.trackTimestamp = ( parameters.trackTimestamp === true );
  42604. }
  42605. /**
  42606. * Initializes the backend so it is ready for usage. Concrete backends
  42607. * are supposed to implement their rendering context creation and related
  42608. * operations in this method.
  42609. *
  42610. * @async
  42611. * @param {Renderer} renderer - The renderer.
  42612. * @return {Promise} A Promise that resolves when the backend has been initialized.
  42613. */
  42614. async init( renderer ) {
  42615. this.renderer = renderer;
  42616. }
  42617. /**
  42618. * The coordinate system of the backend.
  42619. *
  42620. * @abstract
  42621. * @type {number}
  42622. * @readonly
  42623. */
  42624. get coordinateSystem() {}
  42625. // render context
  42626. /**
  42627. * This method is executed at the beginning of a render call and
  42628. * can be used by the backend to prepare the state for upcoming
  42629. * draw calls.
  42630. *
  42631. * @abstract
  42632. * @param {RenderContext} renderContext - The render context.
  42633. */
  42634. beginRender( /*renderContext*/ ) {}
  42635. /**
  42636. * This method is executed at the end of a render call and
  42637. * can be used by the backend to finalize work after draw
  42638. * calls.
  42639. *
  42640. * @abstract
  42641. * @param {RenderContext} renderContext - The render context.
  42642. */
  42643. finishRender( /*renderContext*/ ) {}
  42644. /**
  42645. * This method is executed at the beginning of a compute call and
  42646. * can be used by the backend to prepare the state for upcoming
  42647. * compute tasks.
  42648. *
  42649. * @abstract
  42650. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  42651. */
  42652. beginCompute( /*computeGroup*/ ) {}
  42653. /**
  42654. * This method is executed at the end of a compute call and
  42655. * can be used by the backend to finalize work after compute
  42656. * tasks.
  42657. *
  42658. * @abstract
  42659. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  42660. */
  42661. finishCompute( /*computeGroup*/ ) {}
  42662. // render object
  42663. /**
  42664. * Executes a draw command for the given render object.
  42665. *
  42666. * @abstract
  42667. * @param {RenderObject} renderObject - The render object to draw.
  42668. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  42669. */
  42670. draw( /*renderObject, info*/ ) { }
  42671. // compute node
  42672. /**
  42673. * Executes a compute command for the given compute node.
  42674. *
  42675. * @abstract
  42676. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  42677. * @param {Node} computeNode - The compute node.
  42678. * @param {Array<BindGroup>} bindings - The bindings.
  42679. * @param {ComputePipeline} computePipeline - The compute pipeline.
  42680. */
  42681. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  42682. // program
  42683. /**
  42684. * Creates a shader program from the given programmable stage.
  42685. *
  42686. * @abstract
  42687. * @param {ProgrammableStage} program - The programmable stage.
  42688. */
  42689. createProgram( /*program*/ ) { }
  42690. /**
  42691. * Destroys the shader program of the given programmable stage.
  42692. *
  42693. * @abstract
  42694. * @param {ProgrammableStage} program - The programmable stage.
  42695. */
  42696. destroyProgram( /*program*/ ) { }
  42697. // bindings
  42698. /**
  42699. * Creates bindings from the given bind group definition.
  42700. *
  42701. * @abstract
  42702. * @param {BindGroup} bindGroup - The bind group.
  42703. * @param {Array<BindGroup>} bindings - Array of bind groups.
  42704. * @param {number} cacheIndex - The cache index.
  42705. * @param {number} version - The version.
  42706. */
  42707. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  42708. /**
  42709. * Updates the given bind group definition.
  42710. *
  42711. * @abstract
  42712. * @param {BindGroup} bindGroup - The bind group.
  42713. * @param {Array<BindGroup>} bindings - Array of bind groups.
  42714. * @param {number} cacheIndex - The cache index.
  42715. * @param {number} version - The version.
  42716. */
  42717. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  42718. /**
  42719. * Updates a buffer binding.
  42720. *
  42721. * @abstract
  42722. * @param {Buffer} binding - The buffer binding to update.
  42723. */
  42724. updateBinding( /*binding*/ ) { }
  42725. // pipeline
  42726. /**
  42727. * Creates a render pipeline for the given render object.
  42728. *
  42729. * @abstract
  42730. * @param {RenderObject} renderObject - The render object.
  42731. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  42732. */
  42733. createRenderPipeline( /*renderObject, promises*/ ) { }
  42734. /**
  42735. * Creates a compute pipeline for the given compute node.
  42736. *
  42737. * @abstract
  42738. * @param {ComputePipeline} computePipeline - The compute pipeline.
  42739. * @param {Array<BindGroup>} bindings - The bindings.
  42740. */
  42741. createComputePipeline( /*computePipeline, bindings*/ ) { }
  42742. // cache key
  42743. /**
  42744. * Returns `true` if the render pipeline requires an update.
  42745. *
  42746. * @abstract
  42747. * @param {RenderObject} renderObject - The render object.
  42748. * @return {boolean} Whether the render pipeline requires an update or not.
  42749. */
  42750. needsRenderUpdate( /*renderObject*/ ) { }
  42751. /**
  42752. * Returns a cache key that is used to identify render pipelines.
  42753. *
  42754. * @abstract
  42755. * @param {RenderObject} renderObject - The render object.
  42756. * @return {string} The cache key.
  42757. */
  42758. getRenderCacheKey( /*renderObject*/ ) { }
  42759. // node builder
  42760. /**
  42761. * Returns a node builder for the given render object.
  42762. *
  42763. * @abstract
  42764. * @param {RenderObject} renderObject - The render object.
  42765. * @param {Renderer} renderer - The renderer.
  42766. * @return {NodeBuilder} The node builder.
  42767. */
  42768. createNodeBuilder( /*renderObject, renderer*/ ) { }
  42769. // textures
  42770. /**
  42771. * Creates a GPU sampler for the given texture.
  42772. *
  42773. * @abstract
  42774. * @param {Texture} texture - The texture to create the sampler for.
  42775. */
  42776. createSampler( /*texture*/ ) { }
  42777. /**
  42778. * Destroys the GPU sampler for the given texture.
  42779. *
  42780. * @abstract
  42781. * @param {Texture} texture - The texture to destroy the sampler for.
  42782. */
  42783. destroySampler( /*texture*/ ) {}
  42784. /**
  42785. * Creates a default texture for the given texture that can be used
  42786. * as a placeholder until the actual texture is ready for usage.
  42787. *
  42788. * @abstract
  42789. * @param {Texture} texture - The texture to create a default texture for.
  42790. */
  42791. createDefaultTexture( /*texture*/ ) { }
  42792. /**
  42793. * Defines a texture on the GPU for the given texture object.
  42794. *
  42795. * @abstract
  42796. * @param {Texture} texture - The texture.
  42797. * @param {Object} [options={}] - Optional configuration parameter.
  42798. */
  42799. createTexture( /*texture, options={}*/ ) { }
  42800. /**
  42801. * Uploads the updated texture data to the GPU.
  42802. *
  42803. * @abstract
  42804. * @param {Texture} texture - The texture.
  42805. * @param {Object} [options={}] - Optional configuration parameter.
  42806. */
  42807. updateTexture( /*texture, options = {}*/ ) { }
  42808. /**
  42809. * Generates mipmaps for the given texture.
  42810. *
  42811. * @abstract
  42812. * @param {Texture} texture - The texture.
  42813. */
  42814. generateMipmaps( /*texture*/ ) { }
  42815. /**
  42816. * Destroys the GPU data for the given texture object.
  42817. *
  42818. * @abstract
  42819. * @param {Texture} texture - The texture.
  42820. */
  42821. destroyTexture( /*texture*/ ) { }
  42822. /**
  42823. * Returns texture data as a typed array.
  42824. *
  42825. * @abstract
  42826. * @async
  42827. * @param {Texture} texture - The texture to copy.
  42828. * @param {number} x - The x coordinate of the copy origin.
  42829. * @param {number} y - The y coordinate of the copy origin.
  42830. * @param {number} width - The width of the copy.
  42831. * @param {number} height - The height of the copy.
  42832. * @param {number} faceIndex - The face index.
  42833. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  42834. */
  42835. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  42836. /**
  42837. * Copies data of the given source texture to the given destination texture.
  42838. *
  42839. * @abstract
  42840. * @param {Texture} srcTexture - The source texture.
  42841. * @param {Texture} dstTexture - The destination texture.
  42842. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  42843. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  42844. * @param {number} [srcLevel=0] - The source mip level to copy from.
  42845. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  42846. */
  42847. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  42848. /**
  42849. * Copies the current bound framebuffer to the given texture.
  42850. *
  42851. * @abstract
  42852. * @param {Texture} texture - The destination texture.
  42853. * @param {RenderContext} renderContext - The render context.
  42854. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  42855. */
  42856. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  42857. // attributes
  42858. /**
  42859. * Creates the GPU buffer of a shader attribute.
  42860. *
  42861. * @abstract
  42862. * @param {BufferAttribute} attribute - The buffer attribute.
  42863. */
  42864. createAttribute( /*attribute*/ ) { }
  42865. /**
  42866. * Creates the GPU buffer of an indexed shader attribute.
  42867. *
  42868. * @abstract
  42869. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  42870. */
  42871. createIndexAttribute( /*attribute*/ ) { }
  42872. /**
  42873. * Creates the GPU buffer of a storage attribute.
  42874. *
  42875. * @abstract
  42876. * @param {BufferAttribute} attribute - The buffer attribute.
  42877. */
  42878. createStorageAttribute( /*attribute*/ ) { }
  42879. /**
  42880. * Updates the GPU buffer of a shader attribute.
  42881. *
  42882. * @abstract
  42883. * @param {BufferAttribute} attribute - The buffer attribute to update.
  42884. */
  42885. updateAttribute( /*attribute*/ ) { }
  42886. /**
  42887. * Destroys the GPU buffer of a shader attribute.
  42888. *
  42889. * @abstract
  42890. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  42891. */
  42892. destroyAttribute( /*attribute*/ ) { }
  42893. // canvas
  42894. /**
  42895. * Returns the backend's rendering context.
  42896. *
  42897. * @abstract
  42898. * @return {Object} The rendering context.
  42899. */
  42900. getContext() { }
  42901. /**
  42902. * Backends can use this method if they have to run
  42903. * logic when the renderer gets resized.
  42904. *
  42905. * @abstract
  42906. */
  42907. updateSize() { }
  42908. /**
  42909. * Updates the viewport with the values from the given render context.
  42910. *
  42911. * @abstract
  42912. * @param {RenderContext} renderContext - The render context.
  42913. */
  42914. updateViewport( /*renderContext*/ ) {}
  42915. // utils
  42916. /**
  42917. * Returns a unique identifier for the given render context that can be used
  42918. * to allocate resources like occlusion queries or timestamp queries.
  42919. *
  42920. * @param {RenderContext|ComputeNode} abstractRenderContext - The render context.
  42921. * @return {string} The unique identifier.
  42922. */
  42923. getTimestampUID( abstractRenderContext ) {
  42924. const contextData = this.get( abstractRenderContext );
  42925. let uid = abstractRenderContext.isComputeNode === true ? 'c' : 'r';
  42926. uid += ':' + contextData.frameCalls + ':' + abstractRenderContext.id;
  42927. return uid;
  42928. }
  42929. /**
  42930. * Returns `true` if the given 3D object is fully occluded by other
  42931. * 3D objects in the scene. Backends must implement this method by using
  42932. * a Occlusion Query API.
  42933. *
  42934. * @abstract
  42935. * @param {RenderContext} renderContext - The render context.
  42936. * @param {Object3D} object - The 3D object to test.
  42937. * @return {boolean} Whether the 3D object is fully occluded or not.
  42938. */
  42939. isOccluded( /*renderContext, object*/ ) {}
  42940. /**
  42941. * Resolves the time stamp for the given render context and type.
  42942. *
  42943. * @async
  42944. * @abstract
  42945. * @param {string} [type='render'] - The type of the time stamp.
  42946. * @return {Promise<number>} A Promise that resolves with the time stamp.
  42947. */
  42948. async resolveTimestampsAsync( type = 'render' ) {
  42949. if ( ! this.trackTimestamp ) {
  42950. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  42951. return;
  42952. }
  42953. const queryPool = this.timestampQueryPool[ type ];
  42954. if ( ! queryPool ) {
  42955. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  42956. return;
  42957. }
  42958. const duration = await queryPool.resolveQueriesAsync();
  42959. this.renderer.info[ type ].timestamp = duration;
  42960. return duration;
  42961. }
  42962. /**
  42963. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  42964. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  42965. *
  42966. * @async
  42967. * @abstract
  42968. * @return {Promise} A Promise that resolves when synchronization has been finished.
  42969. */
  42970. async waitForGPU() {}
  42971. /**
  42972. * This method performs a readback operation by moving buffer data from
  42973. * a storage buffer attribute from the GPU to the CPU.
  42974. *
  42975. * @async
  42976. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  42977. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  42978. */
  42979. async getArrayBufferAsync( /* attribute */ ) {}
  42980. /**
  42981. * Checks if the given feature is supported by the backend.
  42982. *
  42983. * @async
  42984. * @abstract
  42985. * @param {string} name - The feature's name.
  42986. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  42987. */
  42988. async hasFeatureAsync( /*name*/ ) { }
  42989. /**
  42990. * Checks if the given feature is supported by the backend.
  42991. *
  42992. * @abstract
  42993. * @param {string} name - The feature's name.
  42994. * @return {boolean} Whether the feature is supported or not.
  42995. */
  42996. hasFeature( /*name*/ ) {}
  42997. /**
  42998. * Returns the maximum anisotropy texture filtering value.
  42999. *
  43000. * @abstract
  43001. * @return {number} The maximum anisotropy texture filtering value.
  43002. */
  43003. getMaxAnisotropy() {}
  43004. /**
  43005. * Returns the drawing buffer size.
  43006. *
  43007. * @return {Vector2} The drawing buffer size.
  43008. */
  43009. getDrawingBufferSize() {
  43010. _vector2 = _vector2 || new Vector2();
  43011. return this.renderer.getDrawingBufferSize( _vector2 );
  43012. }
  43013. /**
  43014. * Defines the scissor test.
  43015. *
  43016. * @abstract
  43017. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  43018. */
  43019. setScissorTest( /*boolean*/ ) { }
  43020. /**
  43021. * Returns the clear color and alpha into a single
  43022. * color object.
  43023. *
  43024. * @return {Color4} The clear color.
  43025. */
  43026. getClearColor() {
  43027. const renderer = this.renderer;
  43028. _color4 = _color4 || new Color4();
  43029. renderer.getClearColor( _color4 );
  43030. _color4.getRGB( _color4 );
  43031. return _color4;
  43032. }
  43033. /**
  43034. * Returns the DOM element. If no DOM element exists, the backend
  43035. * creates a new one.
  43036. *
  43037. * @return {HTMLCanvasElement} The DOM element.
  43038. */
  43039. getDomElement() {
  43040. let domElement = this.domElement;
  43041. if ( domElement === null ) {
  43042. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  43043. // OffscreenCanvas does not have setAttribute, see #22811
  43044. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  43045. this.domElement = domElement;
  43046. }
  43047. return domElement;
  43048. }
  43049. /**
  43050. * Sets a dictionary for the given object into the
  43051. * internal data structure.
  43052. *
  43053. * @param {Object} object - The object.
  43054. * @param {Object} value - The dictionary to set.
  43055. */
  43056. set( object, value ) {
  43057. this.data.set( object, value );
  43058. }
  43059. /**
  43060. * Returns the dictionary for the given object.
  43061. *
  43062. * @param {Object} object - The object.
  43063. * @return {Object} The object's dictionary.
  43064. */
  43065. get( object ) {
  43066. let map = this.data.get( object );
  43067. if ( map === undefined ) {
  43068. map = {};
  43069. this.data.set( object, map );
  43070. }
  43071. return map;
  43072. }
  43073. /**
  43074. * Checks if the given object has a dictionary
  43075. * with data defined.
  43076. *
  43077. * @param {Object} object - The object.
  43078. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  43079. */
  43080. has( object ) {
  43081. return this.data.has( object );
  43082. }
  43083. /**
  43084. * Deletes an object from the internal data structure.
  43085. *
  43086. * @param {Object} object - The object to delete.
  43087. */
  43088. delete( object ) {
  43089. this.data.delete( object );
  43090. }
  43091. /**
  43092. * Frees internal resources.
  43093. *
  43094. * @abstract
  43095. */
  43096. dispose() { }
  43097. }
  43098. let _id$1 = 0;
  43099. /**
  43100. * This module is internally used in context of compute shaders.
  43101. * This type of shader is not natively supported in WebGL 2 and
  43102. * thus implemented via Transform Feedback. `DualAttributeData`
  43103. * manages the related data.
  43104. *
  43105. * @private
  43106. */
  43107. class DualAttributeData {
  43108. constructor( attributeData, dualBuffer ) {
  43109. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  43110. this.type = attributeData.type;
  43111. this.bufferType = attributeData.bufferType;
  43112. this.pbo = attributeData.pbo;
  43113. this.byteLength = attributeData.byteLength;
  43114. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  43115. this.version = attributeData.version;
  43116. this.isInteger = attributeData.isInteger;
  43117. this.activeBufferIndex = 0;
  43118. this.baseId = attributeData.id;
  43119. }
  43120. get id() {
  43121. return `${ this.baseId }|${ this.activeBufferIndex }`;
  43122. }
  43123. get bufferGPU() {
  43124. return this.buffers[ this.activeBufferIndex ];
  43125. }
  43126. get transformBuffer() {
  43127. return this.buffers[ this.activeBufferIndex ^ 1 ];
  43128. }
  43129. switchBuffers() {
  43130. this.activeBufferIndex ^= 1;
  43131. }
  43132. }
  43133. /**
  43134. * A WebGL 2 backend utility module for managing shader attributes.
  43135. *
  43136. * @private
  43137. */
  43138. class WebGLAttributeUtils {
  43139. /**
  43140. * Constructs a new utility object.
  43141. *
  43142. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43143. */
  43144. constructor( backend ) {
  43145. /**
  43146. * A reference to the WebGL 2 backend.
  43147. *
  43148. * @type {WebGLBackend}
  43149. */
  43150. this.backend = backend;
  43151. }
  43152. /**
  43153. * Creates the GPU buffer for the given buffer attribute.
  43154. *
  43155. * @param {BufferAttribute} attribute - The buffer attribute.
  43156. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  43157. */
  43158. createAttribute( attribute, bufferType ) {
  43159. const backend = this.backend;
  43160. const { gl } = backend;
  43161. const array = attribute.array;
  43162. const usage = attribute.usage || gl.STATIC_DRAW;
  43163. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  43164. const bufferData = backend.get( bufferAttribute );
  43165. let bufferGPU = bufferData.bufferGPU;
  43166. if ( bufferGPU === undefined ) {
  43167. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  43168. bufferData.bufferGPU = bufferGPU;
  43169. bufferData.bufferType = bufferType;
  43170. bufferData.version = bufferAttribute.version;
  43171. }
  43172. //attribute.onUploadCallback();
  43173. let type;
  43174. if ( array instanceof Float32Array ) {
  43175. type = gl.FLOAT;
  43176. } else if ( typeof Float16Array !== 'undefined' && array instanceof Float16Array ) {
  43177. type = gl.HALF_FLOAT;
  43178. } else if ( array instanceof Uint16Array ) {
  43179. if ( attribute.isFloat16BufferAttribute ) {
  43180. type = gl.HALF_FLOAT;
  43181. } else {
  43182. type = gl.UNSIGNED_SHORT;
  43183. }
  43184. } else if ( array instanceof Int16Array ) {
  43185. type = gl.SHORT;
  43186. } else if ( array instanceof Uint32Array ) {
  43187. type = gl.UNSIGNED_INT;
  43188. } else if ( array instanceof Int32Array ) {
  43189. type = gl.INT;
  43190. } else if ( array instanceof Int8Array ) {
  43191. type = gl.BYTE;
  43192. } else if ( array instanceof Uint8Array ) {
  43193. type = gl.UNSIGNED_BYTE;
  43194. } else if ( array instanceof Uint8ClampedArray ) {
  43195. type = gl.UNSIGNED_BYTE;
  43196. } else {
  43197. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  43198. }
  43199. let attributeData = {
  43200. bufferGPU,
  43201. bufferType,
  43202. type,
  43203. byteLength: array.byteLength,
  43204. bytesPerElement: array.BYTES_PER_ELEMENT,
  43205. version: attribute.version,
  43206. pbo: attribute.pbo,
  43207. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  43208. id: _id$1 ++
  43209. };
  43210. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  43211. // create buffer for transform feedback use
  43212. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  43213. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  43214. }
  43215. backend.set( attribute, attributeData );
  43216. }
  43217. /**
  43218. * Updates the GPU buffer of the given buffer attribute.
  43219. *
  43220. * @param {BufferAttribute} attribute - The buffer attribute.
  43221. */
  43222. updateAttribute( attribute ) {
  43223. const backend = this.backend;
  43224. const { gl } = backend;
  43225. const array = attribute.array;
  43226. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  43227. const bufferData = backend.get( bufferAttribute );
  43228. const bufferType = bufferData.bufferType;
  43229. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  43230. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  43231. if ( updateRanges.length === 0 ) {
  43232. // Not using update ranges
  43233. gl.bufferSubData( bufferType, 0, array );
  43234. } else {
  43235. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  43236. const range = updateRanges[ i ];
  43237. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  43238. array, range.start, range.count );
  43239. }
  43240. bufferAttribute.clearUpdateRanges();
  43241. }
  43242. gl.bindBuffer( bufferType, null );
  43243. bufferData.version = bufferAttribute.version;
  43244. }
  43245. /**
  43246. * Destroys the GPU buffer of the given buffer attribute.
  43247. *
  43248. * @param {BufferAttribute} attribute - The buffer attribute.
  43249. */
  43250. destroyAttribute( attribute ) {
  43251. const backend = this.backend;
  43252. const { gl } = backend;
  43253. if ( attribute.isInterleavedBufferAttribute ) {
  43254. backend.delete( attribute.data );
  43255. }
  43256. const attributeData = backend.get( attribute );
  43257. gl.deleteBuffer( attributeData.bufferGPU );
  43258. backend.delete( attribute );
  43259. }
  43260. /**
  43261. * This method performs a readback operation by moving buffer data from
  43262. * a storage buffer attribute from the GPU to the CPU.
  43263. *
  43264. * @async
  43265. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  43266. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  43267. */
  43268. async getArrayBufferAsync( attribute ) {
  43269. const backend = this.backend;
  43270. const { gl } = backend;
  43271. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  43272. const { bufferGPU } = backend.get( bufferAttribute );
  43273. const array = attribute.array;
  43274. const byteLength = array.byteLength;
  43275. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  43276. const writeBuffer = gl.createBuffer();
  43277. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  43278. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  43279. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  43280. await backend.utils._clientWaitAsync();
  43281. const dstBuffer = new attribute.array.constructor( array.length );
  43282. // Ensure the buffer is bound before reading
  43283. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  43284. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  43285. gl.deleteBuffer( writeBuffer );
  43286. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  43287. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  43288. return dstBuffer.buffer;
  43289. }
  43290. /**
  43291. * Creates a WebGL buffer with the given data.
  43292. *
  43293. * @private
  43294. * @param {WebGL2RenderingContext} gl - The rendering context.
  43295. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  43296. * @param {TypedArray} array - The array of the buffer attribute.
  43297. * @param {GLenum} usage - The usage.
  43298. * @return {WebGLBuffer} The WebGL buffer.
  43299. */
  43300. _createBuffer( gl, bufferType, array, usage ) {
  43301. const bufferGPU = gl.createBuffer();
  43302. gl.bindBuffer( bufferType, bufferGPU );
  43303. gl.bufferData( bufferType, array, usage );
  43304. gl.bindBuffer( bufferType, null );
  43305. return bufferGPU;
  43306. }
  43307. }
  43308. let equationToGL, factorToGL;
  43309. /**
  43310. * A WebGL 2 backend utility module for managing the WebGL state.
  43311. *
  43312. * The major goal of this module is to reduce the number of state changes
  43313. * by caching the WEbGL state with a series of variables. In this way, the
  43314. * renderer only executes state change commands when necessary which
  43315. * improves the overall performance.
  43316. *
  43317. * @private
  43318. */
  43319. class WebGLState {
  43320. /**
  43321. * Constructs a new utility object.
  43322. *
  43323. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43324. */
  43325. constructor( backend ) {
  43326. /**
  43327. * A reference to the WebGL 2 backend.
  43328. *
  43329. * @type {WebGLBackend}
  43330. */
  43331. this.backend = backend;
  43332. /**
  43333. * A reference to the rendering context.
  43334. *
  43335. * @type {WebGL2RenderingContext}
  43336. */
  43337. this.gl = this.backend.gl;
  43338. // Below properties are intended to cache
  43339. // the WebGL state and are not explicitly
  43340. // documented for convenience reasons.
  43341. this.enabled = {};
  43342. this.currentFlipSided = null;
  43343. this.currentCullFace = null;
  43344. this.currentProgram = null;
  43345. this.currentBlendingEnabled = false;
  43346. this.currentBlending = null;
  43347. this.currentBlendSrc = null;
  43348. this.currentBlendDst = null;
  43349. this.currentBlendSrcAlpha = null;
  43350. this.currentBlendDstAlpha = null;
  43351. this.currentPremultipledAlpha = null;
  43352. this.currentPolygonOffsetFactor = null;
  43353. this.currentPolygonOffsetUnits = null;
  43354. this.currentColorMask = null;
  43355. this.currentDepthFunc = null;
  43356. this.currentDepthMask = null;
  43357. this.currentStencilFunc = null;
  43358. this.currentStencilRef = null;
  43359. this.currentStencilFuncMask = null;
  43360. this.currentStencilFail = null;
  43361. this.currentStencilZFail = null;
  43362. this.currentStencilZPass = null;
  43363. this.currentStencilMask = null;
  43364. this.currentLineWidth = null;
  43365. this.currentClippingPlanes = 0;
  43366. this.currentVAO = null;
  43367. this.currentIndex = null;
  43368. this.currentBoundFramebuffers = {};
  43369. this.currentDrawbuffers = new WeakMap();
  43370. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  43371. this.currentTextureSlot = null;
  43372. this.currentBoundTextures = {};
  43373. this.currentBoundBufferBases = {};
  43374. this._init();
  43375. }
  43376. /**
  43377. * Inits the state of the utility.
  43378. *
  43379. * @private
  43380. */
  43381. _init() {
  43382. const gl = this.gl;
  43383. // Store only WebGL constants here.
  43384. equationToGL = {
  43385. [ AddEquation ]: gl.FUNC_ADD,
  43386. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  43387. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  43388. };
  43389. factorToGL = {
  43390. [ ZeroFactor ]: gl.ZERO,
  43391. [ OneFactor ]: gl.ONE,
  43392. [ SrcColorFactor ]: gl.SRC_COLOR,
  43393. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  43394. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  43395. [ DstColorFactor ]: gl.DST_COLOR,
  43396. [ DstAlphaFactor ]: gl.DST_ALPHA,
  43397. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  43398. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  43399. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  43400. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  43401. };
  43402. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  43403. const viewportParam = gl.getParameter( gl.VIEWPORT );
  43404. this.currentScissor = new Vector4().fromArray( scissorParam );
  43405. this.currentViewport = new Vector4().fromArray( viewportParam );
  43406. this._tempVec4 = new Vector4();
  43407. }
  43408. /**
  43409. * Enables the given WebGL capability.
  43410. *
  43411. * This method caches the capability state so
  43412. * `gl.enable()` is only called when necessary.
  43413. *
  43414. * @param {GLenum} id - The capability to enable.
  43415. */
  43416. enable( id ) {
  43417. const { enabled } = this;
  43418. if ( enabled[ id ] !== true ) {
  43419. this.gl.enable( id );
  43420. enabled[ id ] = true;
  43421. }
  43422. }
  43423. /**
  43424. * Disables the given WebGL capability.
  43425. *
  43426. * This method caches the capability state so
  43427. * `gl.disable()` is only called when necessary.
  43428. *
  43429. * @param {GLenum} id - The capability to enable.
  43430. */
  43431. disable( id ) {
  43432. const { enabled } = this;
  43433. if ( enabled[ id ] !== false ) {
  43434. this.gl.disable( id );
  43435. enabled[ id ] = false;
  43436. }
  43437. }
  43438. /**
  43439. * Specifies whether polygons are front- or back-facing
  43440. * by setting the winding orientation.
  43441. *
  43442. * This method caches the state so `gl.frontFace()` is only
  43443. * called when necessary.
  43444. *
  43445. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  43446. */
  43447. setFlipSided( flipSided ) {
  43448. if ( this.currentFlipSided !== flipSided ) {
  43449. const { gl } = this;
  43450. if ( flipSided ) {
  43451. gl.frontFace( gl.CW );
  43452. } else {
  43453. gl.frontFace( gl.CCW );
  43454. }
  43455. this.currentFlipSided = flipSided;
  43456. }
  43457. }
  43458. /**
  43459. * Specifies whether or not front- and/or back-facing
  43460. * polygons can be culled.
  43461. *
  43462. * This method caches the state so `gl.cullFace()` is only
  43463. * called when necessary.
  43464. *
  43465. * @param {number} cullFace - Defines which polygons are candidates for culling.
  43466. */
  43467. setCullFace( cullFace ) {
  43468. const { gl } = this;
  43469. if ( cullFace !== CullFaceNone ) {
  43470. this.enable( gl.CULL_FACE );
  43471. if ( cullFace !== this.currentCullFace ) {
  43472. if ( cullFace === CullFaceBack ) {
  43473. gl.cullFace( gl.BACK );
  43474. } else if ( cullFace === CullFaceFront ) {
  43475. gl.cullFace( gl.FRONT );
  43476. } else {
  43477. gl.cullFace( gl.FRONT_AND_BACK );
  43478. }
  43479. }
  43480. } else {
  43481. this.disable( gl.CULL_FACE );
  43482. }
  43483. this.currentCullFace = cullFace;
  43484. }
  43485. /**
  43486. * Specifies the width of line primitives.
  43487. *
  43488. * This method caches the state so `gl.lineWidth()` is only
  43489. * called when necessary.
  43490. *
  43491. * @param {number} width - The line width.
  43492. */
  43493. setLineWidth( width ) {
  43494. const { currentLineWidth, gl } = this;
  43495. if ( width !== currentLineWidth ) {
  43496. gl.lineWidth( width );
  43497. this.currentLineWidth = width;
  43498. }
  43499. }
  43500. /**
  43501. * Defines the blending.
  43502. *
  43503. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  43504. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  43505. *
  43506. * @param {number} blending - The blending type.
  43507. * @param {number} blendEquation - The blending equation.
  43508. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  43509. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  43510. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  43511. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  43512. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  43513. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  43514. */
  43515. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  43516. const { gl } = this;
  43517. if ( blending === NoBlending ) {
  43518. if ( this.currentBlendingEnabled === true ) {
  43519. this.disable( gl.BLEND );
  43520. this.currentBlendingEnabled = false;
  43521. }
  43522. return;
  43523. }
  43524. if ( this.currentBlendingEnabled === false ) {
  43525. this.enable( gl.BLEND );
  43526. this.currentBlendingEnabled = true;
  43527. }
  43528. if ( blending !== CustomBlending ) {
  43529. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  43530. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  43531. gl.blendEquation( gl.FUNC_ADD );
  43532. this.currentBlendEquation = AddEquation;
  43533. this.currentBlendEquationAlpha = AddEquation;
  43534. }
  43535. if ( premultipliedAlpha ) {
  43536. switch ( blending ) {
  43537. case NormalBlending:
  43538. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  43539. break;
  43540. case AdditiveBlending:
  43541. gl.blendFunc( gl.ONE, gl.ONE );
  43542. break;
  43543. case SubtractiveBlending:
  43544. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  43545. break;
  43546. case MultiplyBlending:
  43547. gl.blendFuncSeparate( gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ZERO, gl.ONE );
  43548. break;
  43549. default:
  43550. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  43551. break;
  43552. }
  43553. } else {
  43554. switch ( blending ) {
  43555. case NormalBlending:
  43556. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  43557. break;
  43558. case AdditiveBlending:
  43559. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE );
  43560. break;
  43561. case SubtractiveBlending:
  43562. console.error( 'THREE.WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true' );
  43563. break;
  43564. case MultiplyBlending:
  43565. console.error( 'THREE.WebGLState: MultiplyBlending requires material.premultipliedAlpha = true' );
  43566. break;
  43567. default:
  43568. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  43569. break;
  43570. }
  43571. }
  43572. this.currentBlendSrc = null;
  43573. this.currentBlendDst = null;
  43574. this.currentBlendSrcAlpha = null;
  43575. this.currentBlendDstAlpha = null;
  43576. this.currentBlending = blending;
  43577. this.currentPremultipledAlpha = premultipliedAlpha;
  43578. }
  43579. return;
  43580. }
  43581. // custom blending
  43582. blendEquationAlpha = blendEquationAlpha || blendEquation;
  43583. blendSrcAlpha = blendSrcAlpha || blendSrc;
  43584. blendDstAlpha = blendDstAlpha || blendDst;
  43585. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  43586. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  43587. this.currentBlendEquation = blendEquation;
  43588. this.currentBlendEquationAlpha = blendEquationAlpha;
  43589. }
  43590. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  43591. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  43592. this.currentBlendSrc = blendSrc;
  43593. this.currentBlendDst = blendDst;
  43594. this.currentBlendSrcAlpha = blendSrcAlpha;
  43595. this.currentBlendDstAlpha = blendDstAlpha;
  43596. }
  43597. this.currentBlending = blending;
  43598. this.currentPremultipledAlpha = false;
  43599. }
  43600. /**
  43601. * Specifies whether colors can be written when rendering
  43602. * into a framebuffer or not.
  43603. *
  43604. * This method caches the state so `gl.colorMask()` is only
  43605. * called when necessary.
  43606. *
  43607. * @param {boolean} colorMask - The color mask.
  43608. */
  43609. setColorMask( colorMask ) {
  43610. if ( this.currentColorMask !== colorMask ) {
  43611. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  43612. this.currentColorMask = colorMask;
  43613. }
  43614. }
  43615. /**
  43616. * Specifies whether the depth test is enabled or not.
  43617. *
  43618. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  43619. */
  43620. setDepthTest( depthTest ) {
  43621. const { gl } = this;
  43622. if ( depthTest ) {
  43623. this.enable( gl.DEPTH_TEST );
  43624. } else {
  43625. this.disable( gl.DEPTH_TEST );
  43626. }
  43627. }
  43628. /**
  43629. * Specifies whether depth values can be written when rendering
  43630. * into a framebuffer or not.
  43631. *
  43632. * This method caches the state so `gl.depthMask()` is only
  43633. * called when necessary.
  43634. *
  43635. * @param {boolean} depthMask - The depth mask.
  43636. */
  43637. setDepthMask( depthMask ) {
  43638. if ( this.currentDepthMask !== depthMask ) {
  43639. this.gl.depthMask( depthMask );
  43640. this.currentDepthMask = depthMask;
  43641. }
  43642. }
  43643. /**
  43644. * Specifies the depth compare function.
  43645. *
  43646. * This method caches the state so `gl.depthFunc()` is only
  43647. * called when necessary.
  43648. *
  43649. * @param {number} depthFunc - The depth compare function.
  43650. */
  43651. setDepthFunc( depthFunc ) {
  43652. if ( this.currentDepthFunc !== depthFunc ) {
  43653. const { gl } = this;
  43654. switch ( depthFunc ) {
  43655. case NeverDepth:
  43656. gl.depthFunc( gl.NEVER );
  43657. break;
  43658. case AlwaysDepth:
  43659. gl.depthFunc( gl.ALWAYS );
  43660. break;
  43661. case LessDepth:
  43662. gl.depthFunc( gl.LESS );
  43663. break;
  43664. case LessEqualDepth:
  43665. gl.depthFunc( gl.LEQUAL );
  43666. break;
  43667. case EqualDepth:
  43668. gl.depthFunc( gl.EQUAL );
  43669. break;
  43670. case GreaterEqualDepth:
  43671. gl.depthFunc( gl.GEQUAL );
  43672. break;
  43673. case GreaterDepth:
  43674. gl.depthFunc( gl.GREATER );
  43675. break;
  43676. case NotEqualDepth:
  43677. gl.depthFunc( gl.NOTEQUAL );
  43678. break;
  43679. default:
  43680. gl.depthFunc( gl.LEQUAL );
  43681. }
  43682. this.currentDepthFunc = depthFunc;
  43683. }
  43684. }
  43685. /**
  43686. * Specifies the scissor box.
  43687. *
  43688. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  43689. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  43690. * @param {number} width - The width of the viewport.
  43691. * @param {number} height - The height of the viewport.
  43692. *
  43693. */
  43694. scissor( x, y, width, height ) {
  43695. const scissor = this._tempVec4.set( x, y, width, height );
  43696. if ( this.currentScissor.equals( scissor ) === false ) {
  43697. const { gl } = this;
  43698. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  43699. this.currentScissor.copy( scissor );
  43700. }
  43701. }
  43702. /**
  43703. * Specifies the viewport.
  43704. *
  43705. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  43706. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  43707. * @param {number} width - The width of the viewport.
  43708. * @param {number} height - The height of the viewport.
  43709. *
  43710. */
  43711. viewport( x, y, width, height ) {
  43712. const viewport = this._tempVec4.set( x, y, width, height );
  43713. if ( this.currentViewport.equals( viewport ) === false ) {
  43714. const { gl } = this;
  43715. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  43716. this.currentViewport.copy( viewport );
  43717. }
  43718. }
  43719. /**
  43720. * Defines the scissor test.
  43721. *
  43722. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  43723. */
  43724. setScissorTest( boolean ) {
  43725. const gl = this.gl;
  43726. if ( boolean ) {
  43727. gl.enable( gl.SCISSOR_TEST );
  43728. } else {
  43729. gl.disable( gl.SCISSOR_TEST );
  43730. }
  43731. }
  43732. /**
  43733. * Specifies whether the stencil test is enabled or not.
  43734. *
  43735. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  43736. */
  43737. setStencilTest( stencilTest ) {
  43738. const { gl } = this;
  43739. if ( stencilTest ) {
  43740. this.enable( gl.STENCIL_TEST );
  43741. } else {
  43742. this.disable( gl.STENCIL_TEST );
  43743. }
  43744. }
  43745. /**
  43746. * Specifies whether stencil values can be written when rendering
  43747. * into a framebuffer or not.
  43748. *
  43749. * This method caches the state so `gl.stencilMask()` is only
  43750. * called when necessary.
  43751. *
  43752. * @param {boolean} stencilMask - The stencil mask.
  43753. */
  43754. setStencilMask( stencilMask ) {
  43755. if ( this.currentStencilMask !== stencilMask ) {
  43756. this.gl.stencilMask( stencilMask );
  43757. this.currentStencilMask = stencilMask;
  43758. }
  43759. }
  43760. /**
  43761. * Specifies whether the stencil test functions.
  43762. *
  43763. * This method caches the state so `gl.stencilFunc()` is only
  43764. * called when necessary.
  43765. *
  43766. * @param {number} stencilFunc - The stencil compare function.
  43767. * @param {number} stencilRef - The reference value for the stencil test.
  43768. * @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.
  43769. */
  43770. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  43771. if ( this.currentStencilFunc !== stencilFunc ||
  43772. this.currentStencilRef !== stencilRef ||
  43773. this.currentStencilFuncMask !== stencilMask ) {
  43774. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  43775. this.currentStencilFunc = stencilFunc;
  43776. this.currentStencilRef = stencilRef;
  43777. this.currentStencilFuncMask = stencilMask;
  43778. }
  43779. }
  43780. /**
  43781. * Specifies whether the stencil test operation.
  43782. *
  43783. * This method caches the state so `gl.stencilOp()` is only
  43784. * called when necessary.
  43785. *
  43786. * @param {number} stencilFail - The function to use when the stencil test fails.
  43787. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  43788. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  43789. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  43790. */
  43791. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  43792. if ( this.currentStencilFail !== stencilFail ||
  43793. this.currentStencilZFail !== stencilZFail ||
  43794. this.currentStencilZPass !== stencilZPass ) {
  43795. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  43796. this.currentStencilFail = stencilFail;
  43797. this.currentStencilZFail = stencilZFail;
  43798. this.currentStencilZPass = stencilZPass;
  43799. }
  43800. }
  43801. /**
  43802. * Configures the WebGL state for the given material.
  43803. *
  43804. * @param {Material} material - The material to configure the state for.
  43805. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  43806. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  43807. */
  43808. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  43809. const { gl } = this;
  43810. material.side === DoubleSide
  43811. ? this.disable( gl.CULL_FACE )
  43812. : this.enable( gl.CULL_FACE );
  43813. let flipSided = ( material.side === BackSide );
  43814. if ( frontFaceCW ) flipSided = ! flipSided;
  43815. this.setFlipSided( flipSided );
  43816. ( material.blending === NormalBlending && material.transparent === false )
  43817. ? this.setBlending( NoBlending )
  43818. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  43819. this.setDepthFunc( material.depthFunc );
  43820. this.setDepthTest( material.depthTest );
  43821. this.setDepthMask( material.depthWrite );
  43822. this.setColorMask( material.colorWrite );
  43823. const stencilWrite = material.stencilWrite;
  43824. this.setStencilTest( stencilWrite );
  43825. if ( stencilWrite ) {
  43826. this.setStencilMask( material.stencilWriteMask );
  43827. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  43828. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  43829. }
  43830. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  43831. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  43832. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  43833. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  43834. if ( hardwareClippingPlanes > 0 ) {
  43835. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  43836. const CLIP_DISTANCE0_WEBGL = 0x3000;
  43837. for ( let i = 0; i < 8; i ++ ) {
  43838. if ( i < hardwareClippingPlanes ) {
  43839. this.enable( CLIP_DISTANCE0_WEBGL + i );
  43840. } else {
  43841. this.disable( CLIP_DISTANCE0_WEBGL + i );
  43842. }
  43843. }
  43844. }
  43845. }
  43846. }
  43847. /**
  43848. * Specifies the polygon offset.
  43849. *
  43850. * This method caches the state so `gl.polygonOffset()` is only
  43851. * called when necessary.
  43852. *
  43853. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  43854. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  43855. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  43856. */
  43857. setPolygonOffset( polygonOffset, factor, units ) {
  43858. const { gl } = this;
  43859. if ( polygonOffset ) {
  43860. this.enable( gl.POLYGON_OFFSET_FILL );
  43861. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  43862. gl.polygonOffset( factor, units );
  43863. this.currentPolygonOffsetFactor = factor;
  43864. this.currentPolygonOffsetUnits = units;
  43865. }
  43866. } else {
  43867. this.disable( gl.POLYGON_OFFSET_FILL );
  43868. }
  43869. }
  43870. /**
  43871. * Defines the usage of the given WebGL program.
  43872. *
  43873. * This method caches the state so `gl.useProgram()` is only
  43874. * called when necessary.
  43875. *
  43876. * @param {WebGLProgram} program - The WebGL program to use.
  43877. * @return {boolean} Whether a program change has been executed or not.
  43878. */
  43879. useProgram( program ) {
  43880. if ( this.currentProgram !== program ) {
  43881. this.gl.useProgram( program );
  43882. this.currentProgram = program;
  43883. return true;
  43884. }
  43885. return false;
  43886. }
  43887. /**
  43888. * Sets the vertex state by binding the given VAO and element buffer.
  43889. *
  43890. * @param {WebGLVertexArrayObject} vao - The VAO.
  43891. * @param {?WebGLBuffer} indexBuffer - The index buffer.
  43892. * @return {boolean} Whether a vertex state has been changed or not.
  43893. */
  43894. setVertexState( vao, indexBuffer = null ) {
  43895. const gl = this.gl;
  43896. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  43897. gl.bindVertexArray( vao );
  43898. if ( indexBuffer !== null ) {
  43899. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  43900. }
  43901. this.currentVAO = vao;
  43902. this.currentIndex = indexBuffer;
  43903. return true;
  43904. }
  43905. return false;
  43906. }
  43907. /**
  43908. * Resets the vertex array state by resetting the VAO and element buffer.
  43909. */
  43910. resetVertexState() {
  43911. const gl = this.gl;
  43912. gl.bindVertexArray( null );
  43913. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  43914. this.currentVAO = null;
  43915. this.currentIndex = null;
  43916. }
  43917. // framebuffer
  43918. /**
  43919. * Binds the given framebuffer.
  43920. *
  43921. * This method caches the state so `gl.bindFramebuffer()` is only
  43922. * called when necessary.
  43923. *
  43924. * @param {number} target - The binding point (target).
  43925. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  43926. * @return {boolean} Whether a bind has been executed or not.
  43927. */
  43928. bindFramebuffer( target, framebuffer ) {
  43929. const { gl, currentBoundFramebuffers } = this;
  43930. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  43931. gl.bindFramebuffer( target, framebuffer );
  43932. currentBoundFramebuffers[ target ] = framebuffer;
  43933. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  43934. if ( target === gl.DRAW_FRAMEBUFFER ) {
  43935. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  43936. }
  43937. if ( target === gl.FRAMEBUFFER ) {
  43938. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  43939. }
  43940. return true;
  43941. }
  43942. return false;
  43943. }
  43944. /**
  43945. * Defines draw buffers to which fragment colors are written into.
  43946. * Configures the MRT setup of custom framebuffers.
  43947. *
  43948. * This method caches the state so `gl.drawBuffers()` is only
  43949. * called when necessary.
  43950. *
  43951. * @param {RenderContext} renderContext - The render context.
  43952. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  43953. */
  43954. drawBuffers( renderContext, framebuffer ) {
  43955. const { gl } = this;
  43956. let drawBuffers = [];
  43957. let needsUpdate = false;
  43958. if ( renderContext.textures !== null ) {
  43959. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  43960. if ( drawBuffers === undefined ) {
  43961. drawBuffers = [];
  43962. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  43963. }
  43964. const textures = renderContext.textures;
  43965. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  43966. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  43967. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  43968. }
  43969. drawBuffers.length = textures.length;
  43970. needsUpdate = true;
  43971. }
  43972. } else {
  43973. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  43974. drawBuffers[ 0 ] = gl.BACK;
  43975. needsUpdate = true;
  43976. }
  43977. }
  43978. if ( needsUpdate ) {
  43979. gl.drawBuffers( drawBuffers );
  43980. }
  43981. }
  43982. // texture
  43983. /**
  43984. * Makes the given texture unit active.
  43985. *
  43986. * This method caches the state so `gl.activeTexture()` is only
  43987. * called when necessary.
  43988. *
  43989. * @param {number} webglSlot - The texture unit to make active.
  43990. */
  43991. activeTexture( webglSlot ) {
  43992. const { gl, currentTextureSlot, maxTextures } = this;
  43993. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  43994. if ( currentTextureSlot !== webglSlot ) {
  43995. gl.activeTexture( webglSlot );
  43996. this.currentTextureSlot = webglSlot;
  43997. }
  43998. }
  43999. /**
  44000. * Binds the given WebGL texture to a target.
  44001. *
  44002. * This method caches the state so `gl.bindTexture()` is only
  44003. * called when necessary.
  44004. *
  44005. * @param {number} webglType - The binding point (target).
  44006. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  44007. * @param {number} webglSlot - The texture.
  44008. */
  44009. bindTexture( webglType, webglTexture, webglSlot ) {
  44010. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  44011. if ( webglSlot === undefined ) {
  44012. if ( currentTextureSlot === null ) {
  44013. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  44014. } else {
  44015. webglSlot = currentTextureSlot;
  44016. }
  44017. }
  44018. let boundTexture = currentBoundTextures[ webglSlot ];
  44019. if ( boundTexture === undefined ) {
  44020. boundTexture = { type: undefined, texture: undefined };
  44021. currentBoundTextures[ webglSlot ] = boundTexture;
  44022. }
  44023. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  44024. if ( currentTextureSlot !== webglSlot ) {
  44025. gl.activeTexture( webglSlot );
  44026. this.currentTextureSlot = webglSlot;
  44027. }
  44028. gl.bindTexture( webglType, webglTexture );
  44029. boundTexture.type = webglType;
  44030. boundTexture.texture = webglTexture;
  44031. }
  44032. }
  44033. /**
  44034. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  44035. *
  44036. * This method caches the state so `gl.bindBufferBase()` is only
  44037. * called when necessary.
  44038. *
  44039. * @param {number} target - The target for the bind operation.
  44040. * @param {number} index - The index of the target.
  44041. * @param {WebGLBuffer} buffer - The WebGL buffer.
  44042. * @return {boolean} Whether a bind has been executed or not.
  44043. */
  44044. bindBufferBase( target, index, buffer ) {
  44045. const { gl } = this;
  44046. const key = `${target}-${index}`;
  44047. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  44048. gl.bindBufferBase( target, index, buffer );
  44049. this.currentBoundBufferBases[ key ] = buffer;
  44050. return true;
  44051. }
  44052. return false;
  44053. }
  44054. /**
  44055. * Unbinds the current bound texture.
  44056. *
  44057. * This method caches the state so `gl.bindTexture()` is only
  44058. * called when necessary.
  44059. */
  44060. unbindTexture() {
  44061. const { gl, currentTextureSlot, currentBoundTextures } = this;
  44062. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  44063. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  44064. gl.bindTexture( boundTexture.type, null );
  44065. boundTexture.type = undefined;
  44066. boundTexture.texture = undefined;
  44067. }
  44068. }
  44069. }
  44070. /**
  44071. * A WebGL 2 backend utility module with common helpers.
  44072. *
  44073. * @private
  44074. */
  44075. class WebGLUtils {
  44076. /**
  44077. * Constructs a new utility object.
  44078. *
  44079. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44080. */
  44081. constructor( backend ) {
  44082. /**
  44083. * A reference to the WebGL 2 backend.
  44084. *
  44085. * @type {WebGLBackend}
  44086. */
  44087. this.backend = backend;
  44088. /**
  44089. * A reference to the rendering context.
  44090. *
  44091. * @type {WebGL2RenderingContext}
  44092. */
  44093. this.gl = this.backend.gl;
  44094. /**
  44095. * A reference to a backend module holding extension-related
  44096. * utility functions.
  44097. *
  44098. * @type {WebGLExtensions}
  44099. */
  44100. this.extensions = backend.extensions;
  44101. }
  44102. /**
  44103. * Converts the given three.js constant into a WebGL constant.
  44104. * The method currently supports the conversion of texture formats
  44105. * and types.
  44106. *
  44107. * @param {number} p - The three.js constant.
  44108. * @param {string} [colorSpace=NoColorSpace] - The color space.
  44109. * @return {?number} The corresponding WebGL constant.
  44110. */
  44111. convert( p, colorSpace = NoColorSpace ) {
  44112. const { gl, extensions } = this;
  44113. let extension;
  44114. const transfer = ColorManagement.getTransfer( colorSpace );
  44115. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  44116. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  44117. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  44118. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  44119. if ( p === UnsignedInt101111Type ) return gl.UNSIGNED_INT_10F_11F_11F_REV;
  44120. if ( p === ByteType ) return gl.BYTE;
  44121. if ( p === ShortType ) return gl.SHORT;
  44122. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  44123. if ( p === IntType ) return gl.INT;
  44124. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  44125. if ( p === FloatType ) return gl.FLOAT;
  44126. if ( p === HalfFloatType ) {
  44127. return gl.HALF_FLOAT;
  44128. }
  44129. if ( p === AlphaFormat ) return gl.ALPHA;
  44130. if ( p === RGBFormat ) return gl.RGB;
  44131. if ( p === RGBAFormat ) return gl.RGBA;
  44132. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  44133. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  44134. // WebGL2 formats.
  44135. if ( p === RedFormat ) return gl.RED;
  44136. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  44137. if ( p === RGFormat ) return gl.RG;
  44138. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  44139. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  44140. // S3TC
  44141. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  44142. if ( transfer === SRGBTransfer ) {
  44143. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  44144. if ( extension !== null ) {
  44145. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  44146. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  44147. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  44148. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  44149. } else {
  44150. return null;
  44151. }
  44152. } else {
  44153. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  44154. if ( extension !== null ) {
  44155. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  44156. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  44157. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  44158. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  44159. } else {
  44160. return null;
  44161. }
  44162. }
  44163. }
  44164. // PVRTC
  44165. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  44166. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  44167. if ( extension !== null ) {
  44168. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  44169. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  44170. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  44171. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  44172. } else {
  44173. return null;
  44174. }
  44175. }
  44176. // ETC
  44177. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  44178. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  44179. if ( extension !== null ) {
  44180. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  44181. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  44182. } else {
  44183. return null;
  44184. }
  44185. }
  44186. // ASTC
  44187. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  44188. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  44189. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  44190. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  44191. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  44192. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  44193. if ( extension !== null ) {
  44194. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  44195. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  44196. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  44197. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  44198. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  44199. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  44200. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  44201. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  44202. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  44203. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  44204. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  44205. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  44206. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  44207. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  44208. } else {
  44209. return null;
  44210. }
  44211. }
  44212. // BPTC
  44213. if ( p === RGBA_BPTC_Format ) {
  44214. extension = extensions.get( 'EXT_texture_compression_bptc' );
  44215. if ( extension !== null ) {
  44216. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  44217. } else {
  44218. return null;
  44219. }
  44220. }
  44221. // RGTC
  44222. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  44223. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  44224. if ( extension !== null ) {
  44225. if ( p === RED_RGTC1_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  44226. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  44227. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  44228. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  44229. } else {
  44230. return null;
  44231. }
  44232. }
  44233. //
  44234. if ( p === UnsignedInt248Type ) {
  44235. return gl.UNSIGNED_INT_24_8;
  44236. }
  44237. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  44238. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  44239. }
  44240. /**
  44241. * This method can be used to synchronize the CPU with the GPU by waiting until
  44242. * ongoing GPU commands have been completed.
  44243. *
  44244. * @private
  44245. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  44246. */
  44247. _clientWaitAsync() {
  44248. const { gl } = this;
  44249. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  44250. gl.flush();
  44251. return new Promise( ( resolve, reject ) => {
  44252. function test() {
  44253. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  44254. if ( res === gl.WAIT_FAILED ) {
  44255. gl.deleteSync( sync );
  44256. reject();
  44257. return;
  44258. }
  44259. if ( res === gl.TIMEOUT_EXPIRED ) {
  44260. requestAnimationFrame( test );
  44261. return;
  44262. }
  44263. gl.deleteSync( sync );
  44264. resolve();
  44265. }
  44266. test();
  44267. } );
  44268. }
  44269. }
  44270. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  44271. /**
  44272. * A WebGL 2 backend utility module for managing textures.
  44273. *
  44274. * @private
  44275. */
  44276. class WebGLTextureUtils {
  44277. /**
  44278. * Constructs a new utility object.
  44279. *
  44280. * @param {WebGLBackend} backend - The WebGL 2 backend.
  44281. */
  44282. constructor( backend ) {
  44283. /**
  44284. * A reference to the WebGL 2 backend.
  44285. *
  44286. * @type {WebGLBackend}
  44287. */
  44288. this.backend = backend;
  44289. /**
  44290. * A reference to the rendering context.
  44291. *
  44292. * @type {WebGL2RenderingContext}
  44293. */
  44294. this.gl = backend.gl;
  44295. /**
  44296. * A reference to a backend module holding extension-related
  44297. * utility functions.
  44298. *
  44299. * @type {WebGLExtensions}
  44300. */
  44301. this.extensions = backend.extensions;
  44302. /**
  44303. * A dictionary for managing default textures. The key
  44304. * is the binding point (target), the value the WEbGL texture object.
  44305. *
  44306. * @type {Object<GLenum,WebGLTexture>}
  44307. */
  44308. this.defaultTextures = {};
  44309. if ( initialized === false ) {
  44310. this._init();
  44311. initialized = true;
  44312. }
  44313. }
  44314. /**
  44315. * Inits the state of the utility.
  44316. *
  44317. * @private
  44318. */
  44319. _init() {
  44320. const gl = this.gl;
  44321. // Store only WebGL constants here.
  44322. wrappingToGL = {
  44323. [ RepeatWrapping ]: gl.REPEAT,
  44324. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  44325. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  44326. };
  44327. filterToGL = {
  44328. [ NearestFilter ]: gl.NEAREST,
  44329. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  44330. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  44331. [ LinearFilter ]: gl.LINEAR,
  44332. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  44333. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  44334. };
  44335. compareToGL = {
  44336. [ NeverCompare ]: gl.NEVER,
  44337. [ AlwaysCompare ]: gl.ALWAYS,
  44338. [ LessCompare ]: gl.LESS,
  44339. [ LessEqualCompare ]: gl.LEQUAL,
  44340. [ EqualCompare ]: gl.EQUAL,
  44341. [ GreaterEqualCompare ]: gl.GEQUAL,
  44342. [ GreaterCompare ]: gl.GREATER,
  44343. [ NotEqualCompare ]: gl.NOTEQUAL
  44344. };
  44345. }
  44346. /**
  44347. * Returns the native texture type for the given texture.
  44348. *
  44349. * @param {Texture} texture - The texture.
  44350. * @return {GLenum} The native texture type.
  44351. */
  44352. getGLTextureType( texture ) {
  44353. const { gl } = this;
  44354. let glTextureType;
  44355. if ( texture.isCubeTexture === true ) {
  44356. glTextureType = gl.TEXTURE_CUBE_MAP;
  44357. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  44358. glTextureType = gl.TEXTURE_2D_ARRAY;
  44359. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  44360. glTextureType = gl.TEXTURE_3D;
  44361. } else {
  44362. glTextureType = gl.TEXTURE_2D;
  44363. }
  44364. return glTextureType;
  44365. }
  44366. /**
  44367. * Returns the native texture type for the given texture.
  44368. *
  44369. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  44370. * @param {GLenum} glFormat - The WebGL format.
  44371. * @param {GLenum} glType - The WebGL type.
  44372. * @param {string} colorSpace - The texture's color space.
  44373. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  44374. * @return {GLenum} The internal format.
  44375. */
  44376. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  44377. const { gl, extensions } = this;
  44378. if ( internalFormatName !== null ) {
  44379. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  44380. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  44381. }
  44382. let internalFormat = glFormat;
  44383. if ( glFormat === gl.RED ) {
  44384. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  44385. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  44386. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  44387. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  44388. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  44389. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  44390. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  44391. if ( glType === gl.INT ) internalFormat = gl.R32I;
  44392. }
  44393. if ( glFormat === gl.RED_INTEGER ) {
  44394. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  44395. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  44396. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  44397. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  44398. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  44399. if ( glType === gl.INT ) internalFormat = gl.R32I;
  44400. }
  44401. if ( glFormat === gl.RG ) {
  44402. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  44403. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  44404. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  44405. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  44406. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  44407. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  44408. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  44409. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  44410. }
  44411. if ( glFormat === gl.RG_INTEGER ) {
  44412. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  44413. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  44414. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  44415. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  44416. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  44417. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  44418. }
  44419. if ( glFormat === gl.RGB ) {
  44420. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  44421. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  44422. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  44423. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  44424. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  44425. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  44426. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  44427. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  44428. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  44429. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  44430. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  44431. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  44432. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  44433. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  44434. if ( glType === gl.UNSIGNED_INT_10F_11F_11F_REV ) internalFormat = gl.R11F_G11F_B10F;
  44435. }
  44436. if ( glFormat === gl.RGB_INTEGER ) {
  44437. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  44438. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  44439. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  44440. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  44441. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  44442. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  44443. }
  44444. if ( glFormat === gl.RGBA ) {
  44445. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  44446. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  44447. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  44448. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  44449. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  44450. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  44451. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  44452. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  44453. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  44454. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  44455. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  44456. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  44457. }
  44458. if ( glFormat === gl.RGBA_INTEGER ) {
  44459. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  44460. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  44461. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  44462. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  44463. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  44464. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  44465. }
  44466. if ( glFormat === gl.DEPTH_COMPONENT ) {
  44467. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  44468. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  44469. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  44470. }
  44471. if ( glFormat === gl.DEPTH_STENCIL ) {
  44472. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  44473. }
  44474. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  44475. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  44476. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  44477. extensions.get( 'EXT_color_buffer_float' );
  44478. }
  44479. return internalFormat;
  44480. }
  44481. /**
  44482. * Sets the texture parameters for the given texture.
  44483. *
  44484. * @param {GLenum} textureType - The texture type.
  44485. * @param {Texture} texture - The texture.
  44486. */
  44487. setTextureParameters( textureType, texture ) {
  44488. const { gl, extensions, backend } = this;
  44489. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  44490. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  44491. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  44492. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  44493. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  44494. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  44495. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  44496. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  44497. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  44498. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  44499. // WebGL 2 does not support wrapping for depth 2D array textures
  44500. if ( ! texture.isArrayTexture ) {
  44501. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  44502. }
  44503. }
  44504. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  44505. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  44506. // follow WebGPU backend mapping for texture filtering
  44507. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  44508. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  44509. if ( texture.compareFunction ) {
  44510. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  44511. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  44512. }
  44513. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  44514. if ( texture.magFilter === NearestFilter ) return;
  44515. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  44516. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  44517. if ( texture.anisotropy > 1 ) {
  44518. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  44519. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  44520. }
  44521. }
  44522. }
  44523. /**
  44524. * Creates a default texture for the given texture that can be used
  44525. * as a placeholder until the actual texture is ready for usage.
  44526. *
  44527. * @param {Texture} texture - The texture to create a default texture for.
  44528. */
  44529. createDefaultTexture( texture ) {
  44530. const { gl, backend, defaultTextures } = this;
  44531. const glTextureType = this.getGLTextureType( texture );
  44532. let textureGPU = defaultTextures[ glTextureType ];
  44533. if ( textureGPU === undefined ) {
  44534. textureGPU = gl.createTexture();
  44535. backend.state.bindTexture( glTextureType, textureGPU );
  44536. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  44537. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  44538. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  44539. defaultTextures[ glTextureType ] = textureGPU;
  44540. }
  44541. backend.set( texture, {
  44542. textureGPU,
  44543. glTextureType,
  44544. isDefault: true
  44545. } );
  44546. }
  44547. /**
  44548. * Defines a texture on the GPU for the given texture object.
  44549. *
  44550. * @param {Texture} texture - The texture.
  44551. * @param {Object} [options={}] - Optional configuration parameter.
  44552. * @return {undefined}
  44553. */
  44554. createTexture( texture, options ) {
  44555. const { gl, backend } = this;
  44556. const { levels, width, height, depth } = options;
  44557. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  44558. const glType = backend.utils.convert( texture.type );
  44559. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  44560. const textureGPU = gl.createTexture();
  44561. const glTextureType = this.getGLTextureType( texture );
  44562. backend.state.bindTexture( glTextureType, textureGPU );
  44563. this.setTextureParameters( glTextureType, texture );
  44564. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  44565. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  44566. } else if ( texture.isData3DTexture ) {
  44567. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  44568. } else if ( ! texture.isVideoTexture ) {
  44569. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  44570. }
  44571. backend.set( texture, {
  44572. textureGPU,
  44573. glTextureType,
  44574. glFormat,
  44575. glType,
  44576. glInternalFormat
  44577. } );
  44578. }
  44579. /**
  44580. * Uploads texture buffer data to the GPU memory.
  44581. *
  44582. * @param {WebGLBuffer} buffer - The buffer data.
  44583. * @param {Texture} texture - The texture,
  44584. */
  44585. copyBufferToTexture( buffer, texture ) {
  44586. const { gl, backend } = this;
  44587. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  44588. const { width, height } = texture.source.data;
  44589. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  44590. backend.state.bindTexture( glTextureType, textureGPU );
  44591. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  44592. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  44593. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  44594. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  44595. backend.state.unbindTexture();
  44596. // debug
  44597. // const framebuffer = gl.createFramebuffer();
  44598. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  44599. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  44600. // const readout = new Float32Array( width * height * 4 );
  44601. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  44602. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  44603. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  44604. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  44605. // console.log( readout );
  44606. }
  44607. /**
  44608. * Uploads the updated texture data to the GPU.
  44609. *
  44610. * @param {Texture} texture - The texture.
  44611. * @param {Object} [options={}] - Optional configuration parameter.
  44612. */
  44613. updateTexture( texture, options ) {
  44614. const { gl } = this;
  44615. const { width, height } = options;
  44616. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  44617. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  44618. return;
  44619. this.backend.state.bindTexture( glTextureType, textureGPU );
  44620. this.setTextureParameters( glTextureType, texture );
  44621. if ( texture.isCompressedTexture ) {
  44622. const mipmaps = texture.mipmaps;
  44623. const image = options.image;
  44624. for ( let i = 0; i < mipmaps.length; i ++ ) {
  44625. const mipmap = mipmaps[ i ];
  44626. if ( texture.isCompressedArrayTexture ) {
  44627. if ( texture.format !== gl.RGBA ) {
  44628. if ( glFormat !== null ) {
  44629. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  44630. } else {
  44631. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  44632. }
  44633. } else {
  44634. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  44635. }
  44636. } else {
  44637. if ( glFormat !== null ) {
  44638. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  44639. } else {
  44640. console.warn( 'Unsupported compressed texture format' );
  44641. }
  44642. }
  44643. }
  44644. } else if ( texture.isCubeTexture ) {
  44645. const images = options.images;
  44646. const mipmaps = texture.mipmaps;
  44647. for ( let i = 0; i < 6; i ++ ) {
  44648. const image = getImage( images[ i ] );
  44649. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  44650. for ( let j = 0; j < mipmaps.length; j ++ ) {
  44651. const mipmap = mipmaps[ j ];
  44652. const image = getImage( mipmap.images[ i ] );
  44653. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j + 1, 0, 0, image.width, image.height, glFormat, glType, image );
  44654. }
  44655. }
  44656. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  44657. const image = options.image;
  44658. if ( texture.layerUpdates.size > 0 ) {
  44659. const layerByteLength = getByteLength( image.width, image.height, texture.format, texture.type );
  44660. for ( const layerIndex of texture.layerUpdates ) {
  44661. const layerData = image.data.subarray(
  44662. layerIndex * layerByteLength / image.data.BYTES_PER_ELEMENT,
  44663. ( layerIndex + 1 ) * layerByteLength / image.data.BYTES_PER_ELEMENT
  44664. );
  44665. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, layerIndex, image.width, image.height, 1, glFormat, glType, layerData );
  44666. }
  44667. texture.clearLayerUpdates();
  44668. } else {
  44669. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  44670. }
  44671. } else if ( texture.isData3DTexture ) {
  44672. const image = options.image;
  44673. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  44674. } else if ( texture.isVideoTexture ) {
  44675. texture.update();
  44676. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  44677. } else {
  44678. const mipmaps = texture.mipmaps;
  44679. if ( mipmaps.length > 0 ) {
  44680. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  44681. const mipmap = mipmaps[ i ];
  44682. const image = getImage( mipmap );
  44683. gl.texSubImage2D( glTextureType, i, 0, 0, mipmap.width, mipmap.height, glFormat, glType, image );
  44684. }
  44685. } else {
  44686. const image = getImage( options.image );
  44687. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  44688. }
  44689. }
  44690. }
  44691. /**
  44692. * Generates mipmaps for the given texture.
  44693. *
  44694. * @param {Texture} texture - The texture.
  44695. */
  44696. generateMipmaps( texture ) {
  44697. const { gl, backend } = this;
  44698. const { textureGPU, glTextureType } = backend.get( texture );
  44699. backend.state.bindTexture( glTextureType, textureGPU );
  44700. gl.generateMipmap( glTextureType );
  44701. }
  44702. /**
  44703. * Deallocates the render buffers of the given render target.
  44704. *
  44705. * @param {RenderTarget} renderTarget - The render target.
  44706. */
  44707. deallocateRenderBuffers( renderTarget ) {
  44708. const { gl, backend } = this;
  44709. // remove framebuffer reference
  44710. if ( renderTarget ) {
  44711. const renderContextData = backend.get( renderTarget );
  44712. renderContextData.renderBufferStorageSetup = undefined;
  44713. if ( renderContextData.framebuffers ) {
  44714. for ( const cacheKey in renderContextData.framebuffers ) {
  44715. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  44716. }
  44717. delete renderContextData.framebuffers;
  44718. }
  44719. if ( renderContextData.depthRenderbuffer ) {
  44720. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  44721. delete renderContextData.depthRenderbuffer;
  44722. }
  44723. if ( renderContextData.stencilRenderbuffer ) {
  44724. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  44725. delete renderContextData.stencilRenderbuffer;
  44726. }
  44727. if ( renderContextData.msaaFrameBuffer ) {
  44728. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  44729. delete renderContextData.msaaFrameBuffer;
  44730. }
  44731. if ( renderContextData.msaaRenderbuffers ) {
  44732. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  44733. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  44734. }
  44735. delete renderContextData.msaaRenderbuffers;
  44736. }
  44737. }
  44738. }
  44739. /**
  44740. * Destroys the GPU data for the given texture object.
  44741. *
  44742. * @param {Texture} texture - The texture.
  44743. */
  44744. destroyTexture( texture ) {
  44745. const { gl, backend } = this;
  44746. const { textureGPU, renderTarget } = backend.get( texture );
  44747. this.deallocateRenderBuffers( renderTarget );
  44748. gl.deleteTexture( textureGPU );
  44749. backend.delete( texture );
  44750. }
  44751. /**
  44752. * Copies data of the given source texture to the given destination texture.
  44753. *
  44754. * @param {Texture} srcTexture - The source texture.
  44755. * @param {Texture} dstTexture - The destination texture.
  44756. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  44757. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  44758. * @param {number} [srcLevel=0] - The source mip level to copy from.
  44759. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  44760. */
  44761. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  44762. const { gl, backend } = this;
  44763. const { state } = this.backend;
  44764. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  44765. state.bindTexture( glTextureType, dstTextureGPU );
  44766. // gather the necessary dimensions to copy
  44767. let width, height, depth, minX, minY, minZ;
  44768. let dstX, dstY, dstZ;
  44769. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  44770. if ( srcRegion !== null ) {
  44771. width = srcRegion.max.x - srcRegion.min.x;
  44772. height = srcRegion.max.y - srcRegion.min.y;
  44773. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  44774. minX = srcRegion.min.x;
  44775. minY = srcRegion.min.y;
  44776. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  44777. } else {
  44778. const levelScale = Math.pow( 2, - srcLevel );
  44779. width = Math.floor( image.width * levelScale );
  44780. height = Math.floor( image.height * levelScale );
  44781. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  44782. depth = image.depth;
  44783. } else if ( srcTexture.isData3DTexture ) {
  44784. depth = Math.floor( image.depth * levelScale );
  44785. } else {
  44786. depth = 1;
  44787. }
  44788. minX = 0;
  44789. minY = 0;
  44790. minZ = 0;
  44791. }
  44792. if ( dstPosition !== null ) {
  44793. dstX = dstPosition.x;
  44794. dstY = dstPosition.y;
  44795. dstZ = dstPosition.z;
  44796. } else {
  44797. dstX = 0;
  44798. dstY = 0;
  44799. dstZ = 0;
  44800. }
  44801. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  44802. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  44803. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  44804. // used for copying data from cpu
  44805. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  44806. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  44807. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  44808. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  44809. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  44810. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  44811. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  44812. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  44813. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  44814. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  44815. // set up the src texture
  44816. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  44817. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  44818. const srcTextureData = backend.get( srcTexture );
  44819. const dstTextureData = backend.get( dstTexture );
  44820. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  44821. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  44822. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  44823. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  44824. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  44825. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  44826. let mask = gl.COLOR_BUFFER_BIT;
  44827. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  44828. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  44829. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  44830. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  44831. } else {
  44832. if ( isDst3D ) {
  44833. // copy data into the 3d texture
  44834. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  44835. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  44836. } else if ( dstTexture.isCompressedArrayTexture ) {
  44837. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  44838. } else {
  44839. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  44840. }
  44841. } else {
  44842. // copy data into the 2d texture
  44843. if ( srcTexture.isDataTexture ) {
  44844. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  44845. } else if ( srcTexture.isCompressedTexture ) {
  44846. gl.compressedTexSubImage2D( glTextureType, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  44847. } else {
  44848. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  44849. }
  44850. }
  44851. }
  44852. // reset values
  44853. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  44854. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  44855. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  44856. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  44857. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  44858. // Generate mipmaps only when copying level 0
  44859. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  44860. gl.generateMipmap( glTextureType );
  44861. }
  44862. state.unbindTexture();
  44863. }
  44864. /**
  44865. * Copies the current bound framebuffer to the given texture.
  44866. *
  44867. * @param {Texture} texture - The destination texture.
  44868. * @param {RenderContext} renderContext - The render context.
  44869. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  44870. */
  44871. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  44872. const { gl } = this;
  44873. const { state } = this.backend;
  44874. const { textureGPU } = this.backend.get( texture );
  44875. const { x, y, z: width, w: height } = rectangle;
  44876. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  44877. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  44878. if ( requireDrawFrameBuffer ) {
  44879. const partial = ( x !== 0 || y !== 0 );
  44880. let mask;
  44881. let attachment;
  44882. if ( texture.isDepthTexture === true ) {
  44883. mask = gl.DEPTH_BUFFER_BIT;
  44884. attachment = gl.DEPTH_ATTACHMENT;
  44885. if ( renderContext.stencil ) {
  44886. mask |= gl.STENCIL_BUFFER_BIT;
  44887. }
  44888. } else {
  44889. mask = gl.COLOR_BUFFER_BIT;
  44890. attachment = gl.COLOR_ATTACHMENT0;
  44891. }
  44892. if ( partial ) {
  44893. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  44894. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  44895. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  44896. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  44897. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  44898. const flippedY = srcHeight - y - height;
  44899. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  44900. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  44901. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  44902. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  44903. state.unbindTexture();
  44904. } else {
  44905. const fb = gl.createFramebuffer();
  44906. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  44907. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  44908. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  44909. gl.deleteFramebuffer( fb );
  44910. }
  44911. } else {
  44912. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  44913. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  44914. state.unbindTexture();
  44915. }
  44916. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  44917. this.backend._setFramebuffer( renderContext );
  44918. }
  44919. /**
  44920. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  44921. *
  44922. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  44923. * @param {RenderContext} renderContext - The render context.
  44924. * @param {number} samples - The MSAA sample count.
  44925. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  44926. */
  44927. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  44928. const { gl } = this;
  44929. const renderTarget = renderContext.renderTarget;
  44930. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  44931. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  44932. if ( depthBuffer && ! stencilBuffer ) {
  44933. let glInternalFormat = gl.DEPTH_COMPONENT24;
  44934. if ( useMultisampledRTT === true ) {
  44935. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  44936. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  44937. } else if ( samples > 0 ) {
  44938. if ( depthTexture && depthTexture.isDepthTexture ) {
  44939. if ( depthTexture.type === gl.FLOAT ) {
  44940. glInternalFormat = gl.DEPTH_COMPONENT32F;
  44941. }
  44942. }
  44943. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  44944. } else {
  44945. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  44946. }
  44947. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  44948. } else if ( depthBuffer && stencilBuffer ) {
  44949. if ( samples > 0 ) {
  44950. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  44951. } else {
  44952. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  44953. }
  44954. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  44955. }
  44956. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  44957. }
  44958. /**
  44959. * Returns texture data as a typed array.
  44960. *
  44961. * @async
  44962. * @param {Texture} texture - The texture to copy.
  44963. * @param {number} x - The x coordinate of the copy origin.
  44964. * @param {number} y - The y coordinate of the copy origin.
  44965. * @param {number} width - The width of the copy.
  44966. * @param {number} height - The height of the copy.
  44967. * @param {number} faceIndex - The face index.
  44968. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  44969. */
  44970. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  44971. const { backend, gl } = this;
  44972. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  44973. const fb = gl.createFramebuffer();
  44974. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  44975. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  44976. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  44977. const typedArrayType = this._getTypedArrayType( glType );
  44978. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  44979. const elementCount = width * height;
  44980. const byteLength = elementCount * bytesPerTexel;
  44981. const buffer = gl.createBuffer();
  44982. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  44983. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  44984. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  44985. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  44986. await backend.utils._clientWaitAsync();
  44987. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  44988. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  44989. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  44990. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  44991. gl.deleteFramebuffer( fb );
  44992. return dstBuffer;
  44993. }
  44994. /**
  44995. * Returns the corresponding typed array type for the given WebGL data type.
  44996. *
  44997. * @private
  44998. * @param {GLenum} glType - The WebGL data type.
  44999. * @return {TypedArray.constructor} The typed array type.
  45000. */
  45001. _getTypedArrayType( glType ) {
  45002. const { gl } = this;
  45003. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  45004. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  45005. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  45006. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  45007. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  45008. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  45009. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  45010. if ( glType === gl.FLOAT ) return Float32Array;
  45011. throw new Error( `Unsupported WebGL type: ${glType}` );
  45012. }
  45013. /**
  45014. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  45015. *
  45016. * @private
  45017. * @param {GLenum} glType - The WebGL data type.
  45018. * @param {GLenum} glFormat - The WebGL texture format.
  45019. * @return {number} The bytes-per-texel.
  45020. */
  45021. _getBytesPerTexel( glType, glFormat ) {
  45022. const { gl } = this;
  45023. let bytesPerComponent = 0;
  45024. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  45025. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  45026. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  45027. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  45028. glType === gl.UNSIGNED_SHORT ||
  45029. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  45030. if ( glType === gl.UNSIGNED_INT ||
  45031. glType === gl.FLOAT ) bytesPerComponent = 4;
  45032. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  45033. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  45034. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  45035. }
  45036. }
  45037. function getImage( source ) {
  45038. if ( source.isDataTexture ) {
  45039. return source.image.data;
  45040. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  45041. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  45042. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  45043. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  45044. return source;
  45045. }
  45046. return source.data;
  45047. }
  45048. /**
  45049. * A WebGL 2 backend utility module for managing extensions.
  45050. *
  45051. * @private
  45052. */
  45053. class WebGLExtensions {
  45054. /**
  45055. * Constructs a new utility object.
  45056. *
  45057. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45058. */
  45059. constructor( backend ) {
  45060. /**
  45061. * A reference to the WebGL 2 backend.
  45062. *
  45063. * @type {WebGLBackend}
  45064. */
  45065. this.backend = backend;
  45066. /**
  45067. * A reference to the rendering context.
  45068. *
  45069. * @type {WebGL2RenderingContext}
  45070. */
  45071. this.gl = this.backend.gl;
  45072. /**
  45073. * A list with all the supported WebGL extensions.
  45074. *
  45075. * @type {Array<string>}
  45076. */
  45077. this.availableExtensions = this.gl.getSupportedExtensions();
  45078. /**
  45079. * A dictionary with requested WebGL extensions.
  45080. * The key is the name of the extension, the value
  45081. * the requested extension object.
  45082. *
  45083. * @type {Object<string,Object>}
  45084. */
  45085. this.extensions = {};
  45086. }
  45087. /**
  45088. * Returns the extension object for the given extension name.
  45089. *
  45090. * @param {string} name - The extension name.
  45091. * @return {Object} The extension object.
  45092. */
  45093. get( name ) {
  45094. let extension = this.extensions[ name ];
  45095. if ( extension === undefined ) {
  45096. extension = this.gl.getExtension( name );
  45097. this.extensions[ name ] = extension;
  45098. }
  45099. return extension;
  45100. }
  45101. /**
  45102. * Returns `true` if the requested extension is available.
  45103. *
  45104. * @param {string} name - The extension name.
  45105. * @return {boolean} Whether the given extension is available or not.
  45106. */
  45107. has( name ) {
  45108. return this.availableExtensions.includes( name );
  45109. }
  45110. }
  45111. /**
  45112. * A WebGL 2 backend utility module for managing the device's capabilities.
  45113. *
  45114. * @private
  45115. */
  45116. class WebGLCapabilities {
  45117. /**
  45118. * Constructs a new utility object.
  45119. *
  45120. * @param {WebGLBackend} backend - The WebGL 2 backend.
  45121. */
  45122. constructor( backend ) {
  45123. /**
  45124. * A reference to the WebGL 2 backend.
  45125. *
  45126. * @type {WebGLBackend}
  45127. */
  45128. this.backend = backend;
  45129. /**
  45130. * This value holds the cached max anisotropy value.
  45131. *
  45132. * @type {?number}
  45133. * @default null
  45134. */
  45135. this.maxAnisotropy = null;
  45136. }
  45137. /**
  45138. * Returns the maximum anisotropy texture filtering value. This value
  45139. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  45140. * WebGL extension.
  45141. *
  45142. * @return {number} The maximum anisotropy texture filtering value.
  45143. */
  45144. getMaxAnisotropy() {
  45145. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  45146. const gl = this.backend.gl;
  45147. const extensions = this.backend.extensions;
  45148. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  45149. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  45150. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  45151. } else {
  45152. this.maxAnisotropy = 0;
  45153. }
  45154. return this.maxAnisotropy;
  45155. }
  45156. }
  45157. const GLFeatureName = {
  45158. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  45159. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  45160. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  45161. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  45162. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  45163. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  45164. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  45165. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  45166. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  45167. 'OVR_multiview2': 'OVR_multiview2'
  45168. };
  45169. class WebGLBufferRenderer {
  45170. constructor( backend ) {
  45171. this.gl = backend.gl;
  45172. this.extensions = backend.extensions;
  45173. this.info = backend.renderer.info;
  45174. this.mode = null;
  45175. this.index = 0;
  45176. this.type = null;
  45177. this.object = null;
  45178. }
  45179. render( start, count ) {
  45180. const { gl, mode, object, type, info, index } = this;
  45181. if ( index !== 0 ) {
  45182. gl.drawElements( mode, count, type, start );
  45183. } else {
  45184. gl.drawArrays( mode, start, count );
  45185. }
  45186. info.update( object, count, 1 );
  45187. }
  45188. renderInstances( start, count, primcount ) {
  45189. const { gl, mode, type, index, object, info } = this;
  45190. if ( primcount === 0 ) return;
  45191. if ( index !== 0 ) {
  45192. gl.drawElementsInstanced( mode, count, type, start, primcount );
  45193. } else {
  45194. gl.drawArraysInstanced( mode, start, count, primcount );
  45195. }
  45196. info.update( object, count, primcount );
  45197. }
  45198. renderMultiDraw( starts, counts, drawCount ) {
  45199. const { extensions, mode, object, info } = this;
  45200. if ( drawCount === 0 ) return;
  45201. const extension = extensions.get( 'WEBGL_multi_draw' );
  45202. if ( extension === null ) {
  45203. for ( let i = 0; i < drawCount; i ++ ) {
  45204. this.render( starts[ i ], counts[ i ] );
  45205. }
  45206. } else {
  45207. if ( this.index !== 0 ) {
  45208. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  45209. } else {
  45210. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  45211. }
  45212. let elementCount = 0;
  45213. for ( let i = 0; i < drawCount; i ++ ) {
  45214. elementCount += counts[ i ];
  45215. }
  45216. info.update( object, elementCount, 1 );
  45217. }
  45218. }
  45219. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  45220. const { extensions, mode, object, info } = this;
  45221. if ( drawCount === 0 ) return;
  45222. const extension = extensions.get( 'WEBGL_multi_draw' );
  45223. if ( extension === null ) {
  45224. for ( let i = 0; i < drawCount; i ++ ) {
  45225. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  45226. }
  45227. } else {
  45228. if ( this.index !== 0 ) {
  45229. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  45230. } else {
  45231. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  45232. }
  45233. let elementCount = 0;
  45234. for ( let i = 0; i < drawCount; i ++ ) {
  45235. elementCount += counts[ i ] * primcount[ i ];
  45236. }
  45237. info.update( object, elementCount, 1 );
  45238. }
  45239. }
  45240. //
  45241. }
  45242. /**
  45243. * Abstract base class of a timestamp query pool.
  45244. *
  45245. * @abstract
  45246. */
  45247. class TimestampQueryPool {
  45248. /**
  45249. * Creates a new timestamp query pool.
  45250. *
  45251. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  45252. */
  45253. constructor( maxQueries = 256 ) {
  45254. /**
  45255. * Whether to track timestamps or not.
  45256. *
  45257. * @type {boolean}
  45258. * @default true
  45259. */
  45260. this.trackTimestamp = true;
  45261. /**
  45262. * Maximum number of queries this pool can hold.
  45263. *
  45264. * @type {number}
  45265. * @default 256
  45266. */
  45267. this.maxQueries = maxQueries;
  45268. /**
  45269. * How many queries allocated so far.
  45270. *
  45271. * @type {number}
  45272. * @default 0
  45273. */
  45274. this.currentQueryIndex = 0;
  45275. /**
  45276. * Tracks offsets for different contexts.
  45277. *
  45278. * @type {Map<string, number>}
  45279. */
  45280. this.queryOffsets = new Map();
  45281. /**
  45282. * Whether the pool has been disposed or not.
  45283. *
  45284. * @type {boolean}
  45285. * @default false
  45286. */
  45287. this.isDisposed = false;
  45288. /**
  45289. * TODO
  45290. *
  45291. * @type {number}
  45292. * @default 0
  45293. */
  45294. this.lastValue = 0;
  45295. /**
  45296. * TODO
  45297. *
  45298. * @type {boolean}
  45299. * @default false
  45300. */
  45301. this.pendingResolve = false;
  45302. }
  45303. /**
  45304. * Allocate queries for a specific uid.
  45305. *
  45306. * @abstract
  45307. * @param {string} uid - A unique identifier for the render context.
  45308. * @returns {?number}
  45309. */
  45310. allocateQueriesForContext( /* uid */ ) {}
  45311. /**
  45312. * Resolve all timestamps and return data (or process them).
  45313. *
  45314. * @abstract
  45315. * @async
  45316. * @returns {Promise<number>|number} The resolved timestamp value.
  45317. */
  45318. async resolveQueriesAsync() {}
  45319. /**
  45320. * Dispose of the query pool.
  45321. *
  45322. * @abstract
  45323. */
  45324. dispose() {}
  45325. }
  45326. /**
  45327. * Manages a pool of WebGL timestamp queries for performance measurement.
  45328. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  45329. *
  45330. * @augments TimestampQueryPool
  45331. */
  45332. class WebGLTimestampQueryPool extends TimestampQueryPool {
  45333. /**
  45334. * Creates a new WebGL timestamp query pool.
  45335. *
  45336. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  45337. * @param {string} type - The type identifier for this query pool.
  45338. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  45339. */
  45340. constructor( gl, type, maxQueries = 2048 ) {
  45341. super( maxQueries );
  45342. this.gl = gl;
  45343. this.type = type;
  45344. // Check for timer query extensions
  45345. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  45346. gl.getExtension( 'EXT_disjoint_timer_query' );
  45347. if ( ! this.ext ) {
  45348. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  45349. this.trackTimestamp = false;
  45350. return;
  45351. }
  45352. // Create query objects
  45353. this.queries = [];
  45354. for ( let i = 0; i < this.maxQueries; i ++ ) {
  45355. this.queries.push( gl.createQuery() );
  45356. }
  45357. this.activeQuery = null;
  45358. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  45359. }
  45360. /**
  45361. * Allocates a pair of queries for a given render context.
  45362. *
  45363. * @param {string} uid - A unique identifier for the render context.
  45364. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  45365. */
  45366. allocateQueriesForContext( uid ) {
  45367. if ( ! this.trackTimestamp ) return null;
  45368. // Check if we have enough space for a new query pair
  45369. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  45370. 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() } ).` );
  45371. return null;
  45372. }
  45373. const baseOffset = this.currentQueryIndex;
  45374. this.currentQueryIndex += 2;
  45375. // Initialize query states
  45376. this.queryStates.set( baseOffset, 'inactive' );
  45377. this.queryOffsets.set( uid, baseOffset );
  45378. return baseOffset;
  45379. }
  45380. /**
  45381. * Begins a timestamp query for the specified render context.
  45382. *
  45383. * @param {string} uid - A unique identifier for the render context.
  45384. */
  45385. beginQuery( uid ) {
  45386. if ( ! this.trackTimestamp || this.isDisposed ) {
  45387. return;
  45388. }
  45389. const baseOffset = this.queryOffsets.get( uid );
  45390. if ( baseOffset == null ) {
  45391. return;
  45392. }
  45393. // Don't start a new query if there's an active one
  45394. if ( this.activeQuery !== null ) {
  45395. return;
  45396. }
  45397. const query = this.queries[ baseOffset ];
  45398. if ( ! query ) {
  45399. return;
  45400. }
  45401. try {
  45402. // Only begin if query is inactive
  45403. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  45404. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  45405. this.activeQuery = baseOffset;
  45406. this.queryStates.set( baseOffset, 'started' );
  45407. }
  45408. } catch ( error ) {
  45409. console.error( 'Error in beginQuery:', error );
  45410. this.activeQuery = null;
  45411. this.queryStates.set( baseOffset, 'inactive' );
  45412. }
  45413. }
  45414. /**
  45415. * Ends the active timestamp query for the specified render context.
  45416. *
  45417. * @param {string} uid - A unique identifier for the render context.
  45418. */
  45419. endQuery( uid ) {
  45420. if ( ! this.trackTimestamp || this.isDisposed ) {
  45421. return;
  45422. }
  45423. const baseOffset = this.queryOffsets.get( uid );
  45424. if ( baseOffset == null ) {
  45425. return;
  45426. }
  45427. // Only end if this is the active query
  45428. if ( this.activeQuery !== baseOffset ) {
  45429. return;
  45430. }
  45431. try {
  45432. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  45433. this.queryStates.set( baseOffset, 'ended' );
  45434. this.activeQuery = null;
  45435. } catch ( error ) {
  45436. console.error( 'Error in endQuery:', error );
  45437. // Reset state on error
  45438. this.queryStates.set( baseOffset, 'inactive' );
  45439. this.activeQuery = null;
  45440. }
  45441. }
  45442. /**
  45443. * Asynchronously resolves all completed queries and returns the total duration.
  45444. *
  45445. * @async
  45446. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  45447. */
  45448. async resolveQueriesAsync() {
  45449. if ( ! this.trackTimestamp || this.pendingResolve ) {
  45450. return this.lastValue;
  45451. }
  45452. this.pendingResolve = true;
  45453. try {
  45454. // Wait for all ended queries to complete
  45455. const resolvePromises = [];
  45456. for ( const [ baseOffset, state ] of this.queryStates ) {
  45457. if ( state === 'ended' ) {
  45458. const query = this.queries[ baseOffset ];
  45459. resolvePromises.push( this.resolveQuery( query ) );
  45460. }
  45461. }
  45462. if ( resolvePromises.length === 0 ) {
  45463. return this.lastValue;
  45464. }
  45465. const results = await Promise.all( resolvePromises );
  45466. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  45467. // Store the last valid result
  45468. this.lastValue = totalDuration;
  45469. // Reset states
  45470. this.currentQueryIndex = 0;
  45471. this.queryOffsets.clear();
  45472. this.queryStates.clear();
  45473. this.activeQuery = null;
  45474. return totalDuration;
  45475. } catch ( error ) {
  45476. console.error( 'Error resolving queries:', error );
  45477. return this.lastValue;
  45478. } finally {
  45479. this.pendingResolve = false;
  45480. }
  45481. }
  45482. /**
  45483. * Resolves a single query, checking for completion and disjoint operation.
  45484. *
  45485. * @async
  45486. * @param {WebGLQuery} query - The query object to resolve.
  45487. * @returns {Promise<number>} The elapsed time in milliseconds.
  45488. */
  45489. async resolveQuery( query ) {
  45490. return new Promise( ( resolve ) => {
  45491. if ( this.isDisposed ) {
  45492. resolve( this.lastValue );
  45493. return;
  45494. }
  45495. let timeoutId;
  45496. let isResolved = false;
  45497. const cleanup = () => {
  45498. if ( timeoutId ) {
  45499. clearTimeout( timeoutId );
  45500. timeoutId = null;
  45501. }
  45502. };
  45503. const finalizeResolution = ( value ) => {
  45504. if ( ! isResolved ) {
  45505. isResolved = true;
  45506. cleanup();
  45507. resolve( value );
  45508. }
  45509. };
  45510. const checkQuery = () => {
  45511. if ( this.isDisposed ) {
  45512. finalizeResolution( this.lastValue );
  45513. return;
  45514. }
  45515. try {
  45516. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  45517. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  45518. if ( disjoint ) {
  45519. finalizeResolution( this.lastValue );
  45520. return;
  45521. }
  45522. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  45523. if ( ! available ) {
  45524. timeoutId = setTimeout( checkQuery, 1 );
  45525. return;
  45526. }
  45527. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  45528. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  45529. } catch ( error ) {
  45530. console.error( 'Error checking query:', error );
  45531. resolve( this.lastValue );
  45532. }
  45533. };
  45534. checkQuery();
  45535. } );
  45536. }
  45537. /**
  45538. * Releases all resources held by this query pool.
  45539. * This includes deleting all query objects and clearing internal state.
  45540. */
  45541. dispose() {
  45542. if ( this.isDisposed ) {
  45543. return;
  45544. }
  45545. this.isDisposed = true;
  45546. if ( ! this.trackTimestamp ) return;
  45547. for ( const query of this.queries ) {
  45548. this.gl.deleteQuery( query );
  45549. }
  45550. this.queries = [];
  45551. this.queryStates.clear();
  45552. this.queryOffsets.clear();
  45553. this.lastValue = 0;
  45554. this.activeQuery = null;
  45555. }
  45556. }
  45557. /**
  45558. * A backend implementation targeting WebGL 2.
  45559. *
  45560. * @private
  45561. * @augments Backend
  45562. */
  45563. class WebGLBackend extends Backend {
  45564. /**
  45565. * WebGLBackend options.
  45566. *
  45567. * @typedef {Object} WebGLBackend~Options
  45568. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  45569. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  45570. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  45571. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  45572. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  45573. * @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.
  45574. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  45575. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  45576. */
  45577. /**
  45578. * Constructs a new WebGPU backend.
  45579. *
  45580. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  45581. */
  45582. constructor( parameters = {} ) {
  45583. super( parameters );
  45584. /**
  45585. * This flag can be used for type testing.
  45586. *
  45587. * @type {boolean}
  45588. * @readonly
  45589. * @default true
  45590. */
  45591. this.isWebGLBackend = true;
  45592. /**
  45593. * A reference to a backend module holding shader attribute-related
  45594. * utility functions.
  45595. *
  45596. * @type {?WebGLAttributeUtils}
  45597. * @default null
  45598. */
  45599. this.attributeUtils = null;
  45600. /**
  45601. * A reference to a backend module holding extension-related
  45602. * utility functions.
  45603. *
  45604. * @type {?WebGLExtensions}
  45605. * @default null
  45606. */
  45607. this.extensions = null;
  45608. /**
  45609. * A reference to a backend module holding capability-related
  45610. * utility functions.
  45611. *
  45612. * @type {?WebGLCapabilities}
  45613. * @default null
  45614. */
  45615. this.capabilities = null;
  45616. /**
  45617. * A reference to a backend module holding texture-related
  45618. * utility functions.
  45619. *
  45620. * @type {?WebGLTextureUtils}
  45621. * @default null
  45622. */
  45623. this.textureUtils = null;
  45624. /**
  45625. * A reference to a backend module holding renderer-related
  45626. * utility functions.
  45627. *
  45628. * @type {?WebGLBufferRenderer}
  45629. * @default null
  45630. */
  45631. this.bufferRenderer = null;
  45632. /**
  45633. * A reference to the rendering context.
  45634. *
  45635. * @type {?WebGL2RenderingContext}
  45636. * @default null
  45637. */
  45638. this.gl = null;
  45639. /**
  45640. * A reference to a backend module holding state-related
  45641. * utility functions.
  45642. *
  45643. * @type {?WebGLState}
  45644. * @default null
  45645. */
  45646. this.state = null;
  45647. /**
  45648. * A reference to a backend module holding common
  45649. * utility functions.
  45650. *
  45651. * @type {?WebGLUtils}
  45652. * @default null
  45653. */
  45654. this.utils = null;
  45655. /**
  45656. * Dictionary for caching VAOs.
  45657. *
  45658. * @type {Object<string,WebGLVertexArrayObject>}
  45659. */
  45660. this.vaoCache = {};
  45661. /**
  45662. * Dictionary for caching transform feedback objects.
  45663. *
  45664. * @type {Object<string,WebGLTransformFeedback>}
  45665. */
  45666. this.transformFeedbackCache = {};
  45667. /**
  45668. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  45669. * Only relevant when using compute shaders.
  45670. *
  45671. * @type {boolean}
  45672. * @default false
  45673. */
  45674. this.discard = false;
  45675. /**
  45676. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  45677. * device does not support the extension.
  45678. *
  45679. * @type {?EXTDisjointTimerQueryWebGL2}
  45680. * @default null
  45681. */
  45682. this.disjoint = null;
  45683. /**
  45684. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  45685. * device does not support the extension.
  45686. *
  45687. * @type {?KHRParallelShaderCompile}
  45688. * @default null
  45689. */
  45690. this.parallel = null;
  45691. /**
  45692. * A reference to the current render context.
  45693. *
  45694. * @private
  45695. * @type {RenderContext}
  45696. * @default null
  45697. */
  45698. this._currentContext = null;
  45699. /**
  45700. * A unique collection of bindings.
  45701. *
  45702. * @private
  45703. * @type {WeakSet<Array<BindGroup>>}
  45704. */
  45705. this._knownBindings = new WeakSet();
  45706. /**
  45707. * Whether the device supports framebuffers invalidation or not.
  45708. *
  45709. * @private
  45710. * @type {boolean}
  45711. */
  45712. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  45713. /**
  45714. * The target framebuffer when rendering with
  45715. * the WebXR device API.
  45716. *
  45717. * @private
  45718. * @type {?WebGLFramebuffer}
  45719. * @default null
  45720. */
  45721. this._xrFramebuffer = null;
  45722. }
  45723. /**
  45724. * Initializes the backend so it is ready for usage.
  45725. *
  45726. * @param {Renderer} renderer - The renderer.
  45727. */
  45728. init( renderer ) {
  45729. super.init( renderer );
  45730. //
  45731. const parameters = this.parameters;
  45732. const contextAttributes = {
  45733. antialias: renderer.samples > 0,
  45734. alpha: true, // always true for performance reasons
  45735. depth: renderer.depth,
  45736. stencil: renderer.stencil
  45737. };
  45738. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  45739. function onContextLost( event ) {
  45740. event.preventDefault();
  45741. const contextLossInfo = {
  45742. api: 'WebGL',
  45743. message: event.statusMessage || 'Unknown reason',
  45744. reason: null,
  45745. originalEvent: event
  45746. };
  45747. renderer.onDeviceLost( contextLossInfo );
  45748. }
  45749. this._onContextLost = onContextLost;
  45750. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  45751. this.gl = glContext;
  45752. this.extensions = new WebGLExtensions( this );
  45753. this.capabilities = new WebGLCapabilities( this );
  45754. this.attributeUtils = new WebGLAttributeUtils( this );
  45755. this.textureUtils = new WebGLTextureUtils( this );
  45756. this.bufferRenderer = new WebGLBufferRenderer( this );
  45757. this.state = new WebGLState( this );
  45758. this.utils = new WebGLUtils( this );
  45759. this.extensions.get( 'EXT_color_buffer_float' );
  45760. this.extensions.get( 'WEBGL_clip_cull_distance' );
  45761. this.extensions.get( 'OES_texture_float_linear' );
  45762. this.extensions.get( 'EXT_color_buffer_half_float' );
  45763. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  45764. this.extensions.get( 'WEBGL_render_shared_exponent' );
  45765. this.extensions.get( 'WEBGL_multi_draw' );
  45766. this.extensions.get( 'OVR_multiview2' );
  45767. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  45768. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  45769. }
  45770. /**
  45771. * The coordinate system of the backend.
  45772. *
  45773. * @type {number}
  45774. * @readonly
  45775. */
  45776. get coordinateSystem() {
  45777. return WebGLCoordinateSystem;
  45778. }
  45779. /**
  45780. * This method performs a readback operation by moving buffer data from
  45781. * a storage buffer attribute from the GPU to the CPU.
  45782. *
  45783. * @async
  45784. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  45785. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  45786. */
  45787. async getArrayBufferAsync( attribute ) {
  45788. return await this.attributeUtils.getArrayBufferAsync( attribute );
  45789. }
  45790. /**
  45791. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  45792. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  45793. *
  45794. * @async
  45795. * @return {Promise} A Promise that resolves when synchronization has been finished.
  45796. */
  45797. async waitForGPU() {
  45798. await this.utils._clientWaitAsync();
  45799. }
  45800. /**
  45801. * Ensures the backend is XR compatible.
  45802. *
  45803. * @async
  45804. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  45805. */
  45806. async makeXRCompatible() {
  45807. const attributes = this.gl.getContextAttributes();
  45808. if ( attributes.xrCompatible !== true ) {
  45809. await this.gl.makeXRCompatible();
  45810. }
  45811. }
  45812. /**
  45813. * Sets the XR rendering destination.
  45814. *
  45815. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  45816. */
  45817. setXRTarget( xrFramebuffer ) {
  45818. this._xrFramebuffer = xrFramebuffer;
  45819. }
  45820. /**
  45821. * Configures the given XR render target with external textures.
  45822. *
  45823. * This method is only relevant when using the WebXR Layers API.
  45824. *
  45825. * @param {XRRenderTarget} renderTarget - The XR render target.
  45826. * @param {WebGLTexture} colorTexture - A native color texture.
  45827. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  45828. */
  45829. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  45830. const gl = this.gl;
  45831. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  45832. if ( depthTexture !== null ) {
  45833. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  45834. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  45835. // The multisample_render_to_texture extension doesn't work properly if there
  45836. // are midframe flushes and an external depth texture.
  45837. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  45838. console.warn( 'THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  45839. }
  45840. renderTarget._autoAllocateDepthBuffer = false;
  45841. }
  45842. }
  45843. /**
  45844. * Inits a time stamp query for the given render context.
  45845. *
  45846. * @param {string} type - The type of the timestamp query.
  45847. * @param {string} uid - A unique identifier for the timestamp query.
  45848. */
  45849. initTimestampQuery( type, uid ) {
  45850. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  45851. if ( ! this.timestampQueryPool[ type ] ) {
  45852. // TODO: Variable maxQueries?
  45853. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  45854. }
  45855. const timestampQueryPool = this.timestampQueryPool[ type ];
  45856. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  45857. if ( baseOffset !== null ) {
  45858. timestampQueryPool.beginQuery( uid );
  45859. }
  45860. }
  45861. // timestamp utils
  45862. /**
  45863. * Prepares the timestamp buffer.
  45864. *
  45865. * @param {string} type - The type of the timestamp query.
  45866. * @param {string} uid - A unique identifier for the timestamp query.
  45867. */
  45868. prepareTimestampBuffer( type, uid ) {
  45869. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  45870. const timestampQueryPool = this.timestampQueryPool[ type ];
  45871. timestampQueryPool.endQuery( uid );
  45872. }
  45873. /**
  45874. * Returns the backend's rendering context.
  45875. *
  45876. * @return {WebGL2RenderingContext} The rendering context.
  45877. */
  45878. getContext() {
  45879. return this.gl;
  45880. }
  45881. /**
  45882. * This method is executed at the beginning of a render call and prepares
  45883. * the WebGL state for upcoming render calls
  45884. *
  45885. * @param {RenderContext} renderContext - The render context.
  45886. */
  45887. beginRender( renderContext ) {
  45888. const { state } = this;
  45889. const renderContextData = this.get( renderContext );
  45890. //
  45891. renderContextData.frameCalls = this.renderer.info.render.frameCalls;
  45892. //
  45893. if ( renderContext.viewport ) {
  45894. this.updateViewport( renderContext );
  45895. } else {
  45896. const { width, height } = this.getDrawingBufferSize();
  45897. state.viewport( 0, 0, width, height );
  45898. }
  45899. if ( renderContext.scissor ) {
  45900. const { x, y, width, height } = renderContext.scissorValue;
  45901. state.scissor( x, renderContext.height - height - y, width, height );
  45902. }
  45903. //
  45904. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  45905. renderContextData.previousContext = this._currentContext;
  45906. this._currentContext = renderContext;
  45907. this._setFramebuffer( renderContext );
  45908. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  45909. const occlusionQueryCount = renderContext.occlusionQueryCount;
  45910. if ( occlusionQueryCount > 0 ) {
  45911. // Get a reference to the array of objects with queries. The renderContextData property
  45912. // can be changed by another render pass before the async reading of all previous queries complete
  45913. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  45914. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  45915. renderContextData.lastOcclusionObject = null;
  45916. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  45917. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  45918. renderContextData.occlusionQueryIndex = 0;
  45919. }
  45920. }
  45921. /**
  45922. * This method is executed at the end of a render call and finalizes work
  45923. * after draw calls.
  45924. *
  45925. * @param {RenderContext} renderContext - The render context.
  45926. */
  45927. finishRender( renderContext ) {
  45928. const { gl, state } = this;
  45929. const renderContextData = this.get( renderContext );
  45930. const previousContext = renderContextData.previousContext;
  45931. state.resetVertexState();
  45932. const occlusionQueryCount = renderContext.occlusionQueryCount;
  45933. if ( occlusionQueryCount > 0 ) {
  45934. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  45935. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  45936. }
  45937. this.resolveOccludedAsync( renderContext );
  45938. }
  45939. const textures = renderContext.textures;
  45940. if ( textures !== null ) {
  45941. for ( let i = 0; i < textures.length; i ++ ) {
  45942. const texture = textures[ i ];
  45943. if ( texture.generateMipmaps ) {
  45944. this.generateMipmaps( texture );
  45945. }
  45946. }
  45947. }
  45948. this._currentContext = previousContext;
  45949. this._resolveRenderTarget( renderContext );
  45950. if ( previousContext !== null ) {
  45951. this._setFramebuffer( previousContext );
  45952. if ( previousContext.viewport ) {
  45953. this.updateViewport( previousContext );
  45954. } else {
  45955. const { width, height } = this.getDrawingBufferSize();
  45956. state.viewport( 0, 0, width, height );
  45957. }
  45958. }
  45959. this.prepareTimestampBuffer( TimestampQuery.RENDER, this.getTimestampUID( renderContext ) );
  45960. }
  45961. /**
  45962. * This method processes the result of occlusion queries and writes it
  45963. * into render context data.
  45964. *
  45965. * @async
  45966. * @param {RenderContext} renderContext - The render context.
  45967. */
  45968. resolveOccludedAsync( renderContext ) {
  45969. const renderContextData = this.get( renderContext );
  45970. // handle occlusion query results
  45971. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  45972. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  45973. const occluded = new WeakSet();
  45974. const { gl } = this;
  45975. renderContextData.currentOcclusionQueryObjects = null;
  45976. renderContextData.currentOcclusionQueries = null;
  45977. const check = () => {
  45978. let completed = 0;
  45979. // check all queries and requeue as appropriate
  45980. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  45981. const query = currentOcclusionQueries[ i ];
  45982. if ( query === null ) continue;
  45983. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  45984. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  45985. currentOcclusionQueries[ i ] = null;
  45986. gl.deleteQuery( query );
  45987. completed ++;
  45988. }
  45989. }
  45990. if ( completed < currentOcclusionQueries.length ) {
  45991. requestAnimationFrame( check );
  45992. } else {
  45993. renderContextData.occluded = occluded;
  45994. }
  45995. };
  45996. check();
  45997. }
  45998. }
  45999. /**
  46000. * Returns `true` if the given 3D object is fully occluded by other
  46001. * 3D objects in the scene.
  46002. *
  46003. * @param {RenderContext} renderContext - The render context.
  46004. * @param {Object3D} object - The 3D object to test.
  46005. * @return {boolean} Whether the 3D object is fully occluded or not.
  46006. */
  46007. isOccluded( renderContext, object ) {
  46008. const renderContextData = this.get( renderContext );
  46009. return renderContextData.occluded && renderContextData.occluded.has( object );
  46010. }
  46011. /**
  46012. * Updates the viewport with the values from the given render context.
  46013. *
  46014. * @param {RenderContext} renderContext - The render context.
  46015. */
  46016. updateViewport( renderContext ) {
  46017. const { state } = this;
  46018. const { x, y, width, height } = renderContext.viewportValue;
  46019. state.viewport( x, renderContext.height - height - y, width, height );
  46020. }
  46021. /**
  46022. * Defines the scissor test.
  46023. *
  46024. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  46025. */
  46026. setScissorTest( boolean ) {
  46027. const state = this.state;
  46028. state.setScissorTest( boolean );
  46029. }
  46030. /**
  46031. * Returns the clear color and alpha into a single
  46032. * color object.
  46033. *
  46034. * @return {Color4} The clear color.
  46035. */
  46036. getClearColor() {
  46037. const clearColor = super.getClearColor();
  46038. // Since the canvas is always created with alpha: true,
  46039. // WebGL must always premultiply the clear color.
  46040. clearColor.r *= clearColor.a;
  46041. clearColor.g *= clearColor.a;
  46042. clearColor.b *= clearColor.a;
  46043. return clearColor;
  46044. }
  46045. /**
  46046. * Performs a clear operation.
  46047. *
  46048. * @param {boolean} color - Whether the color buffer should be cleared or not.
  46049. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  46050. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  46051. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  46052. * @param {boolean} [setFrameBuffer=true] - Controls whether the intermediate framebuffer should be set or not.
  46053. * @param {boolean} [resolveRenderTarget=true] - Controls whether an active render target should be resolved
  46054. * or not. Only relevant for explicit clears.
  46055. */
  46056. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true, resolveRenderTarget = true ) {
  46057. const { gl, renderer } = this;
  46058. if ( descriptor === null ) {
  46059. const clearColor = this.getClearColor();
  46060. descriptor = {
  46061. textures: null,
  46062. clearColorValue: clearColor
  46063. };
  46064. }
  46065. //
  46066. let clear = 0;
  46067. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  46068. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  46069. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  46070. if ( clear !== 0 ) {
  46071. let clearColor;
  46072. if ( descriptor.clearColorValue ) {
  46073. clearColor = descriptor.clearColorValue;
  46074. } else {
  46075. clearColor = this.getClearColor();
  46076. }
  46077. const clearDepth = renderer.getClearDepth();
  46078. const clearStencil = renderer.getClearStencil();
  46079. if ( depth ) this.state.setDepthMask( true );
  46080. if ( descriptor.textures === null ) {
  46081. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  46082. gl.clear( clear );
  46083. } else {
  46084. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  46085. if ( color ) {
  46086. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  46087. if ( i === 0 ) {
  46088. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  46089. } else {
  46090. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  46091. }
  46092. }
  46093. }
  46094. if ( depth && stencil ) {
  46095. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  46096. } else if ( depth ) {
  46097. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  46098. } else if ( stencil ) {
  46099. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  46100. }
  46101. if ( setFrameBuffer && resolveRenderTarget ) this._resolveRenderTarget( descriptor );
  46102. }
  46103. }
  46104. }
  46105. /**
  46106. * This method is executed at the beginning of a compute call and
  46107. * prepares the state for upcoming compute tasks.
  46108. *
  46109. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  46110. */
  46111. beginCompute( computeGroup ) {
  46112. const { state, gl } = this;
  46113. const computeGroupData = this.get( computeGroup );
  46114. //
  46115. computeGroupData.frameCalls = this.renderer.info.compute.frameCalls;
  46116. //
  46117. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  46118. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  46119. }
  46120. /**
  46121. * Executes a compute command for the given compute node.
  46122. *
  46123. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  46124. * @param {Node} computeNode - The compute node.
  46125. * @param {Array<BindGroup>} bindings - The bindings.
  46126. * @param {ComputePipeline} pipeline - The compute pipeline.
  46127. * @param {?number} [count=null] - The count of compute invocations. If `null`, the count is determined by the compute node.
  46128. */
  46129. compute( computeGroup, computeNode, bindings, pipeline, count = null ) {
  46130. const { state, gl } = this;
  46131. if ( this.discard === false ) {
  46132. // required here to handle async behaviour of render.compute()
  46133. gl.enable( gl.RASTERIZER_DISCARD );
  46134. this.discard = true;
  46135. }
  46136. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  46137. const vaoKey = this._getVaoKey( attributes );
  46138. const vaoGPU = this.vaoCache[ vaoKey ];
  46139. if ( vaoGPU === undefined ) {
  46140. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  46141. } else {
  46142. state.setVertexState( vaoGPU );
  46143. }
  46144. state.useProgram( programGPU );
  46145. this._bindUniforms( bindings );
  46146. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  46147. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  46148. gl.beginTransformFeedback( gl.POINTS );
  46149. count = ( count !== null ) ? count : computeNode.count;
  46150. if ( Array.isArray( count ) ) {
  46151. warnOnce( 'WebGLBackend.compute(): The count parameter must be a single number, not an array.' );
  46152. count = count[ 0 ];
  46153. }
  46154. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  46155. gl.drawArraysInstanced( gl.POINTS, 0, 1, count );
  46156. } else {
  46157. gl.drawArrays( gl.POINTS, 0, count );
  46158. }
  46159. gl.endTransformFeedback();
  46160. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  46161. // switch active buffers
  46162. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  46163. const dualAttributeData = transformBuffers[ i ];
  46164. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  46165. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  46166. }
  46167. dualAttributeData.switchBuffers();
  46168. }
  46169. }
  46170. /**
  46171. * This method is executed at the end of a compute call and
  46172. * finalizes work after compute tasks.
  46173. *
  46174. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  46175. */
  46176. finishCompute( computeGroup ) {
  46177. const gl = this.gl;
  46178. this.discard = false;
  46179. gl.disable( gl.RASTERIZER_DISCARD );
  46180. this.prepareTimestampBuffer( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ) );
  46181. if ( this._currentContext ) {
  46182. this._setFramebuffer( this._currentContext );
  46183. }
  46184. }
  46185. /**
  46186. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  46187. *
  46188. * @param {RenderContext} renderContext - The render context.
  46189. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  46190. *
  46191. * @private
  46192. */
  46193. _isRenderCameraDepthArray( renderContext ) {
  46194. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  46195. }
  46196. /**
  46197. * Executes a draw command for the given render object.
  46198. *
  46199. * @param {RenderObject} renderObject - The render object to draw.
  46200. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  46201. */
  46202. draw( renderObject/*, info*/ ) {
  46203. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  46204. const { programGPU } = this.get( pipeline );
  46205. const { gl, state } = this;
  46206. const contextData = this.get( context );
  46207. const drawParams = renderObject.getDrawParameters();
  46208. if ( drawParams === null ) return;
  46209. //
  46210. this._bindUniforms( renderObject.getBindings() );
  46211. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  46212. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  46213. state.useProgram( programGPU );
  46214. // vertex state
  46215. const attributes = renderObject.getAttributes();
  46216. const attributesData = this.get( attributes );
  46217. let vaoGPU = attributesData.vaoGPU;
  46218. if ( vaoGPU === undefined ) {
  46219. const vaoKey = this._getVaoKey( attributes );
  46220. vaoGPU = this.vaoCache[ vaoKey ];
  46221. if ( vaoGPU === undefined ) {
  46222. vaoGPU = this._createVao( attributes );
  46223. this.vaoCache[ vaoKey ] = vaoGPU;
  46224. attributesData.vaoGPU = vaoGPU;
  46225. }
  46226. }
  46227. const index = renderObject.getIndex();
  46228. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  46229. state.setVertexState( vaoGPU, indexGPU );
  46230. //
  46231. const lastObject = contextData.lastOcclusionObject;
  46232. if ( lastObject !== object && lastObject !== undefined ) {
  46233. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  46234. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  46235. contextData.occlusionQueryIndex ++;
  46236. }
  46237. if ( object.occlusionTest === true ) {
  46238. const query = gl.createQuery();
  46239. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  46240. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  46241. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  46242. }
  46243. contextData.lastOcclusionObject = object;
  46244. }
  46245. //
  46246. const renderer = this.bufferRenderer;
  46247. if ( object.isPoints ) renderer.mode = gl.POINTS;
  46248. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  46249. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  46250. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  46251. else {
  46252. if ( material.wireframe === true ) {
  46253. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  46254. renderer.mode = gl.LINES;
  46255. } else {
  46256. renderer.mode = gl.TRIANGLES;
  46257. }
  46258. }
  46259. //
  46260. const { vertexCount, instanceCount } = drawParams;
  46261. let { firstVertex } = drawParams;
  46262. renderer.object = object;
  46263. if ( index !== null ) {
  46264. firstVertex *= index.array.BYTES_PER_ELEMENT;
  46265. const indexData = this.get( index );
  46266. renderer.index = index.count;
  46267. renderer.type = indexData.type;
  46268. } else {
  46269. renderer.index = 0;
  46270. }
  46271. const draw = () => {
  46272. if ( object.isBatchedMesh ) {
  46273. if ( object._multiDrawInstances !== null ) {
  46274. // @deprecated, r174
  46275. warnOnce( 'THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  46276. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  46277. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  46278. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  46279. } else {
  46280. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  46281. }
  46282. } else if ( instanceCount > 1 ) {
  46283. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  46284. } else {
  46285. renderer.render( firstVertex, vertexCount );
  46286. }
  46287. };
  46288. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  46289. const cameraData = this.get( renderObject.camera );
  46290. const cameras = renderObject.camera.cameras;
  46291. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  46292. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  46293. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  46294. const indexesGPU = [];
  46295. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  46296. const bufferGPU = gl.createBuffer();
  46297. data[ 0 ] = i;
  46298. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  46299. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  46300. indexesGPU.push( bufferGPU );
  46301. }
  46302. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  46303. }
  46304. const cameraIndexData = this.get( cameraIndex );
  46305. const pixelRatio = this.renderer.getPixelRatio();
  46306. const renderTarget = this._currentContext.renderTarget;
  46307. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  46308. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  46309. if ( isRenderCameraDepthArray ) {
  46310. // Clear the depth texture
  46311. const textureData = this.get( renderTarget.depthTexture );
  46312. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  46313. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  46314. const { stencilBuffer } = renderTarget;
  46315. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  46316. this.renderer._activeCubeFace = i;
  46317. this._currentContext.activeCubeFace = i;
  46318. this._setFramebuffer( this._currentContext );
  46319. this.clear( false, true, stencilBuffer, this._currentContext, false, false );
  46320. }
  46321. this.renderer._activeCubeFace = prevActiveCubeFace;
  46322. this._currentContext.activeCubeFace = prevActiveCubeFace;
  46323. }
  46324. }
  46325. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  46326. const subCamera = cameras[ i ];
  46327. if ( object.layers.test( subCamera.layers ) ) {
  46328. if ( isRenderCameraDepthArray ) {
  46329. // Update the active layer
  46330. this.renderer._activeCubeFace = i;
  46331. this._currentContext.activeCubeFace = i;
  46332. this._setFramebuffer( this._currentContext );
  46333. }
  46334. const vp = subCamera.viewport;
  46335. if ( vp !== undefined ) {
  46336. const x = vp.x * pixelRatio;
  46337. const y = vp.y * pixelRatio;
  46338. const width = vp.width * pixelRatio;
  46339. const height = vp.height * pixelRatio;
  46340. state.viewport(
  46341. Math.floor( x ),
  46342. Math.floor( renderObject.context.height - height - y ),
  46343. Math.floor( width ),
  46344. Math.floor( height )
  46345. );
  46346. }
  46347. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  46348. draw();
  46349. }
  46350. this._currentContext.activeCubeFace = prevActiveCubeFace;
  46351. this.renderer._activeCubeFace = prevActiveCubeFace;
  46352. }
  46353. } else {
  46354. draw();
  46355. }
  46356. }
  46357. /**
  46358. * Explain why always null is returned.
  46359. *
  46360. * @param {RenderObject} renderObject - The render object.
  46361. * @return {boolean} Whether the render pipeline requires an update or not.
  46362. */
  46363. needsRenderUpdate( /*renderObject*/ ) {
  46364. return false;
  46365. }
  46366. /**
  46367. * Explain why no cache key is computed.
  46368. *
  46369. * @param {RenderObject} renderObject - The render object.
  46370. * @return {string} The cache key.
  46371. */
  46372. getRenderCacheKey( /*renderObject*/ ) {
  46373. return '';
  46374. }
  46375. // textures
  46376. /**
  46377. * Creates a default texture for the given texture that can be used
  46378. * as a placeholder until the actual texture is ready for usage.
  46379. *
  46380. * @param {Texture} texture - The texture to create a default texture for.
  46381. */
  46382. createDefaultTexture( texture ) {
  46383. this.textureUtils.createDefaultTexture( texture );
  46384. }
  46385. /**
  46386. * Defines a texture on the GPU for the given texture object.
  46387. *
  46388. * @param {Texture} texture - The texture.
  46389. * @param {Object} [options={}] - Optional configuration parameter.
  46390. */
  46391. createTexture( texture, options ) {
  46392. this.textureUtils.createTexture( texture, options );
  46393. }
  46394. /**
  46395. * Uploads the updated texture data to the GPU.
  46396. *
  46397. * @param {Texture} texture - The texture.
  46398. * @param {Object} [options={}] - Optional configuration parameter.
  46399. */
  46400. updateTexture( texture, options ) {
  46401. this.textureUtils.updateTexture( texture, options );
  46402. }
  46403. /**
  46404. * Generates mipmaps for the given texture.
  46405. *
  46406. * @param {Texture} texture - The texture.
  46407. */
  46408. generateMipmaps( texture ) {
  46409. this.textureUtils.generateMipmaps( texture );
  46410. }
  46411. /**
  46412. * Destroys the GPU data for the given texture object.
  46413. *
  46414. * @param {Texture} texture - The texture.
  46415. */
  46416. destroyTexture( texture ) {
  46417. this.textureUtils.destroyTexture( texture );
  46418. }
  46419. /**
  46420. * Returns texture data as a typed array.
  46421. *
  46422. * @async
  46423. * @param {Texture} texture - The texture to copy.
  46424. * @param {number} x - The x coordinate of the copy origin.
  46425. * @param {number} y - The y coordinate of the copy origin.
  46426. * @param {number} width - The width of the copy.
  46427. * @param {number} height - The height of the copy.
  46428. * @param {number} faceIndex - The face index.
  46429. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  46430. */
  46431. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  46432. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  46433. }
  46434. /**
  46435. * This method does nothing since WebGL 2 has no concept of samplers.
  46436. *
  46437. * @param {Texture} texture - The texture to create the sampler for.
  46438. */
  46439. createSampler( /*texture*/ ) {
  46440. //console.warn( 'Abstract class.' );
  46441. }
  46442. /**
  46443. * This method does nothing since WebGL 2 has no concept of samplers.
  46444. *
  46445. * @param {Texture} texture - The texture to destroy the sampler for.
  46446. */
  46447. destroySampler( /*texture*/ ) {}
  46448. // node builder
  46449. /**
  46450. * Returns a node builder for the given render object.
  46451. *
  46452. * @param {RenderObject} object - The render object.
  46453. * @param {Renderer} renderer - The renderer.
  46454. * @return {GLSLNodeBuilder} The node builder.
  46455. */
  46456. createNodeBuilder( object, renderer ) {
  46457. return new GLSLNodeBuilder( object, renderer );
  46458. }
  46459. // program
  46460. /**
  46461. * Creates a shader program from the given programmable stage.
  46462. *
  46463. * @param {ProgrammableStage} program - The programmable stage.
  46464. */
  46465. createProgram( program ) {
  46466. const gl = this.gl;
  46467. const { stage, code } = program;
  46468. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  46469. gl.shaderSource( shader, code );
  46470. gl.compileShader( shader );
  46471. this.set( program, {
  46472. shaderGPU: shader
  46473. } );
  46474. }
  46475. /**
  46476. * Destroys the shader program of the given programmable stage.
  46477. *
  46478. * @param {ProgrammableStage} program - The programmable stage.
  46479. */
  46480. destroyProgram( program ) {
  46481. this.delete( program );
  46482. }
  46483. /**
  46484. * Creates a render pipeline for the given render object.
  46485. *
  46486. * @param {RenderObject} renderObject - The render object.
  46487. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  46488. */
  46489. createRenderPipeline( renderObject, promises ) {
  46490. const gl = this.gl;
  46491. const pipeline = renderObject.pipeline;
  46492. // Program
  46493. const { fragmentProgram, vertexProgram } = pipeline;
  46494. const programGPU = gl.createProgram();
  46495. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  46496. const vertexShader = this.get( vertexProgram ).shaderGPU;
  46497. gl.attachShader( programGPU, fragmentShader );
  46498. gl.attachShader( programGPU, vertexShader );
  46499. gl.linkProgram( programGPU );
  46500. this.set( pipeline, {
  46501. programGPU,
  46502. fragmentShader,
  46503. vertexShader
  46504. } );
  46505. if ( promises !== null && this.parallel ) {
  46506. const p = new Promise( ( resolve /*, reject*/ ) => {
  46507. const parallel = this.parallel;
  46508. const checkStatus = () => {
  46509. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  46510. this._completeCompile( renderObject, pipeline );
  46511. resolve();
  46512. } else {
  46513. requestAnimationFrame( checkStatus );
  46514. }
  46515. };
  46516. checkStatus();
  46517. } );
  46518. promises.push( p );
  46519. return;
  46520. }
  46521. this._completeCompile( renderObject, pipeline );
  46522. }
  46523. /**
  46524. * Formats the source code of error messages.
  46525. *
  46526. * @private
  46527. * @param {string} string - The code.
  46528. * @param {number} errorLine - The error line.
  46529. * @return {string} The formatted code.
  46530. */
  46531. _handleSource( string, errorLine ) {
  46532. const lines = string.split( '\n' );
  46533. const lines2 = [];
  46534. const from = Math.max( errorLine - 6, 0 );
  46535. const to = Math.min( errorLine + 6, lines.length );
  46536. for ( let i = from; i < to; i ++ ) {
  46537. const line = i + 1;
  46538. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  46539. }
  46540. return lines2.join( '\n' );
  46541. }
  46542. /**
  46543. * Gets the shader compilation errors from the info log.
  46544. *
  46545. * @private
  46546. * @param {WebGL2RenderingContext} gl - The rendering context.
  46547. * @param {WebGLShader} shader - The WebGL shader object.
  46548. * @param {string} type - The shader type.
  46549. * @return {string} The shader errors.
  46550. */
  46551. _getShaderErrors( gl, shader, type ) {
  46552. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  46553. const shaderInfoLog = gl.getShaderInfoLog( shader ) || '';
  46554. const errors = shaderInfoLog.trim();
  46555. if ( status && errors === '' ) return '';
  46556. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  46557. if ( errorMatches ) {
  46558. const errorLine = parseInt( errorMatches[ 1 ] );
  46559. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  46560. } else {
  46561. return errors;
  46562. }
  46563. }
  46564. /**
  46565. * Logs shader compilation errors.
  46566. *
  46567. * @private
  46568. * @param {WebGLProgram} programGPU - The WebGL program.
  46569. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  46570. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  46571. */
  46572. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  46573. if ( this.renderer.debug.checkShaderErrors ) {
  46574. const gl = this.gl;
  46575. const programInfoLog = gl.getProgramInfoLog( programGPU ) || '';
  46576. const programLog = programInfoLog.trim();
  46577. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  46578. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  46579. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  46580. } else {
  46581. // default error reporting
  46582. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  46583. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  46584. console.error(
  46585. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  46586. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  46587. 'Program Info Log: ' + programLog + '\n' +
  46588. vertexErrors + '\n' +
  46589. fragmentErrors
  46590. );
  46591. }
  46592. } else if ( programLog !== '' ) {
  46593. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  46594. }
  46595. }
  46596. }
  46597. /**
  46598. * Completes the shader program setup for the given render object.
  46599. *
  46600. * @private
  46601. * @param {RenderObject} renderObject - The render object.
  46602. * @param {RenderPipeline} pipeline - The render pipeline.
  46603. */
  46604. _completeCompile( renderObject, pipeline ) {
  46605. const { state, gl } = this;
  46606. const pipelineData = this.get( pipeline );
  46607. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  46608. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  46609. this._logProgramError( programGPU, fragmentShader, vertexShader );
  46610. }
  46611. state.useProgram( programGPU );
  46612. // Bindings
  46613. const bindings = renderObject.getBindings();
  46614. this._setupBindings( bindings, programGPU );
  46615. //
  46616. this.set( pipeline, {
  46617. programGPU
  46618. } );
  46619. }
  46620. /**
  46621. * Creates a compute pipeline for the given compute node.
  46622. *
  46623. * @param {ComputePipeline} computePipeline - The compute pipeline.
  46624. * @param {Array<BindGroup>} bindings - The bindings.
  46625. */
  46626. createComputePipeline( computePipeline, bindings ) {
  46627. const { state, gl } = this;
  46628. // Program
  46629. const fragmentProgram = {
  46630. stage: 'fragment',
  46631. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  46632. };
  46633. this.createProgram( fragmentProgram );
  46634. const { computeProgram } = computePipeline;
  46635. const programGPU = gl.createProgram();
  46636. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  46637. const vertexShader = this.get( computeProgram ).shaderGPU;
  46638. const transforms = computeProgram.transforms;
  46639. const transformVaryingNames = [];
  46640. const transformAttributeNodes = [];
  46641. for ( let i = 0; i < transforms.length; i ++ ) {
  46642. const transform = transforms[ i ];
  46643. transformVaryingNames.push( transform.varyingName );
  46644. transformAttributeNodes.push( transform.attributeNode );
  46645. }
  46646. gl.attachShader( programGPU, fragmentShader );
  46647. gl.attachShader( programGPU, vertexShader );
  46648. gl.transformFeedbackVaryings(
  46649. programGPU,
  46650. transformVaryingNames,
  46651. gl.SEPARATE_ATTRIBS
  46652. );
  46653. gl.linkProgram( programGPU );
  46654. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  46655. this._logProgramError( programGPU, fragmentShader, vertexShader );
  46656. }
  46657. state.useProgram( programGPU );
  46658. // Bindings
  46659. this._setupBindings( bindings, programGPU );
  46660. const attributeNodes = computeProgram.attributes;
  46661. const attributes = [];
  46662. const transformBuffers = [];
  46663. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  46664. const attribute = attributeNodes[ i ].node.attribute;
  46665. attributes.push( attribute );
  46666. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  46667. }
  46668. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  46669. const attribute = transformAttributeNodes[ i ].attribute;
  46670. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  46671. const attributeData = this.get( attribute );
  46672. transformBuffers.push( attributeData );
  46673. }
  46674. //
  46675. this.set( computePipeline, {
  46676. programGPU,
  46677. transformBuffers,
  46678. attributes
  46679. } );
  46680. }
  46681. /**
  46682. * Creates bindings from the given bind group definition.
  46683. *
  46684. * @param {BindGroup} bindGroup - The bind group.
  46685. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46686. * @param {number} cacheIndex - The cache index.
  46687. * @param {number} version - The version.
  46688. */
  46689. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  46690. if ( this._knownBindings.has( bindings ) === false ) {
  46691. this._knownBindings.add( bindings );
  46692. let uniformBuffers = 0;
  46693. let textures = 0;
  46694. for ( const bindGroup of bindings ) {
  46695. this.set( bindGroup, {
  46696. textures: textures,
  46697. uniformBuffers: uniformBuffers
  46698. } );
  46699. for ( const binding of bindGroup.bindings ) {
  46700. if ( binding.isUniformBuffer ) uniformBuffers ++;
  46701. if ( binding.isSampledTexture ) textures ++;
  46702. }
  46703. }
  46704. }
  46705. this.updateBindings( bindGroup, bindings );
  46706. }
  46707. /**
  46708. * Updates the given bind group definition.
  46709. *
  46710. * @param {BindGroup} bindGroup - The bind group.
  46711. * @param {Array<BindGroup>} bindings - Array of bind groups.
  46712. * @param {number} cacheIndex - The cache index.
  46713. * @param {number} version - The version.
  46714. */
  46715. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  46716. const { gl } = this;
  46717. const bindGroupData = this.get( bindGroup );
  46718. let i = bindGroupData.uniformBuffers;
  46719. let t = bindGroupData.textures;
  46720. for ( const binding of bindGroup.bindings ) {
  46721. const map = this.get( binding );
  46722. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  46723. const data = binding.buffer;
  46724. let { bufferGPU } = this.get( data );
  46725. if ( bufferGPU === undefined ) {
  46726. // create
  46727. bufferGPU = gl.createBuffer();
  46728. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  46729. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  46730. this.set( data, { bufferGPU } );
  46731. } else {
  46732. // update
  46733. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  46734. gl.bufferSubData( gl.UNIFORM_BUFFER, 0, data );
  46735. }
  46736. map.index = i ++;
  46737. map.bufferGPU = bufferGPU;
  46738. this.set( binding, map );
  46739. } else if ( binding.isSampledTexture ) {
  46740. const { textureGPU, glTextureType } = this.get( binding.texture );
  46741. map.index = t ++;
  46742. map.textureGPU = textureGPU;
  46743. map.glTextureType = glTextureType;
  46744. this.set( binding, map );
  46745. }
  46746. }
  46747. }
  46748. /**
  46749. * Updates a buffer binding.
  46750. *
  46751. * @param {Buffer} binding - The buffer binding to update.
  46752. */
  46753. updateBinding( binding ) {
  46754. const gl = this.gl;
  46755. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  46756. const bindingData = this.get( binding );
  46757. const bufferGPU = bindingData.bufferGPU;
  46758. const data = binding.buffer;
  46759. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  46760. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  46761. }
  46762. }
  46763. // attributes
  46764. /**
  46765. * Creates the GPU buffer of an indexed shader attribute.
  46766. *
  46767. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  46768. */
  46769. createIndexAttribute( attribute ) {
  46770. const gl = this.gl;
  46771. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  46772. }
  46773. /**
  46774. * Creates the GPU buffer of a shader attribute.
  46775. *
  46776. * @param {BufferAttribute} attribute - The buffer attribute.
  46777. */
  46778. createAttribute( attribute ) {
  46779. if ( this.has( attribute ) ) return;
  46780. const gl = this.gl;
  46781. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  46782. }
  46783. /**
  46784. * Creates the GPU buffer of a storage attribute.
  46785. *
  46786. * @param {BufferAttribute} attribute - The buffer attribute.
  46787. */
  46788. createStorageAttribute( attribute ) {
  46789. if ( this.has( attribute ) ) return;
  46790. const gl = this.gl;
  46791. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  46792. }
  46793. /**
  46794. * Updates the GPU buffer of a shader attribute.
  46795. *
  46796. * @param {BufferAttribute} attribute - The buffer attribute to update.
  46797. */
  46798. updateAttribute( attribute ) {
  46799. this.attributeUtils.updateAttribute( attribute );
  46800. }
  46801. /**
  46802. * Destroys the GPU buffer of a shader attribute.
  46803. *
  46804. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  46805. */
  46806. destroyAttribute( attribute ) {
  46807. this.attributeUtils.destroyAttribute( attribute );
  46808. }
  46809. /**
  46810. * Checks if the given feature is supported by the backend.
  46811. *
  46812. * @param {string} name - The feature's name.
  46813. * @return {boolean} Whether the feature is supported or not.
  46814. */
  46815. hasFeature( name ) {
  46816. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  46817. const extensions = this.extensions;
  46818. for ( let i = 0; i < keysMatching.length; i ++ ) {
  46819. if ( extensions.has( keysMatching[ i ] ) ) return true;
  46820. }
  46821. return false;
  46822. }
  46823. /**
  46824. * Returns the maximum anisotropy texture filtering value.
  46825. *
  46826. * @return {number} The maximum anisotropy texture filtering value.
  46827. */
  46828. getMaxAnisotropy() {
  46829. return this.capabilities.getMaxAnisotropy();
  46830. }
  46831. /**
  46832. * Copies data of the given source texture to the given destination texture.
  46833. *
  46834. * @param {Texture} srcTexture - The source texture.
  46835. * @param {Texture} dstTexture - The destination texture.
  46836. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  46837. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  46838. * @param {number} [srcLevel=0] - The source mip level to copy from.
  46839. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  46840. */
  46841. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  46842. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  46843. }
  46844. /**
  46845. * Copies the current bound framebuffer to the given texture.
  46846. *
  46847. * @param {Texture} texture - The destination texture.
  46848. * @param {RenderContext} renderContext - The render context.
  46849. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  46850. */
  46851. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  46852. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  46853. }
  46854. /**
  46855. * Configures the active framebuffer from the given render context.
  46856. *
  46857. * @private
  46858. * @param {RenderContext} descriptor - The render context.
  46859. */
  46860. _setFramebuffer( descriptor ) {
  46861. const { gl, state } = this;
  46862. let currentFrameBuffer = null;
  46863. if ( descriptor.textures !== null ) {
  46864. const renderTarget = descriptor.renderTarget;
  46865. const renderTargetContextData = this.get( renderTarget );
  46866. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  46867. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  46868. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  46869. const isRenderTargetArray = renderTarget.depth > 1;
  46870. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  46871. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  46872. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  46873. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  46874. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  46875. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  46876. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  46877. const cacheKey = getCacheKey( descriptor );
  46878. let fb;
  46879. if ( isCube ) {
  46880. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  46881. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  46882. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  46883. fb = this._xrFramebuffer;
  46884. } else {
  46885. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  46886. fb = renderTargetContextData.framebuffers[ cacheKey ];
  46887. }
  46888. if ( fb === undefined ) {
  46889. fb = gl.createFramebuffer();
  46890. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  46891. const textures = descriptor.textures;
  46892. const depthInvalidationArray = [];
  46893. if ( isCube ) {
  46894. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  46895. const { textureGPU } = this.get( textures[ 0 ] );
  46896. const cubeFace = this.renderer._activeCubeFace;
  46897. const mipLevel = this.renderer._activeMipmapLevel;
  46898. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, mipLevel );
  46899. } else {
  46900. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  46901. for ( let i = 0; i < textures.length; i ++ ) {
  46902. const texture = textures[ i ];
  46903. const textureData = this.get( texture );
  46904. textureData.renderTarget = descriptor.renderTarget;
  46905. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  46906. const attachment = gl.COLOR_ATTACHMENT0 + i;
  46907. if ( renderTarget.multiview ) {
  46908. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  46909. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  46910. const layer = this.renderer._activeCubeFace;
  46911. const mipLevel = this.renderer._activeMipmapLevel;
  46912. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, mipLevel, layer );
  46913. } else {
  46914. if ( useMultisampledRTT ) {
  46915. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  46916. } else {
  46917. const mipLevel = this.renderer._activeMipmapLevel;
  46918. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, mipLevel );
  46919. }
  46920. }
  46921. }
  46922. }
  46923. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  46924. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  46925. const renderbuffer = gl.createRenderbuffer();
  46926. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  46927. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  46928. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  46929. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  46930. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  46931. } else {
  46932. if ( descriptor.depthTexture !== null ) {
  46933. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  46934. const textureData = this.get( descriptor.depthTexture );
  46935. textureData.renderTarget = descriptor.renderTarget;
  46936. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  46937. if ( renderTarget.multiview ) {
  46938. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  46939. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  46940. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  46941. } else {
  46942. if ( descriptor.depthTexture.isArrayTexture ) {
  46943. const layer = this.renderer._activeCubeFace;
  46944. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  46945. } else {
  46946. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  46947. }
  46948. }
  46949. }
  46950. }
  46951. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  46952. } else {
  46953. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  46954. if ( isRenderCameraDepthArray ) {
  46955. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  46956. const layer = this.renderer._activeCubeFace;
  46957. const depthData = this.get( descriptor.depthTexture );
  46958. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  46959. gl.framebufferTextureLayer(
  46960. gl.FRAMEBUFFER,
  46961. depthStyle,
  46962. depthData.textureGPU,
  46963. 0,
  46964. layer
  46965. );
  46966. }
  46967. // rebind external XR textures
  46968. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  46969. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  46970. // rebind color
  46971. const textureData = this.get( descriptor.textures[ 0 ] );
  46972. if ( renderTarget.multiview ) {
  46973. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  46974. } else if ( useMultisampledRTT ) {
  46975. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  46976. } else {
  46977. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  46978. }
  46979. // rebind depth
  46980. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  46981. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  46982. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  46983. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  46984. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  46985. } else {
  46986. const textureData = this.get( descriptor.depthTexture );
  46987. if ( renderTarget.multiview ) {
  46988. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  46989. } else if ( useMultisampledRTT ) {
  46990. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  46991. } else {
  46992. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  46993. }
  46994. }
  46995. }
  46996. }
  46997. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  46998. if ( msaaFb === undefined ) {
  46999. const invalidationArray = [];
  47000. msaaFb = gl.createFramebuffer();
  47001. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  47002. const msaaRenderbuffers = [];
  47003. const textures = descriptor.textures;
  47004. for ( let i = 0; i < textures.length; i ++ ) {
  47005. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  47006. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  47007. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  47008. const texture = descriptor.textures[ i ];
  47009. const textureData = this.get( texture );
  47010. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  47011. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  47012. }
  47013. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  47014. renderTargetContextData.msaaFrameBuffer = msaaFb;
  47015. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  47016. if ( depthBuffer && depthRenderbuffer === undefined ) {
  47017. depthRenderbuffer = gl.createRenderbuffer();
  47018. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  47019. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  47020. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  47021. invalidationArray.push( depthStyle );
  47022. }
  47023. renderTargetContextData.invalidationArray = invalidationArray;
  47024. }
  47025. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  47026. } else {
  47027. currentFrameBuffer = fb;
  47028. }
  47029. state.drawBuffers( descriptor, fb );
  47030. }
  47031. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  47032. }
  47033. /**
  47034. * Computes the VAO key for the given index and attributes.
  47035. *
  47036. * @private
  47037. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  47038. * @return {string} The VAO key.
  47039. */
  47040. _getVaoKey( attributes ) {
  47041. let key = '';
  47042. for ( let i = 0; i < attributes.length; i ++ ) {
  47043. const attributeData = this.get( attributes[ i ] );
  47044. key += ':' + attributeData.id;
  47045. }
  47046. return key;
  47047. }
  47048. /**
  47049. * Creates a VAO from the index and attributes.
  47050. *
  47051. * @private
  47052. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  47053. * @return {Object} The VAO data.
  47054. */
  47055. _createVao( attributes ) {
  47056. const { gl } = this;
  47057. const vaoGPU = gl.createVertexArray();
  47058. gl.bindVertexArray( vaoGPU );
  47059. for ( let i = 0; i < attributes.length; i ++ ) {
  47060. const attribute = attributes[ i ];
  47061. const attributeData = this.get( attribute );
  47062. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  47063. gl.enableVertexAttribArray( i );
  47064. let stride, offset;
  47065. if ( attribute.isInterleavedBufferAttribute === true ) {
  47066. stride = attribute.data.stride * attributeData.bytesPerElement;
  47067. offset = attribute.offset * attributeData.bytesPerElement;
  47068. } else {
  47069. stride = 0;
  47070. offset = 0;
  47071. }
  47072. if ( attributeData.isInteger ) {
  47073. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  47074. } else {
  47075. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  47076. }
  47077. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  47078. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  47079. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  47080. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  47081. }
  47082. }
  47083. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  47084. return vaoGPU;
  47085. }
  47086. /**
  47087. * Creates a transform feedback from the given transform buffers.
  47088. *
  47089. * @private
  47090. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  47091. * @return {WebGLTransformFeedback} The transform feedback.
  47092. */
  47093. _getTransformFeedback( transformBuffers ) {
  47094. let key = '';
  47095. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  47096. key += ':' + transformBuffers[ i ].id;
  47097. }
  47098. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  47099. if ( transformFeedbackGPU !== undefined ) {
  47100. return transformFeedbackGPU;
  47101. }
  47102. const { gl } = this;
  47103. transformFeedbackGPU = gl.createTransformFeedback();
  47104. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  47105. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  47106. const attributeData = transformBuffers[ i ];
  47107. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  47108. }
  47109. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  47110. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  47111. return transformFeedbackGPU;
  47112. }
  47113. /**
  47114. * Setups the given bindings.
  47115. *
  47116. * @private
  47117. * @param {Array<BindGroup>} bindings - The bindings.
  47118. * @param {WebGLProgram} programGPU - The WebGL program.
  47119. */
  47120. _setupBindings( bindings, programGPU ) {
  47121. const gl = this.gl;
  47122. for ( const bindGroup of bindings ) {
  47123. for ( const binding of bindGroup.bindings ) {
  47124. const bindingData = this.get( binding );
  47125. const index = bindingData.index;
  47126. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  47127. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  47128. gl.uniformBlockBinding( programGPU, location, index );
  47129. } else if ( binding.isSampledTexture ) {
  47130. const location = gl.getUniformLocation( programGPU, binding.name );
  47131. gl.uniform1i( location, index );
  47132. }
  47133. }
  47134. }
  47135. }
  47136. /**
  47137. * Binds the given uniforms.
  47138. *
  47139. * @private
  47140. * @param {Array<BindGroup>} bindings - The bindings.
  47141. */
  47142. _bindUniforms( bindings ) {
  47143. const { gl, state } = this;
  47144. for ( const bindGroup of bindings ) {
  47145. for ( const binding of bindGroup.bindings ) {
  47146. const bindingData = this.get( binding );
  47147. const index = bindingData.index;
  47148. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  47149. // TODO USE bindBufferRange to group multiple uniform buffers
  47150. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  47151. } else if ( binding.isSampledTexture ) {
  47152. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  47153. }
  47154. }
  47155. }
  47156. }
  47157. /**
  47158. * The method ensures multisampled render targets are resolved.
  47159. *
  47160. * @private
  47161. * @param {RenderContext} renderContext - The render context.
  47162. */
  47163. _resolveRenderTarget( renderContext ) {
  47164. const { gl, state } = this;
  47165. const renderTarget = renderContext.renderTarget;
  47166. if ( renderContext.textures !== null && renderTarget ) {
  47167. const renderTargetContextData = this.get( renderTarget );
  47168. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  47169. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  47170. let mask = gl.COLOR_BUFFER_BIT;
  47171. if ( renderTarget.resolveDepthBuffer ) {
  47172. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  47173. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  47174. }
  47175. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  47176. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  47177. const textures = renderContext.textures;
  47178. const isMRT = textures.length > 1;
  47179. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  47180. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  47181. if ( isMRT ) {
  47182. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  47183. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  47184. for ( let i = 0; i < textures.length; i ++ ) {
  47185. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  47186. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  47187. }
  47188. }
  47189. for ( let i = 0; i < textures.length; i ++ ) {
  47190. if ( isMRT ) {
  47191. // configure attachment for resolve
  47192. const { textureGPU } = this.get( textures[ i ] );
  47193. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  47194. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  47195. }
  47196. if ( renderContext.scissor ) {
  47197. const { x, y, width, height } = renderContext.scissorValue;
  47198. const viewY = renderContext.height - height - y;
  47199. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  47200. } else {
  47201. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  47202. }
  47203. }
  47204. if ( isMRT ) {
  47205. // restore attachments
  47206. for ( let i = 0; i < textures.length; i ++ ) {
  47207. const { textureGPU } = this.get( textures[ i ] );
  47208. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  47209. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  47210. }
  47211. }
  47212. if ( this._supportsInvalidateFramebuffer === true ) {
  47213. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  47214. }
  47215. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  47216. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  47217. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  47218. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  47219. }
  47220. }
  47221. }
  47222. /**
  47223. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  47224. * should be used when MSAA is enabled.
  47225. *
  47226. * @private
  47227. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  47228. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  47229. */
  47230. _useMultisampledExtension( renderTarget ) {
  47231. if ( renderTarget.multiview === true ) {
  47232. return true;
  47233. }
  47234. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  47235. }
  47236. /**
  47237. * Frees internal resources.
  47238. */
  47239. dispose() {
  47240. const extension = this.extensions.get( 'WEBGL_lose_context' );
  47241. if ( extension ) extension.loseContext();
  47242. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  47243. }
  47244. }
  47245. const GPUPrimitiveTopology = {
  47246. PointList: 'point-list',
  47247. LineList: 'line-list',
  47248. LineStrip: 'line-strip',
  47249. TriangleList: 'triangle-list',
  47250. TriangleStrip: 'triangle-strip',
  47251. };
  47252. const GPUCompareFunction = {
  47253. Never: 'never',
  47254. Less: 'less',
  47255. Equal: 'equal',
  47256. LessEqual: 'less-equal',
  47257. Greater: 'greater',
  47258. NotEqual: 'not-equal',
  47259. GreaterEqual: 'greater-equal',
  47260. Always: 'always'
  47261. };
  47262. const GPUStoreOp = {
  47263. Store: 'store'};
  47264. const GPULoadOp = {
  47265. Load: 'load',
  47266. Clear: 'clear'
  47267. };
  47268. const GPUFrontFace = {
  47269. CCW: 'ccw',
  47270. CW: 'cw'
  47271. };
  47272. const GPUCullMode = {
  47273. None: 'none',
  47274. Back: 'back'
  47275. };
  47276. const GPUIndexFormat = {
  47277. Uint16: 'uint16',
  47278. Uint32: 'uint32'
  47279. };
  47280. const GPUTextureFormat = {
  47281. // 8-bit formats
  47282. R8Unorm: 'r8unorm',
  47283. R8Snorm: 'r8snorm',
  47284. R8Uint: 'r8uint',
  47285. R8Sint: 'r8sint',
  47286. // 16-bit formats
  47287. R16Uint: 'r16uint',
  47288. R16Sint: 'r16sint',
  47289. R16Float: 'r16float',
  47290. RG8Unorm: 'rg8unorm',
  47291. RG8Snorm: 'rg8snorm',
  47292. RG8Uint: 'rg8uint',
  47293. RG8Sint: 'rg8sint',
  47294. // 32-bit formats
  47295. R32Uint: 'r32uint',
  47296. R32Sint: 'r32sint',
  47297. R32Float: 'r32float',
  47298. RG16Uint: 'rg16uint',
  47299. RG16Sint: 'rg16sint',
  47300. RG16Float: 'rg16float',
  47301. RGBA8Unorm: 'rgba8unorm',
  47302. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  47303. RGBA8Snorm: 'rgba8snorm',
  47304. RGBA8Uint: 'rgba8uint',
  47305. RGBA8Sint: 'rgba8sint',
  47306. BGRA8Unorm: 'bgra8unorm',
  47307. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  47308. // Packed 32-bit formats
  47309. RGB9E5UFloat: 'rgb9e5ufloat',
  47310. RGB10A2Unorm: 'rgb10a2unorm',
  47311. RG11B10UFloat: 'rg11b10ufloat',
  47312. // 64-bit formats
  47313. RG32Uint: 'rg32uint',
  47314. RG32Sint: 'rg32sint',
  47315. RG32Float: 'rg32float',
  47316. RGBA16Uint: 'rgba16uint',
  47317. RGBA16Sint: 'rgba16sint',
  47318. RGBA16Float: 'rgba16float',
  47319. // 128-bit formats
  47320. RGBA32Uint: 'rgba32uint',
  47321. RGBA32Sint: 'rgba32sint',
  47322. RGBA32Float: 'rgba32float',
  47323. Depth16Unorm: 'depth16unorm',
  47324. Depth24Plus: 'depth24plus',
  47325. Depth24PlusStencil8: 'depth24plus-stencil8',
  47326. Depth32Float: 'depth32float',
  47327. // 'depth32float-stencil8' extension
  47328. Depth32FloatStencil8: 'depth32float-stencil8',
  47329. // BC compressed formats usable if 'texture-compression-bc' is both
  47330. // supported by the device/user agent and enabled in requestDevice.
  47331. BC1RGBAUnorm: 'bc1-rgba-unorm',
  47332. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  47333. BC2RGBAUnorm: 'bc2-rgba-unorm',
  47334. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  47335. BC3RGBAUnorm: 'bc3-rgba-unorm',
  47336. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  47337. BC4RUnorm: 'bc4-r-unorm',
  47338. BC4RSnorm: 'bc4-r-snorm',
  47339. BC5RGUnorm: 'bc5-rg-unorm',
  47340. BC5RGSnorm: 'bc5-rg-snorm',
  47341. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  47342. BC6HRGBFloat: 'bc6h-rgb-float',
  47343. BC7RGBAUnorm: 'bc7-rgba-unorm',
  47344. BC7RGBAUnormSRGB: 'bc7-rgba-unorm-srgb',
  47345. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  47346. // supported by the device/user agent and enabled in requestDevice.
  47347. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  47348. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  47349. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  47350. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  47351. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  47352. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  47353. EACR11Unorm: 'eac-r11unorm',
  47354. EACR11Snorm: 'eac-r11snorm',
  47355. EACRG11Unorm: 'eac-rg11unorm',
  47356. EACRG11Snorm: 'eac-rg11snorm',
  47357. // ASTC compressed formats usable if 'texture-compression-astc' is both
  47358. // supported by the device/user agent and enabled in requestDevice.
  47359. ASTC4x4Unorm: 'astc-4x4-unorm',
  47360. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  47361. ASTC5x4Unorm: 'astc-5x4-unorm',
  47362. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  47363. ASTC5x5Unorm: 'astc-5x5-unorm',
  47364. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  47365. ASTC6x5Unorm: 'astc-6x5-unorm',
  47366. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  47367. ASTC6x6Unorm: 'astc-6x6-unorm',
  47368. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  47369. ASTC8x5Unorm: 'astc-8x5-unorm',
  47370. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  47371. ASTC8x6Unorm: 'astc-8x6-unorm',
  47372. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  47373. ASTC8x8Unorm: 'astc-8x8-unorm',
  47374. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  47375. ASTC10x5Unorm: 'astc-10x5-unorm',
  47376. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  47377. ASTC10x6Unorm: 'astc-10x6-unorm',
  47378. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  47379. ASTC10x8Unorm: 'astc-10x8-unorm',
  47380. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  47381. ASTC10x10Unorm: 'astc-10x10-unorm',
  47382. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  47383. ASTC12x10Unorm: 'astc-12x10-unorm',
  47384. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  47385. ASTC12x12Unorm: 'astc-12x12-unorm',
  47386. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  47387. };
  47388. const GPUAddressMode = {
  47389. ClampToEdge: 'clamp-to-edge',
  47390. Repeat: 'repeat',
  47391. MirrorRepeat: 'mirror-repeat'
  47392. };
  47393. const GPUFilterMode = {
  47394. Linear: 'linear',
  47395. Nearest: 'nearest'
  47396. };
  47397. const GPUBlendFactor = {
  47398. Zero: 'zero',
  47399. One: 'one',
  47400. Src: 'src',
  47401. OneMinusSrc: 'one-minus-src',
  47402. SrcAlpha: 'src-alpha',
  47403. OneMinusSrcAlpha: 'one-minus-src-alpha',
  47404. Dst: 'dst',
  47405. OneMinusDst: 'one-minus-dst',
  47406. DstAlpha: 'dst-alpha',
  47407. OneMinusDstAlpha: 'one-minus-dst-alpha',
  47408. SrcAlphaSaturated: 'src-alpha-saturated',
  47409. Constant: 'constant',
  47410. OneMinusConstant: 'one-minus-constant'
  47411. };
  47412. const GPUBlendOperation = {
  47413. Add: 'add',
  47414. Subtract: 'subtract',
  47415. ReverseSubtract: 'reverse-subtract',
  47416. Min: 'min',
  47417. Max: 'max'
  47418. };
  47419. const GPUColorWriteFlags = {
  47420. None: 0,
  47421. All: 0xF
  47422. };
  47423. const GPUStencilOperation = {
  47424. Keep: 'keep',
  47425. Zero: 'zero',
  47426. Replace: 'replace',
  47427. Invert: 'invert',
  47428. IncrementClamp: 'increment-clamp',
  47429. DecrementClamp: 'decrement-clamp',
  47430. IncrementWrap: 'increment-wrap',
  47431. DecrementWrap: 'decrement-wrap'
  47432. };
  47433. const GPUBufferBindingType = {
  47434. Storage: 'storage',
  47435. ReadOnlyStorage: 'read-only-storage'
  47436. };
  47437. const GPUStorageTextureAccess = {
  47438. WriteOnly: 'write-only',
  47439. ReadOnly: 'read-only',
  47440. ReadWrite: 'read-write',
  47441. };
  47442. const GPUSamplerBindingType = {
  47443. NonFiltering: 'non-filtering',
  47444. Comparison: 'comparison'
  47445. };
  47446. const GPUTextureSampleType = {
  47447. Float: 'float',
  47448. UnfilterableFloat: 'unfilterable-float',
  47449. Depth: 'depth',
  47450. SInt: 'sint',
  47451. UInt: 'uint'
  47452. };
  47453. const GPUTextureDimension = {
  47454. TwoD: '2d',
  47455. ThreeD: '3d'
  47456. };
  47457. const GPUTextureViewDimension = {
  47458. TwoD: '2d',
  47459. TwoDArray: '2d-array',
  47460. Cube: 'cube',
  47461. ThreeD: '3d'
  47462. };
  47463. const GPUTextureAspect = {
  47464. All: 'all'};
  47465. const GPUInputStepMode = {
  47466. Vertex: 'vertex',
  47467. Instance: 'instance'
  47468. };
  47469. const GPUFeatureName = {
  47470. CoreFeaturesAndLimits: 'core-features-and-limits',
  47471. DepthClipControl: 'depth-clip-control',
  47472. Depth32FloatStencil8: 'depth32float-stencil8',
  47473. TextureCompressionBC: 'texture-compression-bc',
  47474. TextureCompressionBCSliced3D: 'texture-compression-bc-sliced-3d',
  47475. TextureCompressionETC2: 'texture-compression-etc2',
  47476. TextureCompressionASTC: 'texture-compression-astc',
  47477. TextureCompressionASTCSliced3D: 'texture-compression-astc-sliced-3d',
  47478. TimestampQuery: 'timestamp-query',
  47479. IndirectFirstInstance: 'indirect-first-instance',
  47480. ShaderF16: 'shader-f16',
  47481. RG11B10UFloat: 'rg11b10ufloat-renderable',
  47482. BGRA8UNormStorage: 'bgra8unorm-storage',
  47483. Float32Filterable: 'float32-filterable',
  47484. Float32Blendable: 'float32-blendable',
  47485. ClipDistances: 'clip-distances',
  47486. DualSourceBlending: 'dual-source-blending',
  47487. Subgroups: 'subgroups',
  47488. TextureFormatsTier1: 'texture-formats-tier1',
  47489. TextureFormatsTier2: 'texture-formats-tier2'
  47490. };
  47491. /**
  47492. * A special form of sampler binding type.
  47493. * It's texture value is managed by a node object.
  47494. *
  47495. * @private
  47496. * @augments Sampler
  47497. */
  47498. class NodeSampler extends Sampler {
  47499. /**
  47500. * Constructs a new node-based sampler.
  47501. *
  47502. * @param {string} name - The samplers's name.
  47503. * @param {TextureNode} textureNode - The texture node.
  47504. * @param {UniformGroupNode} groupNode - The uniform group node.
  47505. */
  47506. constructor( name, textureNode, groupNode ) {
  47507. super( name, textureNode ? textureNode.value : null );
  47508. /**
  47509. * The texture node.
  47510. *
  47511. * @type {TextureNode}
  47512. */
  47513. this.textureNode = textureNode;
  47514. /**
  47515. * The uniform group node.
  47516. *
  47517. * @type {UniformGroupNode}
  47518. */
  47519. this.groupNode = groupNode;
  47520. }
  47521. /**
  47522. * Updates the texture value of this sampler.
  47523. */
  47524. update() {
  47525. this.texture = this.textureNode.value;
  47526. }
  47527. }
  47528. /**
  47529. * Represents a storage buffer binding type.
  47530. *
  47531. * @private
  47532. * @augments Buffer
  47533. */
  47534. class StorageBuffer extends Buffer {
  47535. /**
  47536. * Constructs a new uniform buffer.
  47537. *
  47538. * @param {string} name - The buffer's name.
  47539. * @param {BufferAttribute} attribute - The buffer attribute.
  47540. */
  47541. constructor( name, attribute ) {
  47542. super( name, attribute ? attribute.array : null );
  47543. /**
  47544. * This flag can be used for type testing.
  47545. *
  47546. * @type {BufferAttribute}
  47547. */
  47548. this.attribute = attribute;
  47549. /**
  47550. * This flag can be used for type testing.
  47551. *
  47552. * @type {boolean}
  47553. * @readonly
  47554. * @default true
  47555. */
  47556. this.isStorageBuffer = true;
  47557. }
  47558. }
  47559. let _id = 0;
  47560. /**
  47561. * A special form of storage buffer binding type.
  47562. * It's buffer value is managed by a node object.
  47563. *
  47564. * @private
  47565. * @augments StorageBuffer
  47566. */
  47567. class NodeStorageBuffer extends StorageBuffer {
  47568. /**
  47569. * Constructs a new node-based storage buffer.
  47570. *
  47571. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  47572. * @param {UniformGroupNode} groupNode - The uniform group node.
  47573. */
  47574. constructor( nodeUniform, groupNode ) {
  47575. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  47576. /**
  47577. * The node uniform.
  47578. *
  47579. * @type {StorageBufferNode}
  47580. */
  47581. this.nodeUniform = nodeUniform;
  47582. /**
  47583. * The access type.
  47584. *
  47585. * @type {string}
  47586. */
  47587. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  47588. /**
  47589. * The uniform group node.
  47590. *
  47591. * @type {UniformGroupNode}
  47592. */
  47593. this.groupNode = groupNode;
  47594. }
  47595. /**
  47596. * The storage buffer.
  47597. *
  47598. * @type {BufferAttribute}
  47599. */
  47600. get buffer() {
  47601. return this.nodeUniform.value;
  47602. }
  47603. }
  47604. /**
  47605. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  47606. *
  47607. * @private
  47608. */
  47609. class WebGPUTexturePassUtils extends DataMap {
  47610. /**
  47611. * Constructs a new utility object.
  47612. *
  47613. * @param {GPUDevice} device - The WebGPU device.
  47614. */
  47615. constructor( device ) {
  47616. super();
  47617. /**
  47618. * The WebGPU device.
  47619. *
  47620. * @type {GPUDevice}
  47621. */
  47622. this.device = device;
  47623. const mipmapVertexSource = `
  47624. struct VarysStruct {
  47625. @builtin( position ) Position: vec4<f32>,
  47626. @location( 0 ) vTex : vec2<f32>
  47627. };
  47628. @vertex
  47629. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  47630. var Varys : VarysStruct;
  47631. var pos = array< vec2<f32>, 4 >(
  47632. vec2<f32>( -1.0, 1.0 ),
  47633. vec2<f32>( 1.0, 1.0 ),
  47634. vec2<f32>( -1.0, -1.0 ),
  47635. vec2<f32>( 1.0, -1.0 )
  47636. );
  47637. var tex = array< vec2<f32>, 4 >(
  47638. vec2<f32>( 0.0, 0.0 ),
  47639. vec2<f32>( 1.0, 0.0 ),
  47640. vec2<f32>( 0.0, 1.0 ),
  47641. vec2<f32>( 1.0, 1.0 )
  47642. );
  47643. Varys.vTex = tex[ vertexIndex ];
  47644. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  47645. return Varys;
  47646. }
  47647. `;
  47648. const mipmapFragmentSource = `
  47649. @group( 0 ) @binding( 0 )
  47650. var imgSampler : sampler;
  47651. @group( 0 ) @binding( 1 )
  47652. var img : texture_2d<f32>;
  47653. @fragment
  47654. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  47655. return textureSample( img, imgSampler, vTex );
  47656. }
  47657. `;
  47658. const flipYFragmentSource = `
  47659. @group( 0 ) @binding( 0 )
  47660. var imgSampler : sampler;
  47661. @group( 0 ) @binding( 1 )
  47662. var img : texture_2d<f32>;
  47663. @fragment
  47664. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  47665. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  47666. }
  47667. `;
  47668. /**
  47669. * The mipmap GPU sampler.
  47670. *
  47671. * @type {GPUSampler}
  47672. */
  47673. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  47674. /**
  47675. * The flipY GPU sampler.
  47676. *
  47677. * @type {GPUSampler}
  47678. */
  47679. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  47680. /**
  47681. * A cache for GPU render pipelines used for copy/transfer passes.
  47682. * Every texture format requires a unique pipeline.
  47683. *
  47684. * @type {Object<string,GPURenderPipeline>}
  47685. */
  47686. this.transferPipelines = {};
  47687. /**
  47688. * A cache for GPU render pipelines used for flipY passes.
  47689. * Every texture format requires a unique pipeline.
  47690. *
  47691. * @type {Object<string,GPURenderPipeline>}
  47692. */
  47693. this.flipYPipelines = {};
  47694. /**
  47695. * The mipmap vertex shader module.
  47696. *
  47697. * @type {GPUShaderModule}
  47698. */
  47699. this.mipmapVertexShaderModule = device.createShaderModule( {
  47700. label: 'mipmapVertex',
  47701. code: mipmapVertexSource
  47702. } );
  47703. /**
  47704. * The mipmap fragment shader module.
  47705. *
  47706. * @type {GPUShaderModule}
  47707. */
  47708. this.mipmapFragmentShaderModule = device.createShaderModule( {
  47709. label: 'mipmapFragment',
  47710. code: mipmapFragmentSource
  47711. } );
  47712. /**
  47713. * The flipY fragment shader module.
  47714. *
  47715. * @type {GPUShaderModule}
  47716. */
  47717. this.flipYFragmentShaderModule = device.createShaderModule( {
  47718. label: 'flipYFragment',
  47719. code: flipYFragmentSource
  47720. } );
  47721. }
  47722. /**
  47723. * Returns a render pipeline for the internal copy render pass. The pass
  47724. * requires a unique render pipeline for each texture format.
  47725. *
  47726. * @param {string} format - The GPU texture format
  47727. * @return {GPURenderPipeline} The GPU render pipeline.
  47728. */
  47729. getTransferPipeline( format ) {
  47730. let pipeline = this.transferPipelines[ format ];
  47731. if ( pipeline === undefined ) {
  47732. pipeline = this.device.createRenderPipeline( {
  47733. label: `mipmap-${ format }`,
  47734. vertex: {
  47735. module: this.mipmapVertexShaderModule,
  47736. entryPoint: 'main'
  47737. },
  47738. fragment: {
  47739. module: this.mipmapFragmentShaderModule,
  47740. entryPoint: 'main',
  47741. targets: [ { format } ]
  47742. },
  47743. primitive: {
  47744. topology: GPUPrimitiveTopology.TriangleStrip,
  47745. stripIndexFormat: GPUIndexFormat.Uint32
  47746. },
  47747. layout: 'auto'
  47748. } );
  47749. this.transferPipelines[ format ] = pipeline;
  47750. }
  47751. return pipeline;
  47752. }
  47753. /**
  47754. * Returns a render pipeline for the flipY render pass. The pass
  47755. * requires a unique render pipeline for each texture format.
  47756. *
  47757. * @param {string} format - The GPU texture format
  47758. * @return {GPURenderPipeline} The GPU render pipeline.
  47759. */
  47760. getFlipYPipeline( format ) {
  47761. let pipeline = this.flipYPipelines[ format ];
  47762. if ( pipeline === undefined ) {
  47763. pipeline = this.device.createRenderPipeline( {
  47764. label: `flipY-${ format }`,
  47765. vertex: {
  47766. module: this.mipmapVertexShaderModule,
  47767. entryPoint: 'main'
  47768. },
  47769. fragment: {
  47770. module: this.flipYFragmentShaderModule,
  47771. entryPoint: 'main',
  47772. targets: [ { format } ]
  47773. },
  47774. primitive: {
  47775. topology: GPUPrimitiveTopology.TriangleStrip,
  47776. stripIndexFormat: GPUIndexFormat.Uint32
  47777. },
  47778. layout: 'auto'
  47779. } );
  47780. this.flipYPipelines[ format ] = pipeline;
  47781. }
  47782. return pipeline;
  47783. }
  47784. /**
  47785. * Flip the contents of the given GPU texture along its vertical axis.
  47786. *
  47787. * @param {GPUTexture} textureGPU - The GPU texture object.
  47788. * @param {Object} textureGPUDescriptor - The texture descriptor.
  47789. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  47790. */
  47791. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  47792. const format = textureGPUDescriptor.format;
  47793. const { width, height } = textureGPUDescriptor.size;
  47794. const transferPipeline = this.getTransferPipeline( format );
  47795. const flipYPipeline = this.getFlipYPipeline( format );
  47796. const tempTexture = this.device.createTexture( {
  47797. size: { width, height, depthOrArrayLayers: 1 },
  47798. format,
  47799. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  47800. } );
  47801. const srcView = textureGPU.createView( {
  47802. baseMipLevel: 0,
  47803. mipLevelCount: 1,
  47804. dimension: GPUTextureViewDimension.TwoD,
  47805. baseArrayLayer
  47806. } );
  47807. const dstView = tempTexture.createView( {
  47808. baseMipLevel: 0,
  47809. mipLevelCount: 1,
  47810. dimension: GPUTextureViewDimension.TwoD,
  47811. baseArrayLayer: 0
  47812. } );
  47813. const commandEncoder = this.device.createCommandEncoder( {} );
  47814. const pass = ( pipeline, sourceView, destinationView ) => {
  47815. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  47816. const bindGroup = this.device.createBindGroup( {
  47817. layout: bindGroupLayout,
  47818. entries: [ {
  47819. binding: 0,
  47820. resource: this.flipYSampler
  47821. }, {
  47822. binding: 1,
  47823. resource: sourceView
  47824. } ]
  47825. } );
  47826. const passEncoder = commandEncoder.beginRenderPass( {
  47827. colorAttachments: [ {
  47828. view: destinationView,
  47829. loadOp: GPULoadOp.Clear,
  47830. storeOp: GPUStoreOp.Store,
  47831. clearValue: [ 0, 0, 0, 0 ]
  47832. } ]
  47833. } );
  47834. passEncoder.setPipeline( pipeline );
  47835. passEncoder.setBindGroup( 0, bindGroup );
  47836. passEncoder.draw( 4, 1, 0, 0 );
  47837. passEncoder.end();
  47838. };
  47839. pass( transferPipeline, srcView, dstView );
  47840. pass( flipYPipeline, dstView, srcView );
  47841. this.device.queue.submit( [ commandEncoder.finish() ] );
  47842. tempTexture.destroy();
  47843. }
  47844. /**
  47845. * Generates mipmaps for the given GPU texture.
  47846. *
  47847. * @param {GPUTexture} textureGPU - The GPU texture object.
  47848. * @param {Object} textureGPUDescriptor - The texture descriptor.
  47849. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  47850. */
  47851. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  47852. const textureData = this.get( textureGPU );
  47853. if ( textureData.useCount === undefined ) {
  47854. textureData.useCount = 0;
  47855. textureData.layers = [];
  47856. }
  47857. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  47858. const commandEncoder = this.device.createCommandEncoder( {} );
  47859. this._mipmapRunBundles( commandEncoder, passes );
  47860. this.device.queue.submit( [ commandEncoder.finish() ] );
  47861. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  47862. textureData.useCount ++;
  47863. }
  47864. /**
  47865. * Since multiple copy render passes are required to generate mipmaps, the passes
  47866. * are managed as render bundles to improve performance.
  47867. *
  47868. * @param {GPUTexture} textureGPU - The GPU texture object.
  47869. * @param {Object} textureGPUDescriptor - The texture descriptor.
  47870. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  47871. * @return {Array<Object>} An array of render bundles.
  47872. */
  47873. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  47874. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  47875. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  47876. let srcView = textureGPU.createView( {
  47877. baseMipLevel: 0,
  47878. mipLevelCount: 1,
  47879. dimension: GPUTextureViewDimension.TwoD,
  47880. baseArrayLayer
  47881. } );
  47882. const passes = [];
  47883. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  47884. const bindGroup = this.device.createBindGroup( {
  47885. layout: bindGroupLayout,
  47886. entries: [ {
  47887. binding: 0,
  47888. resource: this.mipmapSampler
  47889. }, {
  47890. binding: 1,
  47891. resource: srcView
  47892. } ]
  47893. } );
  47894. const dstView = textureGPU.createView( {
  47895. baseMipLevel: i,
  47896. mipLevelCount: 1,
  47897. dimension: GPUTextureViewDimension.TwoD,
  47898. baseArrayLayer
  47899. } );
  47900. const passDescriptor = {
  47901. colorAttachments: [ {
  47902. view: dstView,
  47903. loadOp: GPULoadOp.Clear,
  47904. storeOp: GPUStoreOp.Store,
  47905. clearValue: [ 0, 0, 0, 0 ]
  47906. } ]
  47907. };
  47908. const passEncoder = this.device.createRenderBundleEncoder( {
  47909. colorFormats: [ textureGPUDescriptor.format ]
  47910. } );
  47911. passEncoder.setPipeline( pipeline );
  47912. passEncoder.setBindGroup( 0, bindGroup );
  47913. passEncoder.draw( 4, 1, 0, 0 );
  47914. passes.push( {
  47915. renderBundles: [ passEncoder.finish() ],
  47916. passDescriptor
  47917. } );
  47918. srcView = dstView;
  47919. }
  47920. return passes;
  47921. }
  47922. /**
  47923. * Executes the render bundles.
  47924. *
  47925. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  47926. * @param {Array<Object>} passes - An array of render bundles.
  47927. */
  47928. _mipmapRunBundles( commandEncoder, passes ) {
  47929. const levels = passes.length;
  47930. for ( let i = 0; i < levels; i ++ ) {
  47931. const pass = passes[ i ];
  47932. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  47933. passEncoder.executeBundles( pass.renderBundles );
  47934. passEncoder.end();
  47935. }
  47936. }
  47937. }
  47938. const _compareToWebGPU = {
  47939. [ NeverCompare ]: 'never',
  47940. [ LessCompare ]: 'less',
  47941. [ EqualCompare ]: 'equal',
  47942. [ LessEqualCompare ]: 'less-equal',
  47943. [ GreaterCompare ]: 'greater',
  47944. [ GreaterEqualCompare ]: 'greater-equal',
  47945. [ AlwaysCompare ]: 'always',
  47946. [ NotEqualCompare ]: 'not-equal'
  47947. };
  47948. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  47949. /**
  47950. * A WebGPU backend utility module for managing textures.
  47951. *
  47952. * @private
  47953. */
  47954. class WebGPUTextureUtils {
  47955. /**
  47956. * Constructs a new utility object.
  47957. *
  47958. * @param {WebGPUBackend} backend - The WebGPU backend.
  47959. */
  47960. constructor( backend ) {
  47961. /**
  47962. * A reference to the WebGPU backend.
  47963. *
  47964. * @type {WebGPUBackend}
  47965. */
  47966. this.backend = backend;
  47967. /**
  47968. * A reference to the pass utils.
  47969. *
  47970. * @type {?WebGPUTexturePassUtils}
  47971. * @default null
  47972. */
  47973. this._passUtils = null;
  47974. /**
  47975. * A dictionary for managing default textures. The key
  47976. * is the texture format, the value the texture object.
  47977. *
  47978. * @type {Object<string,Texture>}
  47979. */
  47980. this.defaultTexture = {};
  47981. /**
  47982. * A dictionary for managing default cube textures. The key
  47983. * is the texture format, the value the texture object.
  47984. *
  47985. * @type {Object<string,CubeTexture>}
  47986. */
  47987. this.defaultCubeTexture = {};
  47988. /**
  47989. * A default video frame.
  47990. *
  47991. * @type {?VideoFrame}
  47992. * @default null
  47993. */
  47994. this.defaultVideoFrame = null;
  47995. /**
  47996. * Represents the color attachment of the default framebuffer.
  47997. *
  47998. * @type {?GPUTexture}
  47999. * @default null
  48000. */
  48001. this.colorBuffer = null;
  48002. /**
  48003. * Represents the depth attachment of the default framebuffer.
  48004. *
  48005. * @type {DepthTexture}
  48006. */
  48007. this.depthTexture = new DepthTexture();
  48008. this.depthTexture.name = 'depthBuffer';
  48009. }
  48010. /**
  48011. * Creates a GPU sampler for the given texture.
  48012. *
  48013. * @param {Texture} texture - The texture to create the sampler for.
  48014. */
  48015. createSampler( texture ) {
  48016. const backend = this.backend;
  48017. const device = backend.device;
  48018. const textureGPU = backend.get( texture );
  48019. const samplerDescriptorGPU = {
  48020. addressModeU: this._convertAddressMode( texture.wrapS ),
  48021. addressModeV: this._convertAddressMode( texture.wrapT ),
  48022. addressModeW: this._convertAddressMode( texture.wrapR ),
  48023. magFilter: this._convertFilterMode( texture.magFilter ),
  48024. minFilter: this._convertFilterMode( texture.minFilter ),
  48025. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  48026. maxAnisotropy: 1
  48027. };
  48028. // anisotropy can only be used when all filter modes are set to linear.
  48029. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  48030. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  48031. }
  48032. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  48033. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  48034. }
  48035. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  48036. }
  48037. /**
  48038. * Creates a default texture for the given texture that can be used
  48039. * as a placeholder until the actual texture is ready for usage.
  48040. *
  48041. * @param {Texture} texture - The texture to create a default texture for.
  48042. */
  48043. createDefaultTexture( texture ) {
  48044. let textureGPU;
  48045. const format = getFormat( texture );
  48046. if ( texture.isCubeTexture ) {
  48047. textureGPU = this._getDefaultCubeTextureGPU( format );
  48048. } else {
  48049. textureGPU = this._getDefaultTextureGPU( format );
  48050. }
  48051. this.backend.get( texture ).texture = textureGPU;
  48052. }
  48053. /**
  48054. * Defines a texture on the GPU for the given texture object.
  48055. *
  48056. * @param {Texture} texture - The texture.
  48057. * @param {Object} [options={}] - Optional configuration parameter.
  48058. */
  48059. createTexture( texture, options = {} ) {
  48060. const backend = this.backend;
  48061. const textureData = backend.get( texture );
  48062. if ( textureData.initialized ) {
  48063. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  48064. }
  48065. if ( texture.isExternalTexture ) {
  48066. textureData.texture = texture.sourceTexture;
  48067. textureData.initialized = true;
  48068. return;
  48069. }
  48070. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  48071. if ( options.levels === undefined ) options.levels = 1;
  48072. if ( options.depth === undefined ) options.depth = 1;
  48073. const { width, height, depth, levels } = options;
  48074. if ( texture.isFramebufferTexture ) {
  48075. if ( options.renderTarget ) {
  48076. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  48077. } else {
  48078. options.format = this.backend.utils.getPreferredCanvasFormat();
  48079. }
  48080. }
  48081. const dimension = this._getDimension( texture );
  48082. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  48083. textureData.format = format;
  48084. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  48085. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  48086. if ( texture.isStorageTexture === true ) {
  48087. usage |= GPUTextureUsage.STORAGE_BINDING;
  48088. }
  48089. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true && format !== GPUTextureFormat.RGB9E5UFloat ) {
  48090. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  48091. }
  48092. const textureDescriptorGPU = {
  48093. label: texture.name,
  48094. size: {
  48095. width: width,
  48096. height: height,
  48097. depthOrArrayLayers: depth,
  48098. },
  48099. mipLevelCount: levels,
  48100. sampleCount: primarySamples,
  48101. dimension: dimension,
  48102. format: format,
  48103. usage: usage
  48104. };
  48105. // texture creation
  48106. if ( format === undefined ) {
  48107. console.warn( 'WebGPURenderer: Texture format not supported.' );
  48108. this.createDefaultTexture( texture );
  48109. return;
  48110. }
  48111. if ( texture.isCubeTexture ) {
  48112. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  48113. }
  48114. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  48115. if ( isMSAA ) {
  48116. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  48117. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  48118. msaaTextureDescriptorGPU.sampleCount = samples;
  48119. msaaTextureDescriptorGPU.mipLevelCount = 1; // See https://www.w3.org/TR/webgpu/#texture-creation
  48120. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  48121. }
  48122. textureData.initialized = true;
  48123. textureData.textureDescriptorGPU = textureDescriptorGPU;
  48124. }
  48125. /**
  48126. * Destroys the GPU data for the given texture object.
  48127. *
  48128. * @param {Texture} texture - The texture.
  48129. */
  48130. destroyTexture( texture ) {
  48131. const backend = this.backend;
  48132. const textureData = backend.get( texture );
  48133. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  48134. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  48135. backend.delete( texture );
  48136. }
  48137. /**
  48138. * Destroys the GPU sampler for the given texture.
  48139. *
  48140. * @param {Texture} texture - The texture to destroy the sampler for.
  48141. */
  48142. destroySampler( texture ) {
  48143. const backend = this.backend;
  48144. const textureData = backend.get( texture );
  48145. delete textureData.sampler;
  48146. }
  48147. /**
  48148. * Generates mipmaps for the given texture.
  48149. *
  48150. * @param {Texture} texture - The texture.
  48151. */
  48152. generateMipmaps( texture ) {
  48153. const textureData = this.backend.get( texture );
  48154. if ( texture.isCubeTexture ) {
  48155. for ( let i = 0; i < 6; i ++ ) {
  48156. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  48157. }
  48158. } else {
  48159. const depth = texture.image.depth || 1;
  48160. for ( let i = 0; i < depth; i ++ ) {
  48161. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  48162. }
  48163. }
  48164. }
  48165. /**
  48166. * Returns the color buffer representing the color
  48167. * attachment of the default framebuffer.
  48168. *
  48169. * @return {GPUTexture} The color buffer.
  48170. */
  48171. getColorBuffer() {
  48172. if ( this.colorBuffer ) this.colorBuffer.destroy();
  48173. const backend = this.backend;
  48174. const { width, height } = backend.getDrawingBufferSize();
  48175. this.colorBuffer = backend.device.createTexture( {
  48176. label: 'colorBuffer',
  48177. size: {
  48178. width: width,
  48179. height: height,
  48180. depthOrArrayLayers: 1
  48181. },
  48182. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  48183. format: backend.utils.getPreferredCanvasFormat(),
  48184. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  48185. } );
  48186. return this.colorBuffer;
  48187. }
  48188. /**
  48189. * Returns the depth buffer representing the depth
  48190. * attachment of the default framebuffer.
  48191. *
  48192. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  48193. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  48194. * @return {GPUTexture} The depth buffer.
  48195. */
  48196. getDepthBuffer( depth = true, stencil = false ) {
  48197. const backend = this.backend;
  48198. const { width, height } = backend.getDrawingBufferSize();
  48199. const depthTexture = this.depthTexture;
  48200. const depthTextureGPU = backend.get( depthTexture ).texture;
  48201. let format, type;
  48202. if ( stencil ) {
  48203. format = DepthStencilFormat;
  48204. type = UnsignedInt248Type;
  48205. } else if ( depth ) {
  48206. format = DepthFormat;
  48207. type = UnsignedIntType;
  48208. }
  48209. if ( depthTextureGPU !== undefined ) {
  48210. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  48211. return depthTextureGPU;
  48212. }
  48213. this.destroyTexture( depthTexture );
  48214. }
  48215. depthTexture.name = 'depthBuffer';
  48216. depthTexture.format = format;
  48217. depthTexture.type = type;
  48218. depthTexture.image.width = width;
  48219. depthTexture.image.height = height;
  48220. this.createTexture( depthTexture, { width, height } );
  48221. return backend.get( depthTexture ).texture;
  48222. }
  48223. /**
  48224. * Uploads the updated texture data to the GPU.
  48225. *
  48226. * @param {Texture} texture - The texture.
  48227. * @param {Object} [options={}] - Optional configuration parameter.
  48228. */
  48229. updateTexture( texture, options ) {
  48230. const textureData = this.backend.get( texture );
  48231. const mipmaps = texture.mipmaps;
  48232. const { textureDescriptorGPU } = textureData;
  48233. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  48234. return;
  48235. // transfer texture data
  48236. if ( texture.isDataTexture ) {
  48237. if ( mipmaps.length > 0 ) {
  48238. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  48239. const mipmap = mipmaps[ i ];
  48240. this._copyBufferToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, 0, i );
  48241. }
  48242. } else {
  48243. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  48244. }
  48245. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  48246. for ( let i = 0; i < options.image.depth; i ++ ) {
  48247. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  48248. }
  48249. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  48250. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  48251. } else if ( texture.isCubeTexture ) {
  48252. this._copyCubeMapToTexture( texture, textureData.texture, textureDescriptorGPU );
  48253. } else {
  48254. if ( mipmaps.length > 0 ) {
  48255. for ( let i = 0, il = mipmaps.length; i < il; i ++ ) {
  48256. const mipmap = mipmaps[ i ];
  48257. this._copyImageToTexture( mipmap, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha, i );
  48258. }
  48259. } else {
  48260. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  48261. }
  48262. }
  48263. //
  48264. textureData.version = texture.version;
  48265. }
  48266. /**
  48267. * Returns texture data as a typed array.
  48268. *
  48269. * @async
  48270. * @param {Texture} texture - The texture to copy.
  48271. * @param {number} x - The x coordinate of the copy origin.
  48272. * @param {number} y - The y coordinate of the copy origin.
  48273. * @param {number} width - The width of the copy.
  48274. * @param {number} height - The height of the copy.
  48275. * @param {number} faceIndex - The face index.
  48276. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  48277. */
  48278. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  48279. const device = this.backend.device;
  48280. const textureData = this.backend.get( texture );
  48281. const textureGPU = textureData.texture;
  48282. const format = textureData.textureDescriptorGPU.format;
  48283. const bytesPerTexel = this._getBytesPerTexel( format );
  48284. let bytesPerRow = width * bytesPerTexel;
  48285. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  48286. const readBuffer = device.createBuffer(
  48287. {
  48288. size: ( ( height - 1 ) * bytesPerRow ) + ( width * bytesPerTexel ), // see https://github.com/mrdoob/three.js/issues/31658#issuecomment-3229442010
  48289. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  48290. }
  48291. );
  48292. const encoder = device.createCommandEncoder();
  48293. encoder.copyTextureToBuffer(
  48294. {
  48295. texture: textureGPU,
  48296. origin: { x, y, z: faceIndex },
  48297. },
  48298. {
  48299. buffer: readBuffer,
  48300. bytesPerRow: bytesPerRow
  48301. },
  48302. {
  48303. width: width,
  48304. height: height
  48305. }
  48306. );
  48307. const typedArrayType = this._getTypedArrayType( format );
  48308. device.queue.submit( [ encoder.finish() ] );
  48309. await readBuffer.mapAsync( GPUMapMode.READ );
  48310. const buffer = readBuffer.getMappedRange();
  48311. return new typedArrayType( buffer );
  48312. }
  48313. /**
  48314. * Returns the default GPU texture for the given format.
  48315. *
  48316. * @private
  48317. * @param {string} format - The GPU format.
  48318. * @return {GPUTexture} The GPU texture.
  48319. */
  48320. _getDefaultTextureGPU( format ) {
  48321. let defaultTexture = this.defaultTexture[ format ];
  48322. if ( defaultTexture === undefined ) {
  48323. const texture = new Texture();
  48324. texture.minFilter = NearestFilter;
  48325. texture.magFilter = NearestFilter;
  48326. this.createTexture( texture, { width: 1, height: 1, format } );
  48327. this.defaultTexture[ format ] = defaultTexture = texture;
  48328. }
  48329. return this.backend.get( defaultTexture ).texture;
  48330. }
  48331. /**
  48332. * Returns the default GPU cube texture for the given format.
  48333. *
  48334. * @private
  48335. * @param {string} format - The GPU format.
  48336. * @return {GPUTexture} The GPU texture.
  48337. */
  48338. _getDefaultCubeTextureGPU( format ) {
  48339. let defaultCubeTexture = this.defaultTexture[ format ];
  48340. if ( defaultCubeTexture === undefined ) {
  48341. const texture = new CubeTexture();
  48342. texture.minFilter = NearestFilter;
  48343. texture.magFilter = NearestFilter;
  48344. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  48345. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  48346. }
  48347. return this.backend.get( defaultCubeTexture ).texture;
  48348. }
  48349. /**
  48350. * Uploads cube texture image data to the GPU memory.
  48351. *
  48352. * @private
  48353. * @param {CubeTexture} texture - The cube texture.
  48354. * @param {GPUTexture} textureGPU - The GPU texture.
  48355. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  48356. */
  48357. _copyCubeMapToTexture( texture, textureGPU, textureDescriptorGPU ) {
  48358. const images = texture.images;
  48359. const mipmaps = texture.mipmaps;
  48360. for ( let i = 0; i < 6; i ++ ) {
  48361. const image = images[ i ];
  48362. const flipIndex = texture.flipY === true ? _flipMap[ i ] : i;
  48363. if ( image.isDataTexture ) {
  48364. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY );
  48365. } else {
  48366. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha );
  48367. }
  48368. for ( let j = 0; j < mipmaps.length; j ++ ) {
  48369. const mipmap = mipmaps[ j ];
  48370. const image = mipmap.images[ i ];
  48371. if ( image.isDataTexture ) {
  48372. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, 0, j + 1 );
  48373. } else {
  48374. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, texture.flipY, texture.premultiplyAlpha, j + 1 );
  48375. }
  48376. }
  48377. }
  48378. }
  48379. /**
  48380. * Uploads texture image data to the GPU memory.
  48381. *
  48382. * @private
  48383. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  48384. * @param {GPUTexture} textureGPU - The GPU texture.
  48385. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  48386. * @param {number} originDepth - The origin depth.
  48387. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  48388. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  48389. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  48390. */
  48391. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha, mipLevel = 0 ) {
  48392. const device = this.backend.device;
  48393. const width = ( mipLevel > 0 ) ? image.width : textureDescriptorGPU.size.width;
  48394. const height = ( mipLevel > 0 ) ? image.height : textureDescriptorGPU.size.height;
  48395. device.queue.copyExternalImageToTexture(
  48396. {
  48397. source: image,
  48398. flipY: flipY
  48399. }, {
  48400. texture: textureGPU,
  48401. mipLevel: mipLevel,
  48402. origin: { x: 0, y: 0, z: originDepth },
  48403. premultipliedAlpha: premultiplyAlpha
  48404. }, {
  48405. width: width,
  48406. height: height,
  48407. depthOrArrayLayers: 1
  48408. }
  48409. );
  48410. }
  48411. /**
  48412. * Returns the pass utils singleton.
  48413. *
  48414. * @private
  48415. * @return {WebGPUTexturePassUtils} The utils instance.
  48416. */
  48417. _getPassUtils() {
  48418. let passUtils = this._passUtils;
  48419. if ( passUtils === null ) {
  48420. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  48421. }
  48422. return passUtils;
  48423. }
  48424. /**
  48425. * Generates mipmaps for the given GPU texture.
  48426. *
  48427. * @private
  48428. * @param {GPUTexture} textureGPU - The GPU texture object.
  48429. * @param {Object} textureDescriptorGPU - The texture descriptor.
  48430. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  48431. */
  48432. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  48433. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  48434. }
  48435. /**
  48436. * Flip the contents of the given GPU texture along its vertical axis.
  48437. *
  48438. * @private
  48439. * @param {GPUTexture} textureGPU - The GPU texture object.
  48440. * @param {Object} textureDescriptorGPU - The texture descriptor.
  48441. * @param {number} [originDepth=0] - The origin depth.
  48442. */
  48443. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  48444. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  48445. }
  48446. /**
  48447. * Uploads texture buffer data to the GPU memory.
  48448. *
  48449. * @private
  48450. * @param {Object} image - An object defining the image buffer data.
  48451. * @param {GPUTexture} textureGPU - The GPU texture.
  48452. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  48453. * @param {number} originDepth - The origin depth.
  48454. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  48455. * @param {number} [depth=0] - The depth offset when copying array or 3D texture data.
  48456. * @param {number} [mipLevel=0] - The mip level where the data should be copied to.
  48457. */
  48458. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0, mipLevel = 0 ) {
  48459. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  48460. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  48461. const device = this.backend.device;
  48462. const data = image.data;
  48463. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  48464. const bytesPerRow = image.width * bytesPerTexel;
  48465. device.queue.writeTexture(
  48466. {
  48467. texture: textureGPU,
  48468. mipLevel: mipLevel,
  48469. origin: { x: 0, y: 0, z: originDepth }
  48470. },
  48471. data,
  48472. {
  48473. offset: image.width * image.height * bytesPerTexel * depth,
  48474. bytesPerRow
  48475. },
  48476. {
  48477. width: image.width,
  48478. height: image.height,
  48479. depthOrArrayLayers: 1
  48480. } );
  48481. if ( flipY === true ) {
  48482. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  48483. }
  48484. }
  48485. /**
  48486. * Uploads compressed texture data to the GPU memory.
  48487. *
  48488. * @private
  48489. * @param {Array<Object>} mipmaps - An array with mipmap data.
  48490. * @param {GPUTexture} textureGPU - The GPU texture.
  48491. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  48492. */
  48493. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  48494. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  48495. const device = this.backend.device;
  48496. const blockData = this._getBlockData( textureDescriptorGPU.format );
  48497. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  48498. for ( let i = 0; i < mipmaps.length; i ++ ) {
  48499. const mipmap = mipmaps[ i ];
  48500. const width = mipmap.width;
  48501. const height = mipmap.height;
  48502. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  48503. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  48504. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  48505. for ( let j = 0; j < depth; j ++ ) {
  48506. device.queue.writeTexture(
  48507. {
  48508. texture: textureGPU,
  48509. mipLevel: i,
  48510. origin: { x: 0, y: 0, z: j }
  48511. },
  48512. mipmap.data,
  48513. {
  48514. offset: j * bytesPerImage,
  48515. bytesPerRow,
  48516. rowsPerImage: Math.ceil( height / blockData.height )
  48517. },
  48518. {
  48519. width: Math.ceil( width / blockData.width ) * blockData.width,
  48520. height: Math.ceil( height / blockData.height ) * blockData.height,
  48521. depthOrArrayLayers: 1
  48522. }
  48523. );
  48524. }
  48525. }
  48526. }
  48527. /**
  48528. * This method is only relevant for compressed texture formats. It returns a block
  48529. * data descriptor for the given GPU compressed texture format.
  48530. *
  48531. * @private
  48532. * @param {string} format - The GPU compressed texture format.
  48533. * @return {Object} The block data descriptor.
  48534. */
  48535. _getBlockData( format ) {
  48536. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  48537. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  48538. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  48539. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  48540. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  48541. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  48542. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  48543. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  48544. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  48545. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  48546. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  48547. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  48548. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  48549. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  48550. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  48551. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  48552. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  48553. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  48554. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  48555. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  48556. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  48557. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  48558. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  48559. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  48560. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  48561. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  48562. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  48563. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  48564. }
  48565. /**
  48566. * Converts the three.js uv wrapping constants to GPU address mode constants.
  48567. *
  48568. * @private
  48569. * @param {number} value - The three.js constant defining a uv wrapping mode.
  48570. * @return {string} The GPU address mode.
  48571. */
  48572. _convertAddressMode( value ) {
  48573. let addressMode = GPUAddressMode.ClampToEdge;
  48574. if ( value === RepeatWrapping ) {
  48575. addressMode = GPUAddressMode.Repeat;
  48576. } else if ( value === MirroredRepeatWrapping ) {
  48577. addressMode = GPUAddressMode.MirrorRepeat;
  48578. }
  48579. return addressMode;
  48580. }
  48581. /**
  48582. * Converts the three.js filter constants to GPU filter constants.
  48583. *
  48584. * @private
  48585. * @param {number} value - The three.js constant defining a filter mode.
  48586. * @return {string} The GPU filter mode.
  48587. */
  48588. _convertFilterMode( value ) {
  48589. let filterMode = GPUFilterMode.Linear;
  48590. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  48591. filterMode = GPUFilterMode.Nearest;
  48592. }
  48593. return filterMode;
  48594. }
  48595. /**
  48596. * Returns the bytes-per-texel value for the given GPU texture format.
  48597. *
  48598. * @private
  48599. * @param {string} format - The GPU texture format.
  48600. * @return {number} The bytes-per-texel.
  48601. */
  48602. _getBytesPerTexel( format ) {
  48603. // 8-bit formats
  48604. if ( format === GPUTextureFormat.R8Unorm ||
  48605. format === GPUTextureFormat.R8Snorm ||
  48606. format === GPUTextureFormat.R8Uint ||
  48607. format === GPUTextureFormat.R8Sint ) return 1;
  48608. // 16-bit formats
  48609. if ( format === GPUTextureFormat.R16Uint ||
  48610. format === GPUTextureFormat.R16Sint ||
  48611. format === GPUTextureFormat.R16Float ||
  48612. format === GPUTextureFormat.RG8Unorm ||
  48613. format === GPUTextureFormat.RG8Snorm ||
  48614. format === GPUTextureFormat.RG8Uint ||
  48615. format === GPUTextureFormat.RG8Sint ) return 2;
  48616. // 32-bit formats
  48617. if ( format === GPUTextureFormat.R32Uint ||
  48618. format === GPUTextureFormat.R32Sint ||
  48619. format === GPUTextureFormat.R32Float ||
  48620. format === GPUTextureFormat.RG16Uint ||
  48621. format === GPUTextureFormat.RG16Sint ||
  48622. format === GPUTextureFormat.RG16Float ||
  48623. format === GPUTextureFormat.RGBA8Unorm ||
  48624. format === GPUTextureFormat.RGBA8UnormSRGB ||
  48625. format === GPUTextureFormat.RGBA8Snorm ||
  48626. format === GPUTextureFormat.RGBA8Uint ||
  48627. format === GPUTextureFormat.RGBA8Sint ||
  48628. format === GPUTextureFormat.BGRA8Unorm ||
  48629. format === GPUTextureFormat.BGRA8UnormSRGB ||
  48630. // Packed 32-bit formats
  48631. format === GPUTextureFormat.RGB9E5UFloat ||
  48632. format === GPUTextureFormat.RGB10A2Unorm ||
  48633. format === GPUTextureFormat.RG11B10UFloat ||
  48634. format === GPUTextureFormat.Depth32Float ||
  48635. format === GPUTextureFormat.Depth24Plus ||
  48636. format === GPUTextureFormat.Depth24PlusStencil8 ||
  48637. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  48638. // 64-bit formats
  48639. if ( format === GPUTextureFormat.RG32Uint ||
  48640. format === GPUTextureFormat.RG32Sint ||
  48641. format === GPUTextureFormat.RG32Float ||
  48642. format === GPUTextureFormat.RGBA16Uint ||
  48643. format === GPUTextureFormat.RGBA16Sint ||
  48644. format === GPUTextureFormat.RGBA16Float ) return 8;
  48645. // 128-bit formats
  48646. if ( format === GPUTextureFormat.RGBA32Uint ||
  48647. format === GPUTextureFormat.RGBA32Sint ||
  48648. format === GPUTextureFormat.RGBA32Float ) return 16;
  48649. }
  48650. /**
  48651. * Returns the corresponding typed array type for the given GPU texture format.
  48652. *
  48653. * @private
  48654. * @param {string} format - The GPU texture format.
  48655. * @return {TypedArray.constructor} The typed array type.
  48656. */
  48657. _getTypedArrayType( format ) {
  48658. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  48659. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  48660. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  48661. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  48662. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  48663. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  48664. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  48665. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  48666. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  48667. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  48668. if ( format === GPUTextureFormat.RGBA8Unorm || format === GPUTextureFormat.RGBA8UnormSRGB ) return Uint8Array;
  48669. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  48670. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  48671. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  48672. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  48673. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  48674. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  48675. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  48676. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  48677. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  48678. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  48679. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  48680. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  48681. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  48682. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  48683. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  48684. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  48685. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  48686. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  48687. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  48688. if ( format === GPUTextureFormat.BGRA8Unorm || format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  48689. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  48690. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  48691. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  48692. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  48693. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  48694. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  48695. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  48696. }
  48697. /**
  48698. * Returns the GPU dimensions for the given texture.
  48699. *
  48700. * @private
  48701. * @param {Texture} texture - The texture.
  48702. * @return {string} The GPU dimension.
  48703. */
  48704. _getDimension( texture ) {
  48705. let dimension;
  48706. if ( texture.is3DTexture || texture.isData3DTexture ) {
  48707. dimension = GPUTextureDimension.ThreeD;
  48708. } else {
  48709. dimension = GPUTextureDimension.TwoD;
  48710. }
  48711. return dimension;
  48712. }
  48713. }
  48714. /**
  48715. * Returns the GPU format for the given texture.
  48716. *
  48717. * @param {Texture} texture - The texture.
  48718. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  48719. * It is not necessary to apply the device for most formats.
  48720. * @return {string} The GPU format.
  48721. */
  48722. function getFormat( texture, device = null ) {
  48723. const format = texture.format;
  48724. const type = texture.type;
  48725. const colorSpace = texture.colorSpace;
  48726. const transfer = ColorManagement.getTransfer( colorSpace );
  48727. let formatGPU;
  48728. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  48729. switch ( format ) {
  48730. case RGB_S3TC_DXT1_Format:
  48731. case RGBA_S3TC_DXT1_Format:
  48732. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  48733. break;
  48734. case RGBA_S3TC_DXT3_Format:
  48735. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  48736. break;
  48737. case RGBA_S3TC_DXT5_Format:
  48738. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  48739. break;
  48740. case RED_RGTC1_Format:
  48741. formatGPU = GPUTextureFormat.BC4RUnorm;
  48742. break;
  48743. case SIGNED_RED_RGTC1_Format:
  48744. formatGPU = GPUTextureFormat.BC4RSnorm;
  48745. break;
  48746. case RED_GREEN_RGTC2_Format:
  48747. formatGPU = GPUTextureFormat.BC5RGUnorm;
  48748. break;
  48749. case SIGNED_RED_GREEN_RGTC2_Format:
  48750. formatGPU = GPUTextureFormat.BC5RGSnorm;
  48751. break;
  48752. case RGBA_BPTC_Format:
  48753. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC7RGBAUnormSRGB : GPUTextureFormat.BC7RGBAUnorm;
  48754. break;
  48755. case RGB_ETC2_Format:
  48756. case RGB_ETC1_Format:
  48757. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  48758. break;
  48759. case RGBA_ETC2_EAC_Format:
  48760. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  48761. break;
  48762. case RGBA_ASTC_4x4_Format:
  48763. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  48764. break;
  48765. case RGBA_ASTC_5x4_Format:
  48766. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  48767. break;
  48768. case RGBA_ASTC_5x5_Format:
  48769. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  48770. break;
  48771. case RGBA_ASTC_6x5_Format:
  48772. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  48773. break;
  48774. case RGBA_ASTC_6x6_Format:
  48775. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  48776. break;
  48777. case RGBA_ASTC_8x5_Format:
  48778. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  48779. break;
  48780. case RGBA_ASTC_8x6_Format:
  48781. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  48782. break;
  48783. case RGBA_ASTC_8x8_Format:
  48784. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  48785. break;
  48786. case RGBA_ASTC_10x5_Format:
  48787. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  48788. break;
  48789. case RGBA_ASTC_10x6_Format:
  48790. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  48791. break;
  48792. case RGBA_ASTC_10x8_Format:
  48793. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  48794. break;
  48795. case RGBA_ASTC_10x10_Format:
  48796. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  48797. break;
  48798. case RGBA_ASTC_12x10_Format:
  48799. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  48800. break;
  48801. case RGBA_ASTC_12x12_Format:
  48802. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  48803. break;
  48804. case RGBAFormat:
  48805. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  48806. break;
  48807. default:
  48808. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  48809. }
  48810. } else {
  48811. switch ( format ) {
  48812. case RGBAFormat:
  48813. switch ( type ) {
  48814. case ByteType:
  48815. formatGPU = GPUTextureFormat.RGBA8Snorm;
  48816. break;
  48817. case ShortType:
  48818. formatGPU = GPUTextureFormat.RGBA16Sint;
  48819. break;
  48820. case UnsignedShortType:
  48821. formatGPU = GPUTextureFormat.RGBA16Uint;
  48822. break;
  48823. case UnsignedIntType:
  48824. formatGPU = GPUTextureFormat.RGBA32Uint;
  48825. break;
  48826. case IntType:
  48827. formatGPU = GPUTextureFormat.RGBA32Sint;
  48828. break;
  48829. case UnsignedByteType:
  48830. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  48831. break;
  48832. case HalfFloatType:
  48833. formatGPU = GPUTextureFormat.RGBA16Float;
  48834. break;
  48835. case FloatType:
  48836. formatGPU = GPUTextureFormat.RGBA32Float;
  48837. break;
  48838. default:
  48839. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  48840. }
  48841. break;
  48842. case RGBFormat:
  48843. switch ( type ) {
  48844. case UnsignedInt5999Type:
  48845. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  48846. break;
  48847. case UnsignedInt101111Type:
  48848. formatGPU = GPUTextureFormat.RG11B10UFloat;
  48849. break;
  48850. default:
  48851. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  48852. }
  48853. break;
  48854. case RedFormat:
  48855. switch ( type ) {
  48856. case ByteType:
  48857. formatGPU = GPUTextureFormat.R8Snorm;
  48858. break;
  48859. case ShortType:
  48860. formatGPU = GPUTextureFormat.R16Sint;
  48861. break;
  48862. case UnsignedShortType:
  48863. formatGPU = GPUTextureFormat.R16Uint;
  48864. break;
  48865. case UnsignedIntType:
  48866. formatGPU = GPUTextureFormat.R32Uint;
  48867. break;
  48868. case IntType:
  48869. formatGPU = GPUTextureFormat.R32Sint;
  48870. break;
  48871. case UnsignedByteType:
  48872. formatGPU = GPUTextureFormat.R8Unorm;
  48873. break;
  48874. case HalfFloatType:
  48875. formatGPU = GPUTextureFormat.R16Float;
  48876. break;
  48877. case FloatType:
  48878. formatGPU = GPUTextureFormat.R32Float;
  48879. break;
  48880. default:
  48881. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  48882. }
  48883. break;
  48884. case RGFormat:
  48885. switch ( type ) {
  48886. case ByteType:
  48887. formatGPU = GPUTextureFormat.RG8Snorm;
  48888. break;
  48889. case ShortType:
  48890. formatGPU = GPUTextureFormat.RG16Sint;
  48891. break;
  48892. case UnsignedShortType:
  48893. formatGPU = GPUTextureFormat.RG16Uint;
  48894. break;
  48895. case UnsignedIntType:
  48896. formatGPU = GPUTextureFormat.RG32Uint;
  48897. break;
  48898. case IntType:
  48899. formatGPU = GPUTextureFormat.RG32Sint;
  48900. break;
  48901. case UnsignedByteType:
  48902. formatGPU = GPUTextureFormat.RG8Unorm;
  48903. break;
  48904. case HalfFloatType:
  48905. formatGPU = GPUTextureFormat.RG16Float;
  48906. break;
  48907. case FloatType:
  48908. formatGPU = GPUTextureFormat.RG32Float;
  48909. break;
  48910. default:
  48911. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  48912. }
  48913. break;
  48914. case DepthFormat:
  48915. switch ( type ) {
  48916. case UnsignedShortType:
  48917. formatGPU = GPUTextureFormat.Depth16Unorm;
  48918. break;
  48919. case UnsignedIntType:
  48920. formatGPU = GPUTextureFormat.Depth24Plus;
  48921. break;
  48922. case FloatType:
  48923. formatGPU = GPUTextureFormat.Depth32Float;
  48924. break;
  48925. default:
  48926. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  48927. }
  48928. break;
  48929. case DepthStencilFormat:
  48930. switch ( type ) {
  48931. case UnsignedInt248Type:
  48932. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  48933. break;
  48934. case FloatType:
  48935. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  48936. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  48937. }
  48938. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  48939. break;
  48940. default:
  48941. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  48942. }
  48943. break;
  48944. case RedIntegerFormat:
  48945. switch ( type ) {
  48946. case IntType:
  48947. formatGPU = GPUTextureFormat.R32Sint;
  48948. break;
  48949. case UnsignedIntType:
  48950. formatGPU = GPUTextureFormat.R32Uint;
  48951. break;
  48952. default:
  48953. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  48954. }
  48955. break;
  48956. case RGIntegerFormat:
  48957. switch ( type ) {
  48958. case IntType:
  48959. formatGPU = GPUTextureFormat.RG32Sint;
  48960. break;
  48961. case UnsignedIntType:
  48962. formatGPU = GPUTextureFormat.RG32Uint;
  48963. break;
  48964. default:
  48965. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  48966. }
  48967. break;
  48968. case RGBAIntegerFormat:
  48969. switch ( type ) {
  48970. case IntType:
  48971. formatGPU = GPUTextureFormat.RGBA32Sint;
  48972. break;
  48973. case UnsignedIntType:
  48974. formatGPU = GPUTextureFormat.RGBA32Uint;
  48975. break;
  48976. default:
  48977. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  48978. }
  48979. break;
  48980. default:
  48981. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  48982. }
  48983. }
  48984. return formatGPU;
  48985. }
  48986. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  48987. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  48988. const wgslTypeLib$1 = {
  48989. 'f32': 'float',
  48990. 'i32': 'int',
  48991. 'u32': 'uint',
  48992. 'bool': 'bool',
  48993. 'vec2<f32>': 'vec2',
  48994. 'vec2<i32>': 'ivec2',
  48995. 'vec2<u32>': 'uvec2',
  48996. 'vec2<bool>': 'bvec2',
  48997. 'vec2f': 'vec2',
  48998. 'vec2i': 'ivec2',
  48999. 'vec2u': 'uvec2',
  49000. 'vec2b': 'bvec2',
  49001. 'vec3<f32>': 'vec3',
  49002. 'vec3<i32>': 'ivec3',
  49003. 'vec3<u32>': 'uvec3',
  49004. 'vec3<bool>': 'bvec3',
  49005. 'vec3f': 'vec3',
  49006. 'vec3i': 'ivec3',
  49007. 'vec3u': 'uvec3',
  49008. 'vec3b': 'bvec3',
  49009. 'vec4<f32>': 'vec4',
  49010. 'vec4<i32>': 'ivec4',
  49011. 'vec4<u32>': 'uvec4',
  49012. 'vec4<bool>': 'bvec4',
  49013. 'vec4f': 'vec4',
  49014. 'vec4i': 'ivec4',
  49015. 'vec4u': 'uvec4',
  49016. 'vec4b': 'bvec4',
  49017. 'mat2x2<f32>': 'mat2',
  49018. 'mat2x2f': 'mat2',
  49019. 'mat3x3<f32>': 'mat3',
  49020. 'mat3x3f': 'mat3',
  49021. 'mat4x4<f32>': 'mat4',
  49022. 'mat4x4f': 'mat4',
  49023. 'sampler': 'sampler',
  49024. 'texture_1d': 'texture',
  49025. 'texture_2d': 'texture',
  49026. 'texture_2d_array': 'texture',
  49027. 'texture_multisampled_2d': 'cubeTexture',
  49028. 'texture_depth_2d': 'depthTexture',
  49029. 'texture_depth_2d_array': 'depthTexture',
  49030. 'texture_depth_multisampled_2d': 'depthTexture',
  49031. 'texture_depth_cube': 'depthTexture',
  49032. 'texture_depth_cube_array': 'depthTexture',
  49033. 'texture_3d': 'texture3D',
  49034. 'texture_cube': 'cubeTexture',
  49035. 'texture_cube_array': 'cubeTexture',
  49036. 'texture_storage_1d': 'storageTexture',
  49037. 'texture_storage_2d': 'storageTexture',
  49038. 'texture_storage_2d_array': 'storageTexture',
  49039. 'texture_storage_3d': 'storageTexture'
  49040. };
  49041. const parse = ( source ) => {
  49042. source = source.trim();
  49043. const declaration = source.match( declarationRegexp );
  49044. if ( declaration !== null && declaration.length === 4 ) {
  49045. const inputsCode = declaration[ 2 ];
  49046. const propsMatches = [];
  49047. let match = null;
  49048. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  49049. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  49050. }
  49051. // Process matches to correctly pair names and types
  49052. const inputs = [];
  49053. for ( let i = 0; i < propsMatches.length; i ++ ) {
  49054. const { name, type } = propsMatches[ i ];
  49055. let resolvedType = type;
  49056. if ( resolvedType.startsWith( 'ptr' ) ) {
  49057. resolvedType = 'pointer';
  49058. } else {
  49059. if ( resolvedType.startsWith( 'texture' ) ) {
  49060. resolvedType = type.split( '<' )[ 0 ];
  49061. }
  49062. resolvedType = wgslTypeLib$1[ resolvedType ];
  49063. }
  49064. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  49065. }
  49066. const blockCode = source.substring( declaration[ 0 ].length );
  49067. const outputType = declaration[ 3 ] || 'void';
  49068. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  49069. const type = wgslTypeLib$1[ outputType ] || outputType;
  49070. return {
  49071. type,
  49072. inputs,
  49073. name,
  49074. inputsCode,
  49075. blockCode,
  49076. outputType
  49077. };
  49078. } else {
  49079. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  49080. }
  49081. };
  49082. /**
  49083. * This class represents a WSL node function.
  49084. *
  49085. * @augments NodeFunction
  49086. */
  49087. class WGSLNodeFunction extends NodeFunction {
  49088. /**
  49089. * Constructs a new WGSL node function.
  49090. *
  49091. * @param {string} source - The WGSL source.
  49092. */
  49093. constructor( source ) {
  49094. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  49095. super( type, inputs, name );
  49096. this.inputsCode = inputsCode;
  49097. this.blockCode = blockCode;
  49098. this.outputType = outputType;
  49099. }
  49100. /**
  49101. * This method returns the WGSL code of the node function.
  49102. *
  49103. * @param {string} [name=this.name] - The function's name.
  49104. * @return {string} The shader code.
  49105. */
  49106. getCode( name = this.name ) {
  49107. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  49108. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  49109. }
  49110. }
  49111. /**
  49112. * A WGSL node parser.
  49113. *
  49114. * @augments NodeParser
  49115. */
  49116. class WGSLNodeParser extends NodeParser {
  49117. /**
  49118. * The method parses the given WGSL code an returns a node function.
  49119. *
  49120. * @param {string} source - The WGSL code.
  49121. * @return {WGSLNodeFunction} A node function.
  49122. */
  49123. parseFunction( source ) {
  49124. return new WGSLNodeFunction( source );
  49125. }
  49126. }
  49127. // GPUShaderStage is not defined in browsers not supporting WebGPU
  49128. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  49129. const accessNames = {
  49130. [ NodeAccess.READ_ONLY ]: 'read',
  49131. [ NodeAccess.WRITE_ONLY ]: 'write',
  49132. [ NodeAccess.READ_WRITE ]: 'read_write'
  49133. };
  49134. const wrapNames = {
  49135. [ RepeatWrapping ]: 'repeat',
  49136. [ ClampToEdgeWrapping ]: 'clamp',
  49137. [ MirroredRepeatWrapping ]: 'mirror'
  49138. };
  49139. const gpuShaderStageLib = {
  49140. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  49141. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  49142. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  49143. };
  49144. const supports = {
  49145. instance: true,
  49146. swizzleAssign: false,
  49147. storageBuffer: true
  49148. };
  49149. const wgslFnOpLib = {
  49150. '^^': 'tsl_xor'
  49151. };
  49152. const wgslTypeLib = {
  49153. float: 'f32',
  49154. int: 'i32',
  49155. uint: 'u32',
  49156. bool: 'bool',
  49157. color: 'vec3<f32>',
  49158. vec2: 'vec2<f32>',
  49159. ivec2: 'vec2<i32>',
  49160. uvec2: 'vec2<u32>',
  49161. bvec2: 'vec2<bool>',
  49162. vec3: 'vec3<f32>',
  49163. ivec3: 'vec3<i32>',
  49164. uvec3: 'vec3<u32>',
  49165. bvec3: 'vec3<bool>',
  49166. vec4: 'vec4<f32>',
  49167. ivec4: 'vec4<i32>',
  49168. uvec4: 'vec4<u32>',
  49169. bvec4: 'vec4<bool>',
  49170. mat2: 'mat2x2<f32>',
  49171. mat3: 'mat3x3<f32>',
  49172. mat4: 'mat4x4<f32>'
  49173. };
  49174. const wgslCodeCache = {};
  49175. const wgslPolyfill = {
  49176. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  49177. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  49178. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  49179. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  49180. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  49181. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  49182. 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 ); }' ),
  49183. 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 ); }' ),
  49184. 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 ); }' ),
  49185. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  49186. 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 ); }' ),
  49187. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  49188. biquadraticTexture: new CodeNode( /* wgsl */`
  49189. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  49190. let res = vec2f( iRes );
  49191. let uvScaled = coord * res;
  49192. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  49193. // https://www.shadertoy.com/view/WtyXRy
  49194. let uv = uvWrapping - 0.5;
  49195. let iuv = floor( uv );
  49196. let f = fract( uv );
  49197. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  49198. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  49199. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  49200. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  49201. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  49202. }
  49203. ` )
  49204. };
  49205. const wgslMethods = {
  49206. dFdx: 'dpdx',
  49207. dFdy: '- dpdy',
  49208. mod_float: 'tsl_mod_float',
  49209. mod_vec2: 'tsl_mod_vec2',
  49210. mod_vec3: 'tsl_mod_vec3',
  49211. mod_vec4: 'tsl_mod_vec4',
  49212. equals_bool: 'tsl_equals_bool',
  49213. equals_bvec2: 'tsl_equals_bvec2',
  49214. equals_bvec3: 'tsl_equals_bvec3',
  49215. equals_bvec4: 'tsl_equals_bvec4',
  49216. inversesqrt: 'inverseSqrt',
  49217. bitcast: 'bitcast<f32>'
  49218. };
  49219. //
  49220. let diagnostics = '';
  49221. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  49222. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  49223. }
  49224. /**
  49225. * A node builder targeting WGSL.
  49226. *
  49227. * This module generates WGSL shader code from node materials and also
  49228. * generates the respective bindings and vertex buffer definitions. These
  49229. * data are later used by the renderer to create render and compute pipelines
  49230. * for render objects.
  49231. *
  49232. * @augments NodeBuilder
  49233. */
  49234. class WGSLNodeBuilder extends NodeBuilder {
  49235. /**
  49236. * Constructs a new WGSL node builder renderer.
  49237. *
  49238. * @param {Object3D} object - The 3D object.
  49239. * @param {Renderer} renderer - The renderer.
  49240. */
  49241. constructor( object, renderer ) {
  49242. super( object, renderer, new WGSLNodeParser() );
  49243. /**
  49244. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  49245. * another dictionary which manages UBOs per group ('render','frame','object').
  49246. *
  49247. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  49248. */
  49249. this.uniformGroups = {};
  49250. /**
  49251. * A dictionary that holds for each shader stage a Map of builtins.
  49252. *
  49253. * @type {Object<string,Map<string,Object>>}
  49254. */
  49255. this.builtins = {};
  49256. /**
  49257. * A dictionary that holds for each shader stage a Set of directives.
  49258. *
  49259. * @type {Object<string,Set<string>>}
  49260. */
  49261. this.directives = {};
  49262. /**
  49263. * A map for managing scope arrays. Only relevant for when using
  49264. * {@link WorkgroupInfoNode} in context of compute shaders.
  49265. *
  49266. * @type {Map<string,Object>}
  49267. */
  49268. this.scopedArrays = new Map();
  49269. }
  49270. /**
  49271. * Generates the WGSL snippet for sampled textures.
  49272. *
  49273. * @private
  49274. * @param {Texture} texture - The texture.
  49275. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49276. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49277. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49278. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49279. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49280. * @return {string} The WGSL snippet.
  49281. */
  49282. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  49283. if ( shaderStage === 'fragment' ) {
  49284. if ( depthSnippet ) {
  49285. if ( offsetSnippet ) {
  49286. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ offsetSnippet } )`;
  49287. }
  49288. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  49289. } else {
  49290. if ( offsetSnippet ) {
  49291. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ offsetSnippet } )`;
  49292. }
  49293. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  49294. }
  49295. } else {
  49296. return this.generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  49297. }
  49298. }
  49299. /**
  49300. * Generates the WGSL snippet when sampling textures with explicit mip level.
  49301. *
  49302. * @private
  49303. * @param {Texture} texture - The texture.
  49304. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49305. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49306. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49307. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49308. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49309. * @return {string} The WGSL snippet.
  49310. */
  49311. generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  49312. if ( this.isUnfilterable( texture ) === false ) {
  49313. if ( offsetSnippet ) {
  49314. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  49315. }
  49316. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  49317. } else if ( this.isFilteredTexture( texture ) ) {
  49318. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  49319. } else {
  49320. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  49321. }
  49322. }
  49323. /**
  49324. * Generates a wrap function used in context of textures.
  49325. *
  49326. * @param {Texture} texture - The texture to generate the function for.
  49327. * @return {string} The name of the generated function.
  49328. */
  49329. generateWrapFunction( texture ) {
  49330. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  49331. let nodeCode = wgslCodeCache[ functionName ];
  49332. if ( nodeCode === undefined ) {
  49333. const includes = [];
  49334. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  49335. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  49336. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  49337. const addWrapSnippet = ( wrap, axis ) => {
  49338. if ( wrap === RepeatWrapping ) {
  49339. includes.push( wgslPolyfill.repeatWrapping_float );
  49340. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  49341. } else if ( wrap === ClampToEdgeWrapping ) {
  49342. includes.push( wgslPolyfill.clampWrapping_float );
  49343. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  49344. } else if ( wrap === MirroredRepeatWrapping ) {
  49345. includes.push( wgslPolyfill.mirrorWrapping_float );
  49346. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  49347. } else {
  49348. code += `\t\tcoord.${ axis }`;
  49349. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  49350. }
  49351. };
  49352. addWrapSnippet( texture.wrapS, 'x' );
  49353. code += ',\n';
  49354. addWrapSnippet( texture.wrapT, 'y' );
  49355. if ( texture.isData3DTexture ) {
  49356. code += ',\n';
  49357. addWrapSnippet( texture.wrapR, 'z' );
  49358. }
  49359. code += '\n\t);\n\n}\n';
  49360. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  49361. }
  49362. nodeCode.build( this );
  49363. return functionName;
  49364. }
  49365. /**
  49366. * Generates the array declaration string.
  49367. *
  49368. * @param {string} type - The type.
  49369. * @param {?number} [count] - The count.
  49370. * @return {string} The generated value as a shader string.
  49371. */
  49372. generateArrayDeclaration( type, count ) {
  49373. return `array< ${ this.getType( type ) }, ${ count } >`;
  49374. }
  49375. /**
  49376. * Generates a WGSL variable that holds the texture dimension of the given texture.
  49377. * It also returns information about the number of layers (elements) of an arrayed
  49378. * texture as well as the cube face count of cube textures.
  49379. *
  49380. * @param {Texture} texture - The texture to generate the function for.
  49381. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  49382. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49383. * @return {string} The name of the dimension variable.
  49384. */
  49385. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  49386. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  49387. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  49388. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  49389. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  49390. let textureDimensionsParams;
  49391. let dimensionType;
  49392. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  49393. const isMultisampled = primarySamples > 1;
  49394. if ( texture.isData3DTexture ) {
  49395. dimensionType = 'vec3<u32>';
  49396. } else {
  49397. // Regular 2D textures, depth textures, etc.
  49398. dimensionType = 'vec2<u32>';
  49399. }
  49400. // Build parameters string based on texture type and multisampling
  49401. if ( isMultisampled || texture.isStorageTexture ) {
  49402. textureDimensionsParams = textureProperty;
  49403. } else {
  49404. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  49405. }
  49406. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  49407. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  49408. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  49409. textureData.arrayLayerCount = new VarNode(
  49410. new ExpressionNode(
  49411. `textureNumLayers(${textureProperty})`,
  49412. 'u32'
  49413. )
  49414. );
  49415. }
  49416. // For cube textures, we know it's always 6 faces
  49417. if ( texture.isTextureCube ) {
  49418. textureData.cubeFaceCount = new VarNode(
  49419. new ExpressionNode( '6u', 'u32' )
  49420. );
  49421. }
  49422. }
  49423. return textureDimensionNode.build( this );
  49424. }
  49425. /**
  49426. * Generates the WGSL snippet for a manual filtered texture.
  49427. *
  49428. * @param {Texture} texture - The texture.
  49429. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49430. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49431. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49432. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49433. * @return {string} The WGSL snippet.
  49434. */
  49435. generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet = '0u' ) {
  49436. this._include( 'biquadraticTexture' );
  49437. const wrapFunction = this.generateWrapFunction( texture );
  49438. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  49439. if ( offsetSnippet ) {
  49440. uvSnippet = `${ uvSnippet } + vec2<f32>(${ offsetSnippet }) / ${ textureDimension }`;
  49441. }
  49442. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  49443. }
  49444. /**
  49445. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  49446. * Since it's a lookup, no sampling or filtering is applied.
  49447. *
  49448. * @param {Texture} texture - The texture.
  49449. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49450. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49451. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49452. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49453. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49454. * @return {string} The WGSL snippet.
  49455. */
  49456. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  49457. const wrapFunction = this.generateWrapFunction( texture );
  49458. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  49459. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  49460. if ( offsetSnippet ) {
  49461. uvSnippet = `${ uvSnippet } + ${ vecType }<f32>(${ offsetSnippet }) / ${ vecType }<f32>( ${ textureDimension } )`;
  49462. }
  49463. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  49464. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, null, levelSnippet );
  49465. }
  49466. /**
  49467. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  49468. *
  49469. * @param {Texture} texture - The texture.
  49470. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49471. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49472. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49473. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49474. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49475. * @return {string} The WGSL snippet.
  49476. */
  49477. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, offsetSnippet, levelSnippet = '0u' ) {
  49478. let snippet;
  49479. if ( offsetSnippet ) {
  49480. uvIndexSnippet = `${ uvIndexSnippet } + ${ offsetSnippet }`;
  49481. }
  49482. if ( depthSnippet ) {
  49483. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  49484. } else {
  49485. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  49486. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  49487. snippet += '.x';
  49488. }
  49489. }
  49490. return snippet;
  49491. }
  49492. /**
  49493. * Generates the WGSL snippet that writes a single texel to a texture.
  49494. *
  49495. * @param {Texture} texture - The texture.
  49496. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49497. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49498. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49499. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  49500. * @return {string} The WGSL snippet.
  49501. */
  49502. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  49503. let snippet;
  49504. if ( depthSnippet ) {
  49505. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  49506. } else {
  49507. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  49508. }
  49509. return snippet;
  49510. }
  49511. /**
  49512. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  49513. *
  49514. * @param {Texture} texture - The texture.
  49515. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  49516. */
  49517. isSampleCompare( texture ) {
  49518. return texture.isDepthTexture === true && texture.compareFunction !== null;
  49519. }
  49520. /**
  49521. * Returns `true` if the given texture is unfilterable.
  49522. *
  49523. * @param {Texture} texture - The texture.
  49524. * @return {boolean} Whether the given texture is unfilterable or not.
  49525. */
  49526. isUnfilterable( texture ) {
  49527. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  49528. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  49529. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  49530. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  49531. }
  49532. /**
  49533. * Generates the WGSL snippet for sampling/loading the given texture.
  49534. *
  49535. * @param {Texture} texture - The texture.
  49536. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49537. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49538. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49539. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49540. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49541. * @return {string} The WGSL snippet.
  49542. */
  49543. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  49544. let snippet = null;
  49545. if ( this.isUnfilterable( texture ) ) {
  49546. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, '0', shaderStage );
  49547. } else {
  49548. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, shaderStage );
  49549. }
  49550. return snippet;
  49551. }
  49552. /**
  49553. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  49554. *
  49555. * @param {Texture} texture - The texture.
  49556. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49557. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49558. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  49559. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49560. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49561. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49562. * @return {string} The WGSL snippet.
  49563. */
  49564. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  49565. if ( shaderStage === 'fragment' ) {
  49566. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  49567. if ( offsetSnippet ) {
  49568. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] }, ${ offsetSnippet } )`;
  49569. }
  49570. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  49571. } else {
  49572. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  49573. }
  49574. }
  49575. /**
  49576. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  49577. * against a reference value.
  49578. *
  49579. * @param {Texture} texture - The texture.
  49580. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49581. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49582. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  49583. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49584. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49585. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49586. * @return {string} The WGSL snippet.
  49587. */
  49588. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  49589. if ( shaderStage === 'fragment' ) {
  49590. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  49591. if ( offsetSnippet ) {
  49592. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  49593. }
  49594. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  49595. }
  49596. if ( offsetSnippet ) {
  49597. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet }, ${ offsetSnippet } )`;
  49598. }
  49599. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  49600. } else {
  49601. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  49602. }
  49603. }
  49604. /**
  49605. * Generates the WGSL snippet when sampling textures with explicit mip level.
  49606. *
  49607. * @param {Texture} texture - The texture.
  49608. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49609. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49610. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  49611. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49612. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49613. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49614. * @return {string} The WGSL snippet.
  49615. */
  49616. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, offsetSnippet ) {
  49617. if ( this.isUnfilterable( texture ) === false ) {
  49618. if ( offsetSnippet ) {
  49619. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet }, ${ offsetSnippet } )`;
  49620. }
  49621. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  49622. } else if ( this.isFilteredTexture( texture ) ) {
  49623. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, offsetSnippet, levelSnippet );
  49624. } else {
  49625. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, offsetSnippet, levelSnippet );
  49626. }
  49627. }
  49628. /**
  49629. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  49630. *
  49631. * @param {Texture} texture - The texture.
  49632. * @param {string} textureProperty - The name of the texture uniform in the shader.
  49633. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  49634. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  49635. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  49636. * @param {?string} offsetSnippet - A WGSL snippet that represents the offset that will be applied to the unnormalized texture coordinate before sampling the texture.
  49637. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49638. * @return {string} The WGSL snippet.
  49639. */
  49640. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, offsetSnippet, shaderStage = this.shaderStage ) {
  49641. if ( shaderStage === 'fragment' ) {
  49642. if ( offsetSnippet ) {
  49643. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet }, ${ offsetSnippet } )`;
  49644. }
  49645. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  49646. } else {
  49647. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  49648. }
  49649. }
  49650. /**
  49651. * Returns a WGSL snippet that represents the property name of the given node.
  49652. *
  49653. * @param {Node} node - The node.
  49654. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49655. * @return {string} The property name.
  49656. */
  49657. getPropertyName( node, shaderStage = this.shaderStage ) {
  49658. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  49659. if ( shaderStage === 'vertex' ) {
  49660. return `varyings.${ node.name }`;
  49661. }
  49662. } else if ( node.isNodeUniform === true ) {
  49663. const name = node.name;
  49664. const type = node.type;
  49665. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  49666. return name;
  49667. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  49668. if ( this.isCustomStruct( node ) ) {
  49669. return name;
  49670. }
  49671. return name + '.value';
  49672. } else {
  49673. return node.groupNode.name + '.' + name;
  49674. }
  49675. }
  49676. return super.getPropertyName( node );
  49677. }
  49678. /**
  49679. * Returns the output struct name.
  49680. *
  49681. * @return {string} The name of the output struct.
  49682. */
  49683. getOutputStructName() {
  49684. return 'output';
  49685. }
  49686. /**
  49687. * Returns the native shader operator name for a given generic name.
  49688. *
  49689. * @param {string} op - The operator name to resolve.
  49690. * @return {?string} The resolved operator name.
  49691. */
  49692. getFunctionOperator( op ) {
  49693. const fnOp = wgslFnOpLib[ op ];
  49694. if ( fnOp !== undefined ) {
  49695. this._include( fnOp );
  49696. return fnOp;
  49697. }
  49698. return null;
  49699. }
  49700. /**
  49701. * Returns the node access for the given node and shader stage.
  49702. *
  49703. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  49704. * @param {string} shaderStage - The shader stage.
  49705. * @return {string} The node access.
  49706. */
  49707. getNodeAccess( node, shaderStage ) {
  49708. if ( shaderStage !== 'compute' ) {
  49709. if ( node.isAtomic === true ) {
  49710. console.warn( 'WebGPURenderer: Atomic operations are only supported in compute shaders.' );
  49711. return NodeAccess.READ_WRITE;
  49712. }
  49713. return NodeAccess.READ_ONLY;
  49714. }
  49715. return node.access;
  49716. }
  49717. /**
  49718. * Returns A WGSL snippet representing the storage access.
  49719. *
  49720. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  49721. * @param {string} shaderStage - The shader stage.
  49722. * @return {string} The WGSL snippet representing the storage access.
  49723. */
  49724. getStorageAccess( node, shaderStage ) {
  49725. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  49726. }
  49727. /**
  49728. * This method is one of the more important ones since it's responsible
  49729. * for generating a matching binding instance for the given uniform node.
  49730. *
  49731. * These bindings are later used in the renderer to create bind groups
  49732. * and layouts.
  49733. *
  49734. * @param {UniformNode} node - The uniform node.
  49735. * @param {string} type - The node data type.
  49736. * @param {string} shaderStage - The shader stage.
  49737. * @param {?string} [name=null] - An optional uniform name.
  49738. * @return {NodeUniform} The node uniform object.
  49739. */
  49740. getUniformFromNode( node, type, shaderStage, name = null ) {
  49741. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  49742. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  49743. if ( nodeData.uniformGPU === undefined ) {
  49744. let uniformGPU;
  49745. const group = node.groupNode;
  49746. const groupName = group.name;
  49747. const bindings = this.getBindGroupArray( groupName, shaderStage );
  49748. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  49749. let texture = null;
  49750. const access = this.getNodeAccess( node, shaderStage );
  49751. if ( type === 'texture' || type === 'storageTexture' ) {
  49752. if ( node.value.is3DTexture === true ) {
  49753. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  49754. } else {
  49755. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  49756. }
  49757. } else if ( type === 'cubeTexture' ) {
  49758. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  49759. } else if ( type === 'texture3D' ) {
  49760. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  49761. }
  49762. texture.store = node.isStorageTextureNode === true;
  49763. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  49764. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  49765. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  49766. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  49767. bindings.push( sampler, texture );
  49768. uniformGPU = [ sampler, texture ];
  49769. } else {
  49770. bindings.push( texture );
  49771. uniformGPU = [ texture ];
  49772. }
  49773. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  49774. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  49775. const buffer = new bufferClass( node, group );
  49776. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  49777. bindings.push( buffer );
  49778. uniformGPU = buffer;
  49779. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  49780. } else {
  49781. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  49782. let uniformsGroup = uniformsStage[ groupName ];
  49783. if ( uniformsGroup === undefined ) {
  49784. uniformsGroup = new NodeUniformsGroup( groupName, group );
  49785. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  49786. uniformsStage[ groupName ] = uniformsGroup;
  49787. bindings.push( uniformsGroup );
  49788. }
  49789. uniformGPU = this.getNodeUniform( uniformNode, type );
  49790. uniformsGroup.addUniform( uniformGPU );
  49791. }
  49792. nodeData.uniformGPU = uniformGPU;
  49793. }
  49794. return uniformNode;
  49795. }
  49796. /**
  49797. * This method should be used whenever builtins are required in nodes.
  49798. * The internal builtins data structure will make sure builtins are
  49799. * defined in the WGSL source.
  49800. *
  49801. * @param {string} name - The builtin name.
  49802. * @param {string} property - The property name.
  49803. * @param {string} type - The node data type.
  49804. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49805. * @return {string} The property name.
  49806. */
  49807. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  49808. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  49809. if ( map.has( name ) === false ) {
  49810. map.set( name, {
  49811. name,
  49812. property,
  49813. type
  49814. } );
  49815. }
  49816. return property;
  49817. }
  49818. /**
  49819. * Returns `true` if the given builtin is defined in the given shader stage.
  49820. *
  49821. * @param {string} name - The builtin name.
  49822. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  49823. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  49824. */
  49825. hasBuiltin( name, shaderStage = this.shaderStage ) {
  49826. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  49827. }
  49828. /**
  49829. * Returns the vertex index builtin.
  49830. *
  49831. * @return {string} The vertex index.
  49832. */
  49833. getVertexIndex() {
  49834. if ( this.shaderStage === 'vertex' ) {
  49835. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  49836. }
  49837. return 'vertexIndex';
  49838. }
  49839. /**
  49840. * Builds the given shader node.
  49841. *
  49842. * @param {ShaderNodeInternal} shaderNode - The shader node.
  49843. * @return {string} The WGSL function code.
  49844. */
  49845. buildFunctionCode( shaderNode ) {
  49846. const layout = shaderNode.layout;
  49847. const flowData = this.flowShaderNode( shaderNode );
  49848. const parameters = [];
  49849. for ( const input of layout.inputs ) {
  49850. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  49851. }
  49852. //
  49853. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  49854. ${ flowData.vars }
  49855. ${ flowData.code }
  49856. `;
  49857. if ( flowData.result ) {
  49858. code += `\treturn ${ flowData.result };\n`;
  49859. }
  49860. code += '\n}\n';
  49861. //
  49862. return code;
  49863. }
  49864. /**
  49865. * Returns the instance index builtin.
  49866. *
  49867. * @return {string} The instance index.
  49868. */
  49869. getInstanceIndex() {
  49870. if ( this.shaderStage === 'vertex' ) {
  49871. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  49872. }
  49873. return 'instanceIndex';
  49874. }
  49875. /**
  49876. * Returns the invocation local index builtin.
  49877. *
  49878. * @return {string} The invocation local index.
  49879. */
  49880. getInvocationLocalIndex() {
  49881. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  49882. }
  49883. /**
  49884. * Returns the subgroup size builtin.
  49885. *
  49886. * @return {string} The subgroup size.
  49887. */
  49888. getSubgroupSize() {
  49889. this.enableSubGroups();
  49890. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  49891. }
  49892. /**
  49893. * Returns the invocation subgroup index builtin.
  49894. *
  49895. * @return {string} The invocation subgroup index.
  49896. */
  49897. getInvocationSubgroupIndex() {
  49898. this.enableSubGroups();
  49899. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  49900. }
  49901. /**
  49902. * Returns the subgroup index builtin.
  49903. *
  49904. * @return {string} The subgroup index.
  49905. */
  49906. getSubgroupIndex() {
  49907. this.enableSubGroups();
  49908. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  49909. }
  49910. /**
  49911. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  49912. *
  49913. * @return {null} Null.
  49914. */
  49915. getDrawIndex() {
  49916. return null;
  49917. }
  49918. /**
  49919. * Returns the front facing builtin.
  49920. *
  49921. * @return {string} The front facing builtin.
  49922. */
  49923. getFrontFacing() {
  49924. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  49925. }
  49926. /**
  49927. * Returns the frag coord builtin.
  49928. *
  49929. * @return {string} The frag coord builtin.
  49930. */
  49931. getFragCoord() {
  49932. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  49933. }
  49934. /**
  49935. * Returns the frag depth builtin.
  49936. *
  49937. * @return {string} The frag depth builtin.
  49938. */
  49939. getFragDepth() {
  49940. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  49941. }
  49942. /**
  49943. * Returns the clip distances builtin.
  49944. *
  49945. * @return {string} The clip distances builtin.
  49946. */
  49947. getClipDistance() {
  49948. return 'varyings.hw_clip_distances';
  49949. }
  49950. /**
  49951. * Whether to flip texture data along its vertical axis or not.
  49952. *
  49953. * @return {boolean} Returns always `false` in context of WGSL.
  49954. */
  49955. isFlipY() {
  49956. return false;
  49957. }
  49958. /**
  49959. * Enables the given directive for the given shader stage.
  49960. *
  49961. * @param {string} name - The directive name.
  49962. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  49963. */
  49964. enableDirective( name, shaderStage = this.shaderStage ) {
  49965. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  49966. stage.add( name );
  49967. }
  49968. /**
  49969. * Returns the directives of the given shader stage as a WGSL string.
  49970. *
  49971. * @param {string} shaderStage - The shader stage.
  49972. * @return {string} A WGSL snippet that enables the directives of the given stage.
  49973. */
  49974. getDirectives( shaderStage ) {
  49975. const snippets = [];
  49976. const directives = this.directives[ shaderStage ];
  49977. if ( directives !== undefined ) {
  49978. for ( const directive of directives ) {
  49979. snippets.push( `enable ${directive};` );
  49980. }
  49981. }
  49982. return snippets.join( '\n' );
  49983. }
  49984. /**
  49985. * Enables the 'subgroups' directive.
  49986. */
  49987. enableSubGroups() {
  49988. this.enableDirective( 'subgroups' );
  49989. }
  49990. /**
  49991. * Enables the 'subgroups-f16' directive.
  49992. */
  49993. enableSubgroupsF16() {
  49994. this.enableDirective( 'subgroups-f16' );
  49995. }
  49996. /**
  49997. * Enables the 'clip_distances' directive.
  49998. */
  49999. enableClipDistances() {
  50000. this.enableDirective( 'clip_distances' );
  50001. }
  50002. /**
  50003. * Enables the 'f16' directive.
  50004. */
  50005. enableShaderF16() {
  50006. this.enableDirective( 'f16' );
  50007. }
  50008. /**
  50009. * Enables the 'dual_source_blending' directive.
  50010. */
  50011. enableDualSourceBlending() {
  50012. this.enableDirective( 'dual_source_blending' );
  50013. }
  50014. /**
  50015. * Enables hardware clipping.
  50016. *
  50017. * @param {string} planeCount - The clipping plane count.
  50018. */
  50019. enableHardwareClipping( planeCount ) {
  50020. this.enableClipDistances();
  50021. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  50022. }
  50023. /**
  50024. * Returns the builtins of the given shader stage as a WGSL string.
  50025. *
  50026. * @param {string} shaderStage - The shader stage.
  50027. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  50028. */
  50029. getBuiltins( shaderStage ) {
  50030. const snippets = [];
  50031. const builtins = this.builtins[ shaderStage ];
  50032. if ( builtins !== undefined ) {
  50033. for ( const { name, property, type } of builtins.values() ) {
  50034. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  50035. }
  50036. }
  50037. return snippets.join( ',\n\t' );
  50038. }
  50039. /**
  50040. * This method should be used when a new scoped buffer is used in context of
  50041. * compute shaders. It adds the array to the internal data structure which is
  50042. * later used to generate the respective WGSL.
  50043. *
  50044. * @param {string} name - The array name.
  50045. * @param {string} scope - The scope.
  50046. * @param {string} bufferType - The buffer type.
  50047. * @param {string} bufferCount - The buffer count.
  50048. * @return {string} The array name.
  50049. */
  50050. getScopedArray( name, scope, bufferType, bufferCount ) {
  50051. if ( this.scopedArrays.has( name ) === false ) {
  50052. this.scopedArrays.set( name, {
  50053. name,
  50054. scope,
  50055. bufferType,
  50056. bufferCount
  50057. } );
  50058. }
  50059. return name;
  50060. }
  50061. /**
  50062. * Returns the scoped arrays of the given shader stage as a WGSL string.
  50063. *
  50064. * @param {string} shaderStage - The shader stage.
  50065. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  50066. * Returns `undefined` when used in the vertex or fragment stage.
  50067. */
  50068. getScopedArrays( shaderStage ) {
  50069. if ( shaderStage !== 'compute' ) {
  50070. return;
  50071. }
  50072. const snippets = [];
  50073. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  50074. const type = this.getType( bufferType );
  50075. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  50076. }
  50077. return snippets.join( '\n' );
  50078. }
  50079. /**
  50080. * Returns the shader attributes of the given shader stage as a WGSL string.
  50081. *
  50082. * @param {string} shaderStage - The shader stage.
  50083. * @return {string} The WGSL snippet that defines the shader attributes.
  50084. */
  50085. getAttributes( shaderStage ) {
  50086. const snippets = [];
  50087. if ( shaderStage === 'compute' ) {
  50088. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  50089. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  50090. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  50091. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  50092. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  50093. this.enableDirective( 'subgroups', shaderStage );
  50094. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  50095. }
  50096. }
  50097. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  50098. const builtins = this.getBuiltins( 'attribute' );
  50099. if ( builtins ) snippets.push( builtins );
  50100. const attributes = this.getAttributesArray();
  50101. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  50102. const attribute = attributes[ index ];
  50103. const name = attribute.name;
  50104. const type = this.getType( attribute.type );
  50105. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  50106. }
  50107. }
  50108. return snippets.join( ',\n\t' );
  50109. }
  50110. /**
  50111. * Returns the members of the given struct type node as a WGSL string.
  50112. *
  50113. * @param {StructTypeNode} struct - The struct type node.
  50114. * @return {string} The WGSL snippet that defines the struct members.
  50115. */
  50116. getStructMembers( struct ) {
  50117. const snippets = [];
  50118. for ( const member of struct.members ) {
  50119. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  50120. let type = this.getType( member.type );
  50121. if ( member.atomic ) {
  50122. type = 'atomic< ' + type + ' >';
  50123. }
  50124. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  50125. }
  50126. if ( struct.output ) {
  50127. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  50128. }
  50129. return snippets.join( ',\n' );
  50130. }
  50131. /**
  50132. * Returns the structs of the given shader stage as a WGSL string.
  50133. *
  50134. * @param {string} shaderStage - The shader stage.
  50135. * @return {string} The WGSL snippet that defines the structs.
  50136. */
  50137. getStructs( shaderStage ) {
  50138. let result = '';
  50139. const structs = this.structs[ shaderStage ];
  50140. if ( structs.length > 0 ) {
  50141. const snippets = [];
  50142. for ( const struct of structs ) {
  50143. let snippet = `struct ${ struct.name } {\n`;
  50144. snippet += this.getStructMembers( struct );
  50145. snippet += '\n};';
  50146. snippets.push( snippet );
  50147. }
  50148. result = '\n' + snippets.join( '\n\n' ) + '\n';
  50149. }
  50150. return result;
  50151. }
  50152. /**
  50153. * Returns a WGSL string representing a variable.
  50154. *
  50155. * @param {string} type - The variable's type.
  50156. * @param {string} name - The variable's name.
  50157. * @param {?number} [count=null] - The array length.
  50158. * @return {string} The WGSL snippet that defines a variable.
  50159. */
  50160. getVar( type, name, count = null ) {
  50161. let snippet = `var ${ name } : `;
  50162. if ( count !== null ) {
  50163. snippet += this.generateArrayDeclaration( type, count );
  50164. } else {
  50165. snippet += this.getType( type );
  50166. }
  50167. return snippet;
  50168. }
  50169. /**
  50170. * Returns the variables of the given shader stage as a WGSL string.
  50171. *
  50172. * @param {string} shaderStage - The shader stage.
  50173. * @return {string} The WGSL snippet that defines the variables.
  50174. */
  50175. getVars( shaderStage ) {
  50176. const snippets = [];
  50177. const vars = this.vars[ shaderStage ];
  50178. if ( vars !== undefined ) {
  50179. for ( const variable of vars ) {
  50180. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  50181. }
  50182. }
  50183. return `\n${ snippets.join( '\n' ) }\n`;
  50184. }
  50185. /**
  50186. * Returns the varyings of the given shader stage as a WGSL string.
  50187. *
  50188. * @param {string} shaderStage - The shader stage.
  50189. * @return {string} The WGSL snippet that defines the varyings.
  50190. */
  50191. getVaryings( shaderStage ) {
  50192. const snippets = [];
  50193. if ( shaderStage === 'vertex' ) {
  50194. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  50195. }
  50196. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  50197. const varyings = this.varyings;
  50198. const vars = this.vars[ shaderStage ];
  50199. for ( let index = 0; index < varyings.length; index ++ ) {
  50200. const varying = varyings[ index ];
  50201. if ( varying.needsInterpolation ) {
  50202. let attributesSnippet = `@location( ${index} )`;
  50203. if ( varying.interpolationType ) {
  50204. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  50205. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  50206. // Otherwise, optimize interpolation when sensible
  50207. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  50208. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  50209. }
  50210. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  50211. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  50212. vars.push( varying );
  50213. }
  50214. }
  50215. }
  50216. const builtins = this.getBuiltins( shaderStage );
  50217. if ( builtins ) snippets.push( builtins );
  50218. const code = snippets.join( ',\n\t' );
  50219. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  50220. }
  50221. isCustomStruct( nodeUniform ) {
  50222. const attribute = nodeUniform.value;
  50223. const bufferNode = nodeUniform.node;
  50224. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  50225. const isStructArray =
  50226. ( bufferNode.value && bufferNode.value.array ) &&
  50227. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  50228. return isAttributeStructType && ! isStructArray;
  50229. }
  50230. /**
  50231. * Returns the uniforms of the given shader stage as a WGSL string.
  50232. *
  50233. * @param {string} shaderStage - The shader stage.
  50234. * @return {string} The WGSL snippet that defines the uniforms.
  50235. */
  50236. getUniforms( shaderStage ) {
  50237. const uniforms = this.uniforms[ shaderStage ];
  50238. const bindingSnippets = [];
  50239. const bufferSnippets = [];
  50240. const structSnippets = [];
  50241. const uniformGroups = {};
  50242. for ( const uniform of uniforms ) {
  50243. const groupName = uniform.groupNode.name;
  50244. const uniformIndexes = this.bindingsIndexes[ groupName ];
  50245. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  50246. const texture = uniform.node.value;
  50247. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  50248. if ( this.isSampleCompare( texture ) ) {
  50249. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  50250. } else {
  50251. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  50252. }
  50253. }
  50254. let textureType;
  50255. let multisampled = '';
  50256. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  50257. if ( primarySamples > 1 ) {
  50258. multisampled = '_multisampled';
  50259. }
  50260. if ( texture.isCubeTexture === true ) {
  50261. textureType = 'texture_cube<f32>';
  50262. } else if ( texture.isDepthTexture === true ) {
  50263. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  50264. textureType = `texture${ multisampled }_2d<f32>`;
  50265. } else {
  50266. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  50267. }
  50268. } else if ( uniform.node.isStorageTextureNode === true ) {
  50269. const format = getFormat( texture );
  50270. const access = this.getStorageAccess( uniform.node, shaderStage );
  50271. const is3D = uniform.node.value.is3DTexture;
  50272. const isArrayTexture = uniform.node.value.isArrayTexture;
  50273. const dimension = is3D ? '3d' : `2d${ isArrayTexture ? '_array' : '' }`;
  50274. textureType = `texture_storage_${ dimension }<${ format }, ${ access }>`;
  50275. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  50276. textureType = 'texture_2d_array<f32>';
  50277. } else if ( texture.is3DTexture === true || texture.isData3DTexture === true ) {
  50278. textureType = 'texture_3d<f32>';
  50279. } else {
  50280. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  50281. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  50282. }
  50283. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  50284. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  50285. const bufferNode = uniform.node;
  50286. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  50287. const bufferCount = bufferNode.bufferCount;
  50288. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  50289. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  50290. if ( this.isCustomStruct( uniform ) ) {
  50291. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  50292. } else {
  50293. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  50294. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  50295. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  50296. }
  50297. } else {
  50298. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  50299. const groupName = uniform.groupNode.name;
  50300. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  50301. index: uniformIndexes.binding ++,
  50302. id: uniformIndexes.group,
  50303. snippets: []
  50304. } );
  50305. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  50306. }
  50307. }
  50308. for ( const name in uniformGroups ) {
  50309. const group = uniformGroups[ name ];
  50310. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  50311. }
  50312. let code = bindingSnippets.join( '\n' );
  50313. code += bufferSnippets.join( '\n' );
  50314. code += structSnippets.join( '\n' );
  50315. return code;
  50316. }
  50317. /**
  50318. * Controls the code build of the shader stages.
  50319. */
  50320. buildCode() {
  50321. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  50322. this.sortBindingGroups();
  50323. for ( const shaderStage in shadersData ) {
  50324. this.shaderStage = shaderStage;
  50325. const stageData = shadersData[ shaderStage ];
  50326. stageData.uniforms = this.getUniforms( shaderStage );
  50327. stageData.attributes = this.getAttributes( shaderStage );
  50328. stageData.varyings = this.getVaryings( shaderStage );
  50329. stageData.structs = this.getStructs( shaderStage );
  50330. stageData.vars = this.getVars( shaderStage );
  50331. stageData.codes = this.getCodes( shaderStage );
  50332. stageData.directives = this.getDirectives( shaderStage );
  50333. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  50334. //
  50335. let flow = '// code\n\n';
  50336. flow += this.flowCode[ shaderStage ];
  50337. const flowNodes = this.flowNodes[ shaderStage ];
  50338. const mainNode = flowNodes[ flowNodes.length - 1 ];
  50339. const outputNode = mainNode.outputNode;
  50340. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  50341. for ( const node of flowNodes ) {
  50342. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  50343. const slotName = node.name;
  50344. if ( slotName ) {
  50345. if ( flow.length > 0 ) flow += '\n';
  50346. flow += `\t// flow -> ${ slotName }\n`;
  50347. }
  50348. flow += `${ flowSlotData.code }\n\t`;
  50349. if ( node === mainNode && shaderStage !== 'compute' ) {
  50350. flow += '// result\n\n\t';
  50351. if ( shaderStage === 'vertex' ) {
  50352. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  50353. } else if ( shaderStage === 'fragment' ) {
  50354. if ( isOutputStruct ) {
  50355. stageData.returnType = outputNode.getNodeType( this );
  50356. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  50357. flow += `return ${ flowSlotData.result };`;
  50358. } else {
  50359. let structSnippet = '\t@location(0) color: vec4<f32>';
  50360. const builtins = this.getBuiltins( 'output' );
  50361. if ( builtins ) structSnippet += ',\n\t' + builtins;
  50362. stageData.returnType = 'OutputStruct';
  50363. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  50364. stageData.structs += '\nvar<private> output : OutputStruct;';
  50365. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  50366. }
  50367. }
  50368. }
  50369. }
  50370. stageData.flow = flow;
  50371. }
  50372. this.shaderStage = null;
  50373. if ( this.material !== null ) {
  50374. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  50375. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  50376. } else {
  50377. // Early strictly validated in computeNode
  50378. const workgroupSize = this.object.workgroupSize;
  50379. this.computeShader = this._getWGSLComputeCode( shadersData.compute, workgroupSize );
  50380. }
  50381. }
  50382. /**
  50383. * Returns the native shader method name for a given generic name.
  50384. *
  50385. * @param {string} method - The method name to resolve.
  50386. * @param {?string} [output=null] - An optional output.
  50387. * @return {string} The resolved WGSL method name.
  50388. */
  50389. getMethod( method, output = null ) {
  50390. let wgslMethod;
  50391. if ( output !== null ) {
  50392. wgslMethod = this._getWGSLMethod( method + '_' + output );
  50393. }
  50394. if ( wgslMethod === undefined ) {
  50395. wgslMethod = this._getWGSLMethod( method );
  50396. }
  50397. return wgslMethod || method;
  50398. }
  50399. /**
  50400. * Returns the bitcast method name for a given input and outputType.
  50401. *
  50402. * @param {string} type - The output type to bitcast to.
  50403. * @return {string} The resolved WGSL bitcast invocation.
  50404. */
  50405. getBitcastMethod( type ) {
  50406. const dataType = this.getType( type );
  50407. return `bitcast<${ dataType }>`;
  50408. }
  50409. /**
  50410. * Returns the native snippet for a ternary operation.
  50411. *
  50412. * @param {string} condSnippet - The condition determining which expression gets resolved.
  50413. * @param {string} ifSnippet - The expression to resolve to if the condition is true.
  50414. * @param {string} elseSnippet - The expression to resolve to if the condition is false.
  50415. * @return {string} The resolved method name.
  50416. */
  50417. getTernary( condSnippet, ifSnippet, elseSnippet ) {
  50418. return `select( ${elseSnippet}, ${ifSnippet}, ${condSnippet} )`;
  50419. }
  50420. /**
  50421. * Returns the WGSL type of the given node data type.
  50422. *
  50423. * @param {string} type - The node data type.
  50424. * @return {string} The WGSL type.
  50425. */
  50426. getType( type ) {
  50427. return wgslTypeLib[ type ] || type;
  50428. }
  50429. /**
  50430. * Whether the requested feature is available or not.
  50431. *
  50432. * @param {string} name - The requested feature.
  50433. * @return {boolean} Whether the requested feature is supported or not.
  50434. */
  50435. isAvailable( name ) {
  50436. let result = supports[ name ];
  50437. if ( result === undefined ) {
  50438. if ( name === 'float32Filterable' ) {
  50439. result = this.renderer.hasFeature( 'float32-filterable' );
  50440. } else if ( name === 'clipDistance' ) {
  50441. result = this.renderer.hasFeature( 'clip-distances' );
  50442. }
  50443. supports[ name ] = result;
  50444. }
  50445. return result;
  50446. }
  50447. /**
  50448. * Returns the native shader method name for a given generic name.
  50449. *
  50450. * @private
  50451. * @param {string} method - The method name to resolve.
  50452. * @return {string} The resolved WGSL method name.
  50453. */
  50454. _getWGSLMethod( method ) {
  50455. if ( wgslPolyfill[ method ] !== undefined ) {
  50456. this._include( method );
  50457. }
  50458. return wgslMethods[ method ];
  50459. }
  50460. /**
  50461. * Includes the given method name into the current
  50462. * function node.
  50463. *
  50464. * @private
  50465. * @param {string} name - The method name to include.
  50466. * @return {CodeNode} The respective code node.
  50467. */
  50468. _include( name ) {
  50469. const codeNode = wgslPolyfill[ name ];
  50470. codeNode.build( this );
  50471. if ( this.currentFunctionNode !== null ) {
  50472. this.currentFunctionNode.includes.push( codeNode );
  50473. }
  50474. return codeNode;
  50475. }
  50476. /**
  50477. * Returns a WGSL vertex shader based on the given shader data.
  50478. *
  50479. * @private
  50480. * @param {Object} shaderData - The shader data.
  50481. * @return {string} The vertex shader.
  50482. */
  50483. _getWGSLVertexCode( shaderData ) {
  50484. return `${ this.getSignature() }
  50485. // directives
  50486. ${shaderData.directives}
  50487. // structs
  50488. ${shaderData.structs}
  50489. // uniforms
  50490. ${shaderData.uniforms}
  50491. // varyings
  50492. ${shaderData.varyings}
  50493. var<private> varyings : VaryingsStruct;
  50494. // codes
  50495. ${shaderData.codes}
  50496. @vertex
  50497. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  50498. // vars
  50499. ${shaderData.vars}
  50500. // flow
  50501. ${shaderData.flow}
  50502. return varyings;
  50503. }
  50504. `;
  50505. }
  50506. /**
  50507. * Returns a WGSL fragment shader based on the given shader data.
  50508. *
  50509. * @private
  50510. * @param {Object} shaderData - The shader data.
  50511. * @return {string} The vertex shader.
  50512. */
  50513. _getWGSLFragmentCode( shaderData ) {
  50514. return `${ this.getSignature() }
  50515. // global
  50516. ${ diagnostics }
  50517. // structs
  50518. ${shaderData.structs}
  50519. // uniforms
  50520. ${shaderData.uniforms}
  50521. // codes
  50522. ${shaderData.codes}
  50523. @fragment
  50524. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  50525. // vars
  50526. ${shaderData.vars}
  50527. // flow
  50528. ${shaderData.flow}
  50529. }
  50530. `;
  50531. }
  50532. /**
  50533. * Returns a WGSL compute shader based on the given shader data.
  50534. *
  50535. * @private
  50536. * @param {Object} shaderData - The shader data.
  50537. * @param {string} workgroupSize - The workgroup size.
  50538. * @return {string} The vertex shader.
  50539. */
  50540. _getWGSLComputeCode( shaderData, workgroupSize ) {
  50541. const [ workgroupSizeX, workgroupSizeY, workgroupSizeZ ] = workgroupSize;
  50542. return `${ this.getSignature() }
  50543. // directives
  50544. ${ shaderData.directives }
  50545. // system
  50546. var<private> instanceIndex : u32;
  50547. // locals
  50548. ${ shaderData.scopedArrays }
  50549. // structs
  50550. ${ shaderData.structs }
  50551. // uniforms
  50552. ${ shaderData.uniforms }
  50553. // codes
  50554. ${ shaderData.codes }
  50555. @compute @workgroup_size( ${ workgroupSizeX }, ${ workgroupSizeY }, ${ workgroupSizeZ } )
  50556. fn main( ${ shaderData.attributes } ) {
  50557. // system
  50558. instanceIndex = globalId.x
  50559. + globalId.y * ( ${ workgroupSizeX } * numWorkgroups.x )
  50560. + globalId.z * ( ${ workgroupSizeX } * numWorkgroups.x ) * ( ${ workgroupSizeY } * numWorkgroups.y );
  50561. // vars
  50562. ${ shaderData.vars }
  50563. // flow
  50564. ${ shaderData.flow }
  50565. }
  50566. `;
  50567. }
  50568. /**
  50569. * Returns a WGSL struct based on the given name and variables.
  50570. *
  50571. * @private
  50572. * @param {string} name - The struct name.
  50573. * @param {string} vars - The struct variables.
  50574. * @return {string} The WGSL snippet representing a struct.
  50575. */
  50576. _getWGSLStruct( name, vars ) {
  50577. return `
  50578. struct ${name} {
  50579. ${vars}
  50580. };`;
  50581. }
  50582. /**
  50583. * Returns a WGSL struct binding.
  50584. *
  50585. * @private
  50586. * @param {string} name - The struct name.
  50587. * @param {string} vars - The struct variables.
  50588. * @param {string} access - The access.
  50589. * @param {number} [binding=0] - The binding index.
  50590. * @param {number} [group=0] - The group index.
  50591. * @return {string} The WGSL snippet representing a struct binding.
  50592. */
  50593. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  50594. const structName = name + 'Struct';
  50595. const structSnippet = this._getWGSLStruct( structName, vars );
  50596. return `${structSnippet}
  50597. @binding( ${ binding } ) @group( ${ group } )
  50598. var<${access}> ${ name } : ${ structName };`;
  50599. }
  50600. }
  50601. /**
  50602. * A WebGPU backend utility module with common helpers.
  50603. *
  50604. * @private
  50605. */
  50606. class WebGPUUtils {
  50607. /**
  50608. * Constructs a new utility object.
  50609. *
  50610. * @param {WebGPUBackend} backend - The WebGPU backend.
  50611. */
  50612. constructor( backend ) {
  50613. /**
  50614. * A reference to the WebGPU backend.
  50615. *
  50616. * @type {WebGPUBackend}
  50617. */
  50618. this.backend = backend;
  50619. }
  50620. /**
  50621. * Returns the depth/stencil GPU format for the given render context.
  50622. *
  50623. * @param {RenderContext} renderContext - The render context.
  50624. * @return {string} The depth/stencil GPU texture format.
  50625. */
  50626. getCurrentDepthStencilFormat( renderContext ) {
  50627. let format;
  50628. if ( renderContext.depthTexture !== null ) {
  50629. format = this.getTextureFormatGPU( renderContext.depthTexture );
  50630. } else if ( renderContext.depth && renderContext.stencil ) {
  50631. format = GPUTextureFormat.Depth24PlusStencil8;
  50632. } else if ( renderContext.depth ) {
  50633. format = GPUTextureFormat.Depth24Plus;
  50634. }
  50635. return format;
  50636. }
  50637. /**
  50638. * Returns the GPU format for the given texture.
  50639. *
  50640. * @param {Texture} texture - The texture.
  50641. * @return {string} The GPU texture format.
  50642. */
  50643. getTextureFormatGPU( texture ) {
  50644. return this.backend.get( texture ).format;
  50645. }
  50646. /**
  50647. * Returns an object that defines the multi-sampling state of the given texture.
  50648. *
  50649. * @param {Texture} texture - The texture.
  50650. * @return {Object} The multi-sampling state.
  50651. */
  50652. getTextureSampleData( texture ) {
  50653. let samples;
  50654. if ( texture.isFramebufferTexture ) {
  50655. samples = 1;
  50656. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  50657. const renderer = this.backend.renderer;
  50658. const renderTarget = renderer.getRenderTarget();
  50659. samples = renderTarget ? renderTarget.samples : renderer.samples;
  50660. } else if ( texture.renderTarget ) {
  50661. samples = texture.renderTarget.samples;
  50662. }
  50663. samples = samples || 1;
  50664. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  50665. const primarySamples = isMSAA ? 1 : samples;
  50666. return { samples, primarySamples, isMSAA };
  50667. }
  50668. /**
  50669. * Returns the default color attachment's GPU format of the current render context.
  50670. *
  50671. * @param {RenderContext} renderContext - The render context.
  50672. * @return {string} The GPU texture format of the default color attachment.
  50673. */
  50674. getCurrentColorFormat( renderContext ) {
  50675. let format;
  50676. if ( renderContext.textures !== null ) {
  50677. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  50678. } else {
  50679. format = this.getPreferredCanvasFormat(); // default context format
  50680. }
  50681. return format;
  50682. }
  50683. /**
  50684. * Returns the output color space of the current render context.
  50685. *
  50686. * @param {RenderContext} renderContext - The render context.
  50687. * @return {string} The output color space.
  50688. */
  50689. getCurrentColorSpace( renderContext ) {
  50690. if ( renderContext.textures !== null ) {
  50691. return renderContext.textures[ 0 ].colorSpace;
  50692. }
  50693. return this.backend.renderer.outputColorSpace;
  50694. }
  50695. /**
  50696. * Returns GPU primitive topology for the given object and material.
  50697. *
  50698. * @param {Object3D} object - The 3D object.
  50699. * @param {Material} material - The material.
  50700. * @return {string} The GPU primitive topology.
  50701. */
  50702. getPrimitiveTopology( object, material ) {
  50703. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  50704. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  50705. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  50706. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  50707. }
  50708. /**
  50709. * Returns a modified sample count from the given sample count value.
  50710. *
  50711. * That is required since WebGPU only supports either 1 or 4.
  50712. *
  50713. * @param {number} sampleCount - The input sample count.
  50714. * @return {number} The (potentially updated) output sample count.
  50715. */
  50716. getSampleCount( sampleCount ) {
  50717. return sampleCount >= 4 ? 4 : 1;
  50718. }
  50719. /**
  50720. * Returns the sample count of the given render context.
  50721. *
  50722. * @param {RenderContext} renderContext - The render context.
  50723. * @return {number} The sample count.
  50724. */
  50725. getSampleCountRenderContext( renderContext ) {
  50726. if ( renderContext.textures !== null ) {
  50727. return this.getSampleCount( renderContext.sampleCount );
  50728. }
  50729. return this.getSampleCount( this.backend.renderer.samples );
  50730. }
  50731. /**
  50732. * Returns the preferred canvas format.
  50733. *
  50734. * There is a separate method for this so it's possible to
  50735. * honor edge cases for specific devices.
  50736. *
  50737. * @return {string} The GPU texture format of the canvas.
  50738. */
  50739. getPreferredCanvasFormat() {
  50740. const outputType = this.backend.parameters.outputType;
  50741. if ( outputType === undefined ) {
  50742. return navigator.gpu.getPreferredCanvasFormat();
  50743. } else if ( outputType === UnsignedByteType ) {
  50744. return GPUTextureFormat.BGRA8Unorm;
  50745. } else if ( outputType === HalfFloatType ) {
  50746. return GPUTextureFormat.RGBA16Float;
  50747. } else {
  50748. throw new Error( 'Unsupported outputType' );
  50749. }
  50750. }
  50751. }
  50752. const typedArraysToVertexFormatPrefix = new Map( [
  50753. [ Int8Array, [ 'sint8', 'snorm8' ]],
  50754. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  50755. [ Int16Array, [ 'sint16', 'snorm16' ]],
  50756. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  50757. [ Int32Array, [ 'sint32', 'snorm32' ]],
  50758. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  50759. [ Float32Array, [ 'float32', ]],
  50760. ] );
  50761. if ( typeof Float16Array !== 'undefined' ) {
  50762. typedArraysToVertexFormatPrefix.set( Float16Array, [ 'float16' ] );
  50763. }
  50764. const typedAttributeToVertexFormatPrefix = new Map( [
  50765. [ Float16BufferAttribute, [ 'float16', ]],
  50766. ] );
  50767. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  50768. [ Int32Array, 'sint32' ],
  50769. [ Int16Array, 'sint32' ], // patch for INT16
  50770. [ Uint32Array, 'uint32' ],
  50771. [ Uint16Array, 'uint32' ], // patch for UINT16
  50772. [ Float32Array, 'float32' ]
  50773. ] );
  50774. /**
  50775. * A WebGPU backend utility module for managing shader attributes.
  50776. *
  50777. * @private
  50778. */
  50779. class WebGPUAttributeUtils {
  50780. /**
  50781. * Constructs a new utility object.
  50782. *
  50783. * @param {WebGPUBackend} backend - The WebGPU backend.
  50784. */
  50785. constructor( backend ) {
  50786. /**
  50787. * A reference to the WebGPU backend.
  50788. *
  50789. * @type {WebGPUBackend}
  50790. */
  50791. this.backend = backend;
  50792. }
  50793. /**
  50794. * Creates the GPU buffer for the given buffer attribute.
  50795. *
  50796. * @param {BufferAttribute} attribute - The buffer attribute.
  50797. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  50798. */
  50799. createAttribute( attribute, usage ) {
  50800. const bufferAttribute = this._getBufferAttribute( attribute );
  50801. const backend = this.backend;
  50802. const bufferData = backend.get( bufferAttribute );
  50803. let buffer = bufferData.buffer;
  50804. if ( buffer === undefined ) {
  50805. const device = backend.device;
  50806. let array = bufferAttribute.array;
  50807. // patch for INT16 and UINT16
  50808. if ( attribute.normalized === false ) {
  50809. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  50810. array = new Int32Array( array );
  50811. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  50812. array = new Uint32Array( array );
  50813. if ( usage & GPUBufferUsage.INDEX ) {
  50814. for ( let i = 0; i < array.length; i ++ ) {
  50815. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  50816. }
  50817. }
  50818. }
  50819. }
  50820. bufferAttribute.array = array;
  50821. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  50822. array = new array.constructor( bufferAttribute.count * 4 );
  50823. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  50824. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  50825. }
  50826. // Update BufferAttribute
  50827. bufferAttribute.itemSize = 4;
  50828. bufferAttribute.array = array;
  50829. bufferData._force3to4BytesAlignment = true;
  50830. }
  50831. // ensure 4 byte alignment
  50832. const byteLength = array.byteLength;
  50833. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  50834. buffer = device.createBuffer( {
  50835. label: bufferAttribute.name,
  50836. size: size,
  50837. usage: usage,
  50838. mappedAtCreation: true
  50839. } );
  50840. new array.constructor( buffer.getMappedRange() ).set( array );
  50841. buffer.unmap();
  50842. bufferData.buffer = buffer;
  50843. }
  50844. }
  50845. /**
  50846. * Updates the GPU buffer of the given buffer attribute.
  50847. *
  50848. * @param {BufferAttribute} attribute - The buffer attribute.
  50849. */
  50850. updateAttribute( attribute ) {
  50851. const bufferAttribute = this._getBufferAttribute( attribute );
  50852. const backend = this.backend;
  50853. const device = backend.device;
  50854. const bufferData = backend.get( bufferAttribute );
  50855. const buffer = backend.get( bufferAttribute ).buffer;
  50856. let array = bufferAttribute.array;
  50857. // if storage buffer ensure 4 byte alignment
  50858. if ( bufferData._force3to4BytesAlignment === true ) {
  50859. array = new array.constructor( bufferAttribute.count * 4 );
  50860. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  50861. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  50862. }
  50863. bufferAttribute.array = array;
  50864. }
  50865. const isTypedArray = this._isTypedArray( array );
  50866. const updateRanges = bufferAttribute.updateRanges;
  50867. if ( updateRanges.length === 0 ) {
  50868. // Not using update ranges
  50869. device.queue.writeBuffer(
  50870. buffer,
  50871. 0,
  50872. array,
  50873. 0
  50874. );
  50875. } else {
  50876. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  50877. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  50878. const range = updateRanges[ i ];
  50879. let dataOffset, size;
  50880. if ( bufferData._force3to4BytesAlignment === true ) {
  50881. const vertexStart = Math.floor( range.start / 3 );
  50882. const vertexCount = Math.ceil( range.count / 3 );
  50883. dataOffset = vertexStart * 4 * byteOffsetFactor;
  50884. size = vertexCount * 4 * byteOffsetFactor;
  50885. } else {
  50886. dataOffset = range.start * byteOffsetFactor;
  50887. size = range.count * byteOffsetFactor;
  50888. }
  50889. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  50890. device.queue.writeBuffer(
  50891. buffer,
  50892. bufferOffset,
  50893. array,
  50894. dataOffset,
  50895. size
  50896. );
  50897. }
  50898. bufferAttribute.clearUpdateRanges();
  50899. }
  50900. }
  50901. /**
  50902. * This method creates the vertex buffer layout data which are
  50903. * require when creating a render pipeline for the given render object.
  50904. *
  50905. * @param {RenderObject} renderObject - The render object.
  50906. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  50907. */
  50908. createShaderVertexBuffers( renderObject ) {
  50909. const attributes = renderObject.getAttributes();
  50910. const vertexBuffers = new Map();
  50911. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  50912. const geometryAttribute = attributes[ slot ];
  50913. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  50914. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  50915. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  50916. if ( vertexBufferLayout === undefined ) {
  50917. let arrayStride, stepMode;
  50918. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  50919. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  50920. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  50921. } else {
  50922. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  50923. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  50924. }
  50925. // patch for INT16 and UINT16
  50926. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  50927. arrayStride = 4;
  50928. }
  50929. vertexBufferLayout = {
  50930. arrayStride,
  50931. attributes: [],
  50932. stepMode
  50933. };
  50934. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  50935. }
  50936. const format = this._getVertexFormat( geometryAttribute );
  50937. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  50938. vertexBufferLayout.attributes.push( {
  50939. shaderLocation: slot,
  50940. offset,
  50941. format
  50942. } );
  50943. }
  50944. return Array.from( vertexBuffers.values() );
  50945. }
  50946. /**
  50947. * Destroys the GPU buffer of the given buffer attribute.
  50948. *
  50949. * @param {BufferAttribute} attribute - The buffer attribute.
  50950. */
  50951. destroyAttribute( attribute ) {
  50952. const backend = this.backend;
  50953. const data = backend.get( this._getBufferAttribute( attribute ) );
  50954. data.buffer.destroy();
  50955. backend.delete( attribute );
  50956. }
  50957. /**
  50958. * This method performs a readback operation by moving buffer data from
  50959. * a storage buffer attribute from the GPU to the CPU.
  50960. *
  50961. * @async
  50962. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  50963. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  50964. */
  50965. async getArrayBufferAsync( attribute ) {
  50966. const backend = this.backend;
  50967. const device = backend.device;
  50968. const data = backend.get( this._getBufferAttribute( attribute ) );
  50969. const bufferGPU = data.buffer;
  50970. const size = bufferGPU.size;
  50971. const readBufferGPU = device.createBuffer( {
  50972. label: `${ attribute.name }_readback`,
  50973. size,
  50974. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  50975. } );
  50976. const cmdEncoder = device.createCommandEncoder( {
  50977. label: `readback_encoder_${ attribute.name }`
  50978. } );
  50979. cmdEncoder.copyBufferToBuffer(
  50980. bufferGPU,
  50981. 0,
  50982. readBufferGPU,
  50983. 0,
  50984. size
  50985. );
  50986. const gpuCommands = cmdEncoder.finish();
  50987. device.queue.submit( [ gpuCommands ] );
  50988. await readBufferGPU.mapAsync( GPUMapMode.READ );
  50989. const arrayBuffer = readBufferGPU.getMappedRange();
  50990. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  50991. readBufferGPU.unmap();
  50992. return dstBuffer.buffer;
  50993. }
  50994. /**
  50995. * Returns the vertex format of the given buffer attribute.
  50996. *
  50997. * @private
  50998. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  50999. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  51000. */
  51001. _getVertexFormat( geometryAttribute ) {
  51002. const { itemSize, normalized } = geometryAttribute;
  51003. const ArrayType = geometryAttribute.array.constructor;
  51004. const AttributeType = geometryAttribute.constructor;
  51005. let format;
  51006. if ( itemSize === 1 ) {
  51007. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  51008. } else {
  51009. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  51010. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  51011. if ( prefix ) {
  51012. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  51013. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  51014. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  51015. if ( paddedItemSize % 1 ) {
  51016. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  51017. }
  51018. format = `${prefix}x${paddedItemSize}`;
  51019. }
  51020. }
  51021. if ( ! format ) {
  51022. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  51023. }
  51024. return format;
  51025. }
  51026. /**
  51027. * Returns `true` if the given array is a typed array.
  51028. *
  51029. * @private
  51030. * @param {any} array - The array.
  51031. * @return {boolean} Whether the given array is a typed array or not.
  51032. */
  51033. _isTypedArray( array ) {
  51034. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  51035. }
  51036. /**
  51037. * Utility method for handling interleaved buffer attributes correctly.
  51038. * To process them, their `InterleavedBuffer` is returned.
  51039. *
  51040. * @private
  51041. * @param {BufferAttribute} attribute - The attribute.
  51042. * @return {BufferAttribute|InterleavedBuffer}
  51043. */
  51044. _getBufferAttribute( attribute ) {
  51045. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  51046. return attribute;
  51047. }
  51048. }
  51049. /**
  51050. * A WebGPU backend utility module for managing bindings.
  51051. *
  51052. * When reading the documentation it's helpful to keep in mind that
  51053. * all class definitions starting with 'GPU*' are modules from the
  51054. * WebGPU API. So for example `BindGroup` is a class from the engine
  51055. * whereas `GPUBindGroup` is a class from WebGPU.
  51056. *
  51057. * @private
  51058. */
  51059. class WebGPUBindingUtils {
  51060. /**
  51061. * Constructs a new utility object.
  51062. *
  51063. * @param {WebGPUBackend} backend - The WebGPU backend.
  51064. */
  51065. constructor( backend ) {
  51066. /**
  51067. * A reference to the WebGPU backend.
  51068. *
  51069. * @type {WebGPUBackend}
  51070. */
  51071. this.backend = backend;
  51072. /**
  51073. * A cache for managing bind group layouts.
  51074. *
  51075. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  51076. */
  51077. this.bindGroupLayoutCache = new WeakMap();
  51078. }
  51079. /**
  51080. * Creates a GPU bind group layout for the given bind group.
  51081. *
  51082. * @param {BindGroup} bindGroup - The bind group.
  51083. * @return {GPUBindGroupLayout} The GPU bind group layout.
  51084. */
  51085. createBindingsLayout( bindGroup ) {
  51086. const backend = this.backend;
  51087. const device = backend.device;
  51088. const entries = [];
  51089. let index = 0;
  51090. for ( const binding of bindGroup.bindings ) {
  51091. const bindingGPU = {
  51092. binding: index ++,
  51093. visibility: binding.visibility
  51094. };
  51095. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  51096. const buffer = {}; // GPUBufferBindingLayout
  51097. if ( binding.isStorageBuffer ) {
  51098. if ( binding.visibility & 4 ) {
  51099. // compute
  51100. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  51101. buffer.type = GPUBufferBindingType.Storage;
  51102. } else {
  51103. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  51104. }
  51105. } else {
  51106. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  51107. }
  51108. }
  51109. bindingGPU.buffer = buffer;
  51110. } else if ( binding.isSampledTexture && binding.store ) {
  51111. const storageTexture = {}; // GPUStorageTextureBindingLayout
  51112. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  51113. const access = binding.access;
  51114. if ( access === NodeAccess.READ_WRITE ) {
  51115. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  51116. } else if ( access === NodeAccess.WRITE_ONLY ) {
  51117. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  51118. } else {
  51119. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  51120. }
  51121. if ( binding.texture.isArrayTexture ) {
  51122. storageTexture.viewDimension = GPUTextureViewDimension.TwoDArray;
  51123. } else if ( binding.texture.is3DTexture ) {
  51124. storageTexture.viewDimension = GPUTextureViewDimension.ThreeD;
  51125. }
  51126. bindingGPU.storageTexture = storageTexture;
  51127. } else if ( binding.isSampledTexture ) {
  51128. const texture = {}; // GPUTextureBindingLayout
  51129. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  51130. if ( primarySamples > 1 ) {
  51131. texture.multisampled = true;
  51132. if ( ! binding.texture.isDepthTexture ) {
  51133. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  51134. }
  51135. }
  51136. if ( binding.texture.isDepthTexture ) {
  51137. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  51138. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  51139. } else {
  51140. texture.sampleType = GPUTextureSampleType.Depth;
  51141. }
  51142. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  51143. const type = binding.texture.type;
  51144. if ( type === IntType ) {
  51145. texture.sampleType = GPUTextureSampleType.SInt;
  51146. } else if ( type === UnsignedIntType ) {
  51147. texture.sampleType = GPUTextureSampleType.UInt;
  51148. } else if ( type === FloatType ) {
  51149. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  51150. texture.sampleType = GPUTextureSampleType.Float;
  51151. } else {
  51152. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  51153. }
  51154. }
  51155. }
  51156. if ( binding.isSampledCubeTexture ) {
  51157. texture.viewDimension = GPUTextureViewDimension.Cube;
  51158. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  51159. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  51160. } else if ( binding.isSampledTexture3D ) {
  51161. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  51162. }
  51163. bindingGPU.texture = texture;
  51164. } else if ( binding.isSampler ) {
  51165. const sampler = {}; // GPUSamplerBindingLayout
  51166. if ( binding.texture.isDepthTexture ) {
  51167. if ( binding.texture.compareFunction !== null ) {
  51168. sampler.type = GPUSamplerBindingType.Comparison;
  51169. } else if ( backend.compatibilityMode ) {
  51170. sampler.type = GPUSamplerBindingType.NonFiltering;
  51171. }
  51172. }
  51173. bindingGPU.sampler = sampler;
  51174. } else {
  51175. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  51176. }
  51177. entries.push( bindingGPU );
  51178. }
  51179. return device.createBindGroupLayout( { entries } );
  51180. }
  51181. /**
  51182. * Creates bindings from the given bind group definition.
  51183. *
  51184. * @param {BindGroup} bindGroup - The bind group.
  51185. * @param {Array<BindGroup>} bindings - Array of bind groups.
  51186. * @param {number} cacheIndex - The cache index.
  51187. * @param {number} version - The version.
  51188. */
  51189. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  51190. const { backend, bindGroupLayoutCache } = this;
  51191. const bindingsData = backend.get( bindGroup );
  51192. // setup (static) binding layout and (dynamic) binding group
  51193. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  51194. if ( bindLayoutGPU === undefined ) {
  51195. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  51196. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  51197. }
  51198. let bindGroupGPU;
  51199. if ( cacheIndex > 0 ) {
  51200. if ( bindingsData.groups === undefined ) {
  51201. bindingsData.groups = [];
  51202. bindingsData.versions = [];
  51203. }
  51204. if ( bindingsData.versions[ cacheIndex ] === version ) {
  51205. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  51206. }
  51207. }
  51208. if ( bindGroupGPU === undefined ) {
  51209. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  51210. if ( cacheIndex > 0 ) {
  51211. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  51212. bindingsData.versions[ cacheIndex ] = version;
  51213. }
  51214. }
  51215. bindingsData.group = bindGroupGPU;
  51216. bindingsData.layout = bindLayoutGPU;
  51217. }
  51218. /**
  51219. * Updates a buffer binding.
  51220. *
  51221. * @param {Buffer} binding - The buffer binding to update.
  51222. */
  51223. updateBinding( binding ) {
  51224. const backend = this.backend;
  51225. const device = backend.device;
  51226. const buffer = binding.buffer;
  51227. const bufferGPU = backend.get( binding ).buffer;
  51228. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  51229. }
  51230. /**
  51231. * Creates a GPU bind group for the camera index.
  51232. *
  51233. * @param {Uint32Array} data - The index data.
  51234. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  51235. * @return {GPUBindGroup} The GPU bind group.
  51236. */
  51237. createBindGroupIndex( data, layout ) {
  51238. const backend = this.backend;
  51239. const device = backend.device;
  51240. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  51241. const index = data[ 0 ];
  51242. const buffer = device.createBuffer( {
  51243. label: 'bindingCameraIndex_' + index,
  51244. size: 16, // uint(4) * 4
  51245. usage: usage
  51246. } );
  51247. device.queue.writeBuffer( buffer, 0, data, 0 );
  51248. const entries = [ { binding: 0, resource: { buffer } } ];
  51249. return device.createBindGroup( {
  51250. label: 'bindGroupCameraIndex_' + index,
  51251. layout,
  51252. entries
  51253. } );
  51254. }
  51255. /**
  51256. * Creates a GPU bind group for the given bind group and GPU layout.
  51257. *
  51258. * @param {BindGroup} bindGroup - The bind group.
  51259. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  51260. * @return {GPUBindGroup} The GPU bind group.
  51261. */
  51262. createBindGroup( bindGroup, layoutGPU ) {
  51263. const backend = this.backend;
  51264. const device = backend.device;
  51265. let bindingPoint = 0;
  51266. const entriesGPU = [];
  51267. for ( const binding of bindGroup.bindings ) {
  51268. if ( binding.isUniformBuffer ) {
  51269. const bindingData = backend.get( binding );
  51270. if ( bindingData.buffer === undefined ) {
  51271. const byteLength = binding.byteLength;
  51272. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  51273. const bufferGPU = device.createBuffer( {
  51274. label: 'bindingBuffer_' + binding.name,
  51275. size: byteLength,
  51276. usage: usage
  51277. } );
  51278. bindingData.buffer = bufferGPU;
  51279. }
  51280. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  51281. } else if ( binding.isStorageBuffer ) {
  51282. const bindingData = backend.get( binding );
  51283. if ( bindingData.buffer === undefined ) {
  51284. const attribute = binding.attribute;
  51285. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  51286. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  51287. bindingData.buffer = backend.get( attribute ).buffer;
  51288. }
  51289. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  51290. } else if ( binding.isSampledTexture ) {
  51291. const textureData = backend.get( binding.texture );
  51292. let resourceGPU;
  51293. if ( textureData.externalTexture !== undefined ) {
  51294. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  51295. } else {
  51296. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  51297. let propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }`;
  51298. if ( textureData.texture.depthOrArrayLayers > 1 ) {
  51299. propertyName += `-${ textureData.texture.depthOrArrayLayers }`;
  51300. }
  51301. propertyName += `-${ mipLevelCount }`;
  51302. resourceGPU = textureData[ propertyName ];
  51303. if ( resourceGPU === undefined ) {
  51304. const aspectGPU = GPUTextureAspect.All;
  51305. let dimensionViewGPU;
  51306. if ( binding.isSampledCubeTexture ) {
  51307. dimensionViewGPU = GPUTextureViewDimension.Cube;
  51308. } else if ( binding.isSampledTexture3D ) {
  51309. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  51310. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  51311. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  51312. } else {
  51313. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  51314. }
  51315. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  51316. }
  51317. }
  51318. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  51319. } else if ( binding.isSampler ) {
  51320. const textureGPU = backend.get( binding.texture );
  51321. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  51322. }
  51323. bindingPoint ++;
  51324. }
  51325. return device.createBindGroup( {
  51326. label: 'bindGroup_' + bindGroup.name,
  51327. layout: layoutGPU,
  51328. entries: entriesGPU
  51329. } );
  51330. }
  51331. }
  51332. /**
  51333. * A WebGPU backend utility module for managing pipelines.
  51334. *
  51335. * @private
  51336. */
  51337. class WebGPUPipelineUtils {
  51338. /**
  51339. * Constructs a new utility object.
  51340. *
  51341. * @param {WebGPUBackend} backend - The WebGPU backend.
  51342. */
  51343. constructor( backend ) {
  51344. /**
  51345. * A reference to the WebGPU backend.
  51346. *
  51347. * @type {WebGPUBackend}
  51348. */
  51349. this.backend = backend;
  51350. /**
  51351. * A Weak Map that tracks the active pipeline for render or compute passes.
  51352. *
  51353. * @private
  51354. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  51355. */
  51356. this._activePipelines = new WeakMap();
  51357. }
  51358. /**
  51359. * Sets the given pipeline for the given pass. The method makes sure to only set the
  51360. * pipeline when necessary.
  51361. *
  51362. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  51363. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  51364. */
  51365. setPipeline( pass, pipeline ) {
  51366. const currentPipeline = this._activePipelines.get( pass );
  51367. if ( currentPipeline !== pipeline ) {
  51368. pass.setPipeline( pipeline );
  51369. this._activePipelines.set( pass, pipeline );
  51370. }
  51371. }
  51372. /**
  51373. * Returns the sample count derived from the given render context.
  51374. *
  51375. * @private
  51376. * @param {RenderContext} renderContext - The render context.
  51377. * @return {number} The sample count.
  51378. */
  51379. _getSampleCount( renderContext ) {
  51380. return this.backend.utils.getSampleCountRenderContext( renderContext );
  51381. }
  51382. /**
  51383. * Creates a render pipeline for the given render object.
  51384. *
  51385. * @param {RenderObject} renderObject - The render object.
  51386. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  51387. */
  51388. createRenderPipeline( renderObject, promises ) {
  51389. const { object, material, geometry, pipeline } = renderObject;
  51390. const { vertexProgram, fragmentProgram } = pipeline;
  51391. const backend = this.backend;
  51392. const device = backend.device;
  51393. const utils = backend.utils;
  51394. const pipelineData = backend.get( pipeline );
  51395. // bind group layouts
  51396. const bindGroupLayouts = [];
  51397. for ( const bindGroup of renderObject.getBindings() ) {
  51398. const bindingsData = backend.get( bindGroup );
  51399. bindGroupLayouts.push( bindingsData.layout );
  51400. }
  51401. // vertex buffers
  51402. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  51403. // blending
  51404. let blending;
  51405. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  51406. blending = this._getBlending( material );
  51407. }
  51408. // stencil
  51409. let stencilFront = {};
  51410. if ( material.stencilWrite === true ) {
  51411. stencilFront = {
  51412. compare: this._getStencilCompare( material ),
  51413. failOp: this._getStencilOperation( material.stencilFail ),
  51414. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  51415. passOp: this._getStencilOperation( material.stencilZPass )
  51416. };
  51417. }
  51418. const colorWriteMask = this._getColorWriteMask( material );
  51419. const targets = [];
  51420. if ( renderObject.context.textures !== null ) {
  51421. const textures = renderObject.context.textures;
  51422. for ( let i = 0; i < textures.length; i ++ ) {
  51423. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  51424. targets.push( {
  51425. format: colorFormat,
  51426. blend: blending,
  51427. writeMask: colorWriteMask
  51428. } );
  51429. }
  51430. } else {
  51431. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  51432. targets.push( {
  51433. format: colorFormat,
  51434. blend: blending,
  51435. writeMask: colorWriteMask
  51436. } );
  51437. }
  51438. const vertexModule = backend.get( vertexProgram ).module;
  51439. const fragmentModule = backend.get( fragmentProgram ).module;
  51440. const primitiveState = this._getPrimitiveState( object, geometry, material );
  51441. const depthCompare = this._getDepthCompare( material );
  51442. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  51443. const sampleCount = this._getSampleCount( renderObject.context );
  51444. const pipelineDescriptor = {
  51445. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  51446. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  51447. fragment: Object.assign( {}, fragmentModule, { targets } ),
  51448. primitive: primitiveState,
  51449. multisample: {
  51450. count: sampleCount,
  51451. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  51452. },
  51453. layout: device.createPipelineLayout( {
  51454. bindGroupLayouts
  51455. } )
  51456. };
  51457. const depthStencil = {};
  51458. const renderDepth = renderObject.context.depth;
  51459. const renderStencil = renderObject.context.stencil;
  51460. if ( renderDepth === true || renderStencil === true ) {
  51461. if ( renderDepth === true ) {
  51462. depthStencil.format = depthStencilFormat;
  51463. depthStencil.depthWriteEnabled = material.depthWrite;
  51464. depthStencil.depthCompare = depthCompare;
  51465. }
  51466. if ( renderStencil === true ) {
  51467. depthStencil.stencilFront = stencilFront;
  51468. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  51469. depthStencil.stencilReadMask = material.stencilFuncMask;
  51470. depthStencil.stencilWriteMask = material.stencilWriteMask;
  51471. }
  51472. if ( material.polygonOffset === true ) {
  51473. depthStencil.depthBias = material.polygonOffsetUnits;
  51474. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  51475. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  51476. }
  51477. pipelineDescriptor.depthStencil = depthStencil;
  51478. }
  51479. if ( promises === null ) {
  51480. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  51481. } else {
  51482. const p = new Promise( ( resolve /*, reject*/ ) => {
  51483. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  51484. pipelineData.pipeline = pipeline;
  51485. resolve();
  51486. } );
  51487. } );
  51488. promises.push( p );
  51489. }
  51490. }
  51491. /**
  51492. * Creates GPU render bundle encoder for the given render context.
  51493. *
  51494. * @param {RenderContext} renderContext - The render context.
  51495. * @param {?string} [label='renderBundleEncoder'] - The label.
  51496. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  51497. */
  51498. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  51499. const backend = this.backend;
  51500. const { utils, device } = backend;
  51501. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  51502. const colorFormat = utils.getCurrentColorFormat( renderContext );
  51503. const sampleCount = this._getSampleCount( renderContext );
  51504. const descriptor = {
  51505. label: label,
  51506. colorFormats: [ colorFormat ],
  51507. depthStencilFormat,
  51508. sampleCount
  51509. };
  51510. return device.createRenderBundleEncoder( descriptor );
  51511. }
  51512. /**
  51513. * Creates a compute pipeline for the given compute node.
  51514. *
  51515. * @param {ComputePipeline} pipeline - The compute pipeline.
  51516. * @param {Array<BindGroup>} bindings - The bindings.
  51517. */
  51518. createComputePipeline( pipeline, bindings ) {
  51519. const backend = this.backend;
  51520. const device = backend.device;
  51521. const computeProgram = backend.get( pipeline.computeProgram ).module;
  51522. const pipelineGPU = backend.get( pipeline );
  51523. // bind group layouts
  51524. const bindGroupLayouts = [];
  51525. for ( const bindingsGroup of bindings ) {
  51526. const bindingsData = backend.get( bindingsGroup );
  51527. bindGroupLayouts.push( bindingsData.layout );
  51528. }
  51529. pipelineGPU.pipeline = device.createComputePipeline( {
  51530. compute: computeProgram,
  51531. layout: device.createPipelineLayout( {
  51532. bindGroupLayouts
  51533. } )
  51534. } );
  51535. }
  51536. /**
  51537. * Returns the blending state as a descriptor object required
  51538. * for the pipeline creation.
  51539. *
  51540. * @private
  51541. * @param {Material} material - The material.
  51542. * @return {Object} The blending state.
  51543. */
  51544. _getBlending( material ) {
  51545. let color, alpha;
  51546. const blending = material.blending;
  51547. const blendSrc = material.blendSrc;
  51548. const blendDst = material.blendDst;
  51549. const blendEquation = material.blendEquation;
  51550. if ( blending === CustomBlending ) {
  51551. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  51552. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  51553. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  51554. color = {
  51555. srcFactor: this._getBlendFactor( blendSrc ),
  51556. dstFactor: this._getBlendFactor( blendDst ),
  51557. operation: this._getBlendOperation( blendEquation )
  51558. };
  51559. alpha = {
  51560. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  51561. dstFactor: this._getBlendFactor( blendDstAlpha ),
  51562. operation: this._getBlendOperation( blendEquationAlpha )
  51563. };
  51564. } else {
  51565. const premultipliedAlpha = material.premultipliedAlpha;
  51566. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  51567. color = {
  51568. srcFactor: srcRGB,
  51569. dstFactor: dstRGB,
  51570. operation: GPUBlendOperation.Add
  51571. };
  51572. alpha = {
  51573. srcFactor: srcAlpha,
  51574. dstFactor: dstAlpha,
  51575. operation: GPUBlendOperation.Add
  51576. };
  51577. };
  51578. if ( premultipliedAlpha ) {
  51579. switch ( blending ) {
  51580. case NormalBlending:
  51581. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  51582. break;
  51583. case AdditiveBlending:
  51584. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  51585. break;
  51586. case SubtractiveBlending:
  51587. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  51588. break;
  51589. case MultiplyBlending:
  51590. setBlend( GPUBlendFactor.Dst, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.Zero, GPUBlendFactor.One );
  51591. break;
  51592. }
  51593. } else {
  51594. switch ( blending ) {
  51595. case NormalBlending:
  51596. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  51597. break;
  51598. case AdditiveBlending:
  51599. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  51600. break;
  51601. case SubtractiveBlending:
  51602. console.error( 'THREE.WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true' );
  51603. break;
  51604. case MultiplyBlending:
  51605. console.error( 'THREE.WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true' );
  51606. break;
  51607. }
  51608. }
  51609. }
  51610. if ( color !== undefined && alpha !== undefined ) {
  51611. return { color, alpha };
  51612. } else {
  51613. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  51614. }
  51615. }
  51616. /**
  51617. * Returns the GPU blend factor which is required for the pipeline creation.
  51618. *
  51619. * @private
  51620. * @param {number} blend - The blend factor as a three.js constant.
  51621. * @return {string} The GPU blend factor.
  51622. */
  51623. _getBlendFactor( blend ) {
  51624. let blendFactor;
  51625. switch ( blend ) {
  51626. case ZeroFactor:
  51627. blendFactor = GPUBlendFactor.Zero;
  51628. break;
  51629. case OneFactor:
  51630. blendFactor = GPUBlendFactor.One;
  51631. break;
  51632. case SrcColorFactor:
  51633. blendFactor = GPUBlendFactor.Src;
  51634. break;
  51635. case OneMinusSrcColorFactor:
  51636. blendFactor = GPUBlendFactor.OneMinusSrc;
  51637. break;
  51638. case SrcAlphaFactor:
  51639. blendFactor = GPUBlendFactor.SrcAlpha;
  51640. break;
  51641. case OneMinusSrcAlphaFactor:
  51642. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  51643. break;
  51644. case DstColorFactor:
  51645. blendFactor = GPUBlendFactor.Dst;
  51646. break;
  51647. case OneMinusDstColorFactor:
  51648. blendFactor = GPUBlendFactor.OneMinusDst;
  51649. break;
  51650. case DstAlphaFactor:
  51651. blendFactor = GPUBlendFactor.DstAlpha;
  51652. break;
  51653. case OneMinusDstAlphaFactor:
  51654. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  51655. break;
  51656. case SrcAlphaSaturateFactor:
  51657. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  51658. break;
  51659. case BlendColorFactor:
  51660. blendFactor = GPUBlendFactor.Constant;
  51661. break;
  51662. case OneMinusBlendColorFactor:
  51663. blendFactor = GPUBlendFactor.OneMinusConstant;
  51664. break;
  51665. default:
  51666. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  51667. }
  51668. return blendFactor;
  51669. }
  51670. /**
  51671. * Returns the GPU stencil compare function which is required for the pipeline creation.
  51672. *
  51673. * @private
  51674. * @param {Material} material - The material.
  51675. * @return {string} The GPU stencil compare function.
  51676. */
  51677. _getStencilCompare( material ) {
  51678. let stencilCompare;
  51679. const stencilFunc = material.stencilFunc;
  51680. switch ( stencilFunc ) {
  51681. case NeverStencilFunc:
  51682. stencilCompare = GPUCompareFunction.Never;
  51683. break;
  51684. case AlwaysStencilFunc:
  51685. stencilCompare = GPUCompareFunction.Always;
  51686. break;
  51687. case LessStencilFunc:
  51688. stencilCompare = GPUCompareFunction.Less;
  51689. break;
  51690. case LessEqualStencilFunc:
  51691. stencilCompare = GPUCompareFunction.LessEqual;
  51692. break;
  51693. case EqualStencilFunc:
  51694. stencilCompare = GPUCompareFunction.Equal;
  51695. break;
  51696. case GreaterEqualStencilFunc:
  51697. stencilCompare = GPUCompareFunction.GreaterEqual;
  51698. break;
  51699. case GreaterStencilFunc:
  51700. stencilCompare = GPUCompareFunction.Greater;
  51701. break;
  51702. case NotEqualStencilFunc:
  51703. stencilCompare = GPUCompareFunction.NotEqual;
  51704. break;
  51705. default:
  51706. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  51707. }
  51708. return stencilCompare;
  51709. }
  51710. /**
  51711. * Returns the GPU stencil operation which is required for the pipeline creation.
  51712. *
  51713. * @private
  51714. * @param {number} op - A three.js constant defining the stencil operation.
  51715. * @return {string} The GPU stencil operation.
  51716. */
  51717. _getStencilOperation( op ) {
  51718. let stencilOperation;
  51719. switch ( op ) {
  51720. case KeepStencilOp:
  51721. stencilOperation = GPUStencilOperation.Keep;
  51722. break;
  51723. case ZeroStencilOp:
  51724. stencilOperation = GPUStencilOperation.Zero;
  51725. break;
  51726. case ReplaceStencilOp:
  51727. stencilOperation = GPUStencilOperation.Replace;
  51728. break;
  51729. case InvertStencilOp:
  51730. stencilOperation = GPUStencilOperation.Invert;
  51731. break;
  51732. case IncrementStencilOp:
  51733. stencilOperation = GPUStencilOperation.IncrementClamp;
  51734. break;
  51735. case DecrementStencilOp:
  51736. stencilOperation = GPUStencilOperation.DecrementClamp;
  51737. break;
  51738. case IncrementWrapStencilOp:
  51739. stencilOperation = GPUStencilOperation.IncrementWrap;
  51740. break;
  51741. case DecrementWrapStencilOp:
  51742. stencilOperation = GPUStencilOperation.DecrementWrap;
  51743. break;
  51744. default:
  51745. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  51746. }
  51747. return stencilOperation;
  51748. }
  51749. /**
  51750. * Returns the GPU blend operation which is required for the pipeline creation.
  51751. *
  51752. * @private
  51753. * @param {number} blendEquation - A three.js constant defining the blend equation.
  51754. * @return {string} The GPU blend operation.
  51755. */
  51756. _getBlendOperation( blendEquation ) {
  51757. let blendOperation;
  51758. switch ( blendEquation ) {
  51759. case AddEquation:
  51760. blendOperation = GPUBlendOperation.Add;
  51761. break;
  51762. case SubtractEquation:
  51763. blendOperation = GPUBlendOperation.Subtract;
  51764. break;
  51765. case ReverseSubtractEquation:
  51766. blendOperation = GPUBlendOperation.ReverseSubtract;
  51767. break;
  51768. case MinEquation:
  51769. blendOperation = GPUBlendOperation.Min;
  51770. break;
  51771. case MaxEquation:
  51772. blendOperation = GPUBlendOperation.Max;
  51773. break;
  51774. default:
  51775. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  51776. }
  51777. return blendOperation;
  51778. }
  51779. /**
  51780. * Returns the primitive state as a descriptor object required
  51781. * for the pipeline creation.
  51782. *
  51783. * @private
  51784. * @param {Object3D} object - The 3D object.
  51785. * @param {BufferGeometry} geometry - The geometry.
  51786. * @param {Material} material - The material.
  51787. * @return {Object} The primitive state.
  51788. */
  51789. _getPrimitiveState( object, geometry, material ) {
  51790. const descriptor = {};
  51791. const utils = this.backend.utils;
  51792. //
  51793. descriptor.topology = utils.getPrimitiveTopology( object, material );
  51794. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  51795. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  51796. }
  51797. //
  51798. let flipSided = ( material.side === BackSide );
  51799. if ( object.isMesh && object.matrixWorld.determinant() < 0 ) flipSided = ! flipSided;
  51800. descriptor.frontFace = ( flipSided === true ) ? GPUFrontFace.CW : GPUFrontFace.CCW;
  51801. //
  51802. descriptor.cullMode = ( material.side === DoubleSide ) ? GPUCullMode.None : GPUCullMode.Back;
  51803. return descriptor;
  51804. }
  51805. /**
  51806. * Returns the GPU color write mask which is required for the pipeline creation.
  51807. *
  51808. * @private
  51809. * @param {Material} material - The material.
  51810. * @return {number} The GPU color write mask.
  51811. */
  51812. _getColorWriteMask( material ) {
  51813. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  51814. }
  51815. /**
  51816. * Returns the GPU depth compare function which is required for the pipeline creation.
  51817. *
  51818. * @private
  51819. * @param {Material} material - The material.
  51820. * @return {string} The GPU depth compare function.
  51821. */
  51822. _getDepthCompare( material ) {
  51823. let depthCompare;
  51824. if ( material.depthTest === false ) {
  51825. depthCompare = GPUCompareFunction.Always;
  51826. } else {
  51827. const depthFunc = material.depthFunc;
  51828. switch ( depthFunc ) {
  51829. case NeverDepth:
  51830. depthCompare = GPUCompareFunction.Never;
  51831. break;
  51832. case AlwaysDepth:
  51833. depthCompare = GPUCompareFunction.Always;
  51834. break;
  51835. case LessDepth:
  51836. depthCompare = GPUCompareFunction.Less;
  51837. break;
  51838. case LessEqualDepth:
  51839. depthCompare = GPUCompareFunction.LessEqual;
  51840. break;
  51841. case EqualDepth:
  51842. depthCompare = GPUCompareFunction.Equal;
  51843. break;
  51844. case GreaterEqualDepth:
  51845. depthCompare = GPUCompareFunction.GreaterEqual;
  51846. break;
  51847. case GreaterDepth:
  51848. depthCompare = GPUCompareFunction.Greater;
  51849. break;
  51850. case NotEqualDepth:
  51851. depthCompare = GPUCompareFunction.NotEqual;
  51852. break;
  51853. default:
  51854. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  51855. }
  51856. }
  51857. return depthCompare;
  51858. }
  51859. }
  51860. /**
  51861. * Manages a pool of WebGPU timestamp queries for performance measurement.
  51862. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  51863. *
  51864. * @augments TimestampQueryPool
  51865. */
  51866. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  51867. /**
  51868. * Creates a new WebGPU timestamp query pool.
  51869. *
  51870. * @param {GPUDevice} device - The WebGPU device to create queries on.
  51871. * @param {string} type - The type identifier for this query pool.
  51872. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  51873. */
  51874. constructor( device, type, maxQueries = 2048 ) {
  51875. super( maxQueries );
  51876. this.device = device;
  51877. this.type = type;
  51878. this.querySet = this.device.createQuerySet( {
  51879. type: 'timestamp',
  51880. count: this.maxQueries,
  51881. label: `queryset_global_timestamp_${type}`
  51882. } );
  51883. const bufferSize = this.maxQueries * 8;
  51884. this.resolveBuffer = this.device.createBuffer( {
  51885. label: `buffer_timestamp_resolve_${type}`,
  51886. size: bufferSize,
  51887. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  51888. } );
  51889. this.resultBuffer = this.device.createBuffer( {
  51890. label: `buffer_timestamp_result_${type}`,
  51891. size: bufferSize,
  51892. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  51893. } );
  51894. }
  51895. /**
  51896. * Allocates a pair of queries for a given render context.
  51897. *
  51898. * @param {string} uid - A unique identifier for the render context.
  51899. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  51900. */
  51901. allocateQueriesForContext( uid ) {
  51902. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  51903. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  51904. 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() } ).` );
  51905. return null;
  51906. }
  51907. const baseOffset = this.currentQueryIndex;
  51908. this.currentQueryIndex += 2;
  51909. this.queryOffsets.set( uid, baseOffset );
  51910. return baseOffset;
  51911. }
  51912. /**
  51913. * Asynchronously resolves all pending queries and returns the total duration.
  51914. * If there's already a pending resolve operation, returns that promise instead.
  51915. *
  51916. * @async
  51917. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  51918. */
  51919. async resolveQueriesAsync() {
  51920. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  51921. return this.lastValue;
  51922. }
  51923. if ( this.pendingResolve ) {
  51924. return this.pendingResolve;
  51925. }
  51926. this.pendingResolve = this._resolveQueries();
  51927. try {
  51928. const result = await this.pendingResolve;
  51929. return result;
  51930. } finally {
  51931. this.pendingResolve = null;
  51932. }
  51933. }
  51934. /**
  51935. * Internal method to resolve queries and calculate total duration.
  51936. *
  51937. * @async
  51938. * @private
  51939. * @returns {Promise<number>} The total duration in milliseconds.
  51940. */
  51941. async _resolveQueries() {
  51942. if ( this.isDisposed ) {
  51943. return this.lastValue;
  51944. }
  51945. try {
  51946. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  51947. return this.lastValue;
  51948. }
  51949. const currentOffsets = new Map( this.queryOffsets );
  51950. const queryCount = this.currentQueryIndex;
  51951. const bytesUsed = queryCount * 8;
  51952. // Reset state before GPU work
  51953. this.currentQueryIndex = 0;
  51954. this.queryOffsets.clear();
  51955. const commandEncoder = this.device.createCommandEncoder();
  51956. commandEncoder.resolveQuerySet(
  51957. this.querySet,
  51958. 0,
  51959. queryCount,
  51960. this.resolveBuffer,
  51961. 0
  51962. );
  51963. commandEncoder.copyBufferToBuffer(
  51964. this.resolveBuffer,
  51965. 0,
  51966. this.resultBuffer,
  51967. 0,
  51968. bytesUsed
  51969. );
  51970. const commandBuffer = commandEncoder.finish();
  51971. this.device.queue.submit( [ commandBuffer ] );
  51972. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  51973. return this.lastValue;
  51974. }
  51975. // Create and track the mapping operation
  51976. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  51977. if ( this.isDisposed ) {
  51978. if ( this.resultBuffer.mapState === 'mapped' ) {
  51979. this.resultBuffer.unmap();
  51980. }
  51981. return this.lastValue;
  51982. }
  51983. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  51984. let totalDuration = 0;
  51985. for ( const [ , baseOffset ] of currentOffsets ) {
  51986. const startTime = times[ baseOffset ];
  51987. const endTime = times[ baseOffset + 1 ];
  51988. const duration = Number( endTime - startTime ) / 1e6;
  51989. totalDuration += duration;
  51990. }
  51991. this.resultBuffer.unmap();
  51992. this.lastValue = totalDuration;
  51993. return totalDuration;
  51994. } catch ( error ) {
  51995. console.error( 'Error resolving queries:', error );
  51996. if ( this.resultBuffer.mapState === 'mapped' ) {
  51997. this.resultBuffer.unmap();
  51998. }
  51999. return this.lastValue;
  52000. }
  52001. }
  52002. /**
  52003. * Dispose of the query pool.
  52004. *
  52005. * @async
  52006. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  52007. */
  52008. async dispose() {
  52009. if ( this.isDisposed ) {
  52010. return;
  52011. }
  52012. this.isDisposed = true;
  52013. // Wait for pending resolve operation
  52014. if ( this.pendingResolve ) {
  52015. try {
  52016. await this.pendingResolve;
  52017. } catch ( error ) {
  52018. console.error( 'Error waiting for pending resolve:', error );
  52019. }
  52020. }
  52021. // Ensure buffer is unmapped before destroying
  52022. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  52023. try {
  52024. this.resultBuffer.unmap();
  52025. } catch ( error ) {
  52026. console.error( 'Error unmapping buffer:', error );
  52027. }
  52028. }
  52029. // Destroy resources
  52030. if ( this.querySet ) {
  52031. this.querySet.destroy();
  52032. this.querySet = null;
  52033. }
  52034. if ( this.resolveBuffer ) {
  52035. this.resolveBuffer.destroy();
  52036. this.resolveBuffer = null;
  52037. }
  52038. if ( this.resultBuffer ) {
  52039. this.resultBuffer.destroy();
  52040. this.resultBuffer = null;
  52041. }
  52042. this.queryOffsets.clear();
  52043. this.pendingResolve = null;
  52044. }
  52045. }
  52046. /*// debugger tools
  52047. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  52048. //*/
  52049. /**
  52050. * A backend implementation targeting WebGPU.
  52051. *
  52052. * @private
  52053. * @augments Backend
  52054. */
  52055. class WebGPUBackend extends Backend {
  52056. /**
  52057. * WebGPUBackend options.
  52058. *
  52059. * @typedef {Object} WebGPUBackend~Options
  52060. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  52061. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  52062. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  52063. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  52064. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  52065. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  52066. * @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.
  52067. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  52068. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  52069. * @property {string} [powerPreference=undefined] - The power preference.
  52070. * @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.
  52071. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  52072. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  52073. */
  52074. /**
  52075. * Constructs a new WebGPU backend.
  52076. *
  52077. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  52078. */
  52079. constructor( parameters = {} ) {
  52080. super( parameters );
  52081. /**
  52082. * This flag can be used for type testing.
  52083. *
  52084. * @type {boolean}
  52085. * @readonly
  52086. * @default true
  52087. */
  52088. this.isWebGPUBackend = true;
  52089. // some parameters require default values other than "undefined"
  52090. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  52091. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  52092. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  52093. /**
  52094. * Indicates whether the backend is in compatibility mode or not.
  52095. * @type {boolean}
  52096. * @default false
  52097. */
  52098. this.compatibilityMode = this.parameters.compatibilityMode;
  52099. /**
  52100. * A reference to the device.
  52101. *
  52102. * @type {?GPUDevice}
  52103. * @default null
  52104. */
  52105. this.device = null;
  52106. /**
  52107. * A reference to the context.
  52108. *
  52109. * @type {?GPUCanvasContext}
  52110. * @default null
  52111. */
  52112. this.context = null;
  52113. /**
  52114. * A reference to the color attachment of the default framebuffer.
  52115. *
  52116. * @type {?GPUTexture}
  52117. * @default null
  52118. */
  52119. this.colorBuffer = null;
  52120. /**
  52121. * A reference to the default render pass descriptor.
  52122. *
  52123. * @type {?Object}
  52124. * @default null
  52125. */
  52126. this.defaultRenderPassdescriptor = null;
  52127. /**
  52128. * A reference to a backend module holding common utility functions.
  52129. *
  52130. * @type {WebGPUUtils}
  52131. */
  52132. this.utils = new WebGPUUtils( this );
  52133. /**
  52134. * A reference to a backend module holding shader attribute-related
  52135. * utility functions.
  52136. *
  52137. * @type {WebGPUAttributeUtils}
  52138. */
  52139. this.attributeUtils = new WebGPUAttributeUtils( this );
  52140. /**
  52141. * A reference to a backend module holding shader binding-related
  52142. * utility functions.
  52143. *
  52144. * @type {WebGPUBindingUtils}
  52145. */
  52146. this.bindingUtils = new WebGPUBindingUtils( this );
  52147. /**
  52148. * A reference to a backend module holding shader pipeline-related
  52149. * utility functions.
  52150. *
  52151. * @type {WebGPUPipelineUtils}
  52152. */
  52153. this.pipelineUtils = new WebGPUPipelineUtils( this );
  52154. /**
  52155. * A reference to a backend module holding shader texture-related
  52156. * utility functions.
  52157. *
  52158. * @type {WebGPUTextureUtils}
  52159. */
  52160. this.textureUtils = new WebGPUTextureUtils( this );
  52161. /**
  52162. * A map that manages the resolve buffers for occlusion queries.
  52163. *
  52164. * @type {Map<number,GPUBuffer>}
  52165. */
  52166. this.occludedResolveCache = new Map();
  52167. }
  52168. /**
  52169. * Initializes the backend so it is ready for usage.
  52170. *
  52171. * @async
  52172. * @param {Renderer} renderer - The renderer.
  52173. * @return {Promise} A Promise that resolves when the backend has been initialized.
  52174. */
  52175. async init( renderer ) {
  52176. await super.init( renderer );
  52177. //
  52178. const parameters = this.parameters;
  52179. // create the device if it is not passed with parameters
  52180. let device;
  52181. if ( parameters.device === undefined ) {
  52182. const adapterOptions = {
  52183. powerPreference: parameters.powerPreference,
  52184. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  52185. };
  52186. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  52187. if ( adapter === null ) {
  52188. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  52189. }
  52190. // feature support
  52191. const features = Object.values( GPUFeatureName );
  52192. const supportedFeatures = [];
  52193. for ( const name of features ) {
  52194. if ( adapter.features.has( name ) ) {
  52195. supportedFeatures.push( name );
  52196. }
  52197. }
  52198. const deviceDescriptor = {
  52199. requiredFeatures: supportedFeatures,
  52200. requiredLimits: parameters.requiredLimits
  52201. };
  52202. device = await adapter.requestDevice( deviceDescriptor );
  52203. } else {
  52204. device = parameters.device;
  52205. }
  52206. device.lost.then( ( info ) => {
  52207. const deviceLossInfo = {
  52208. api: 'WebGPU',
  52209. message: info.message || 'Unknown reason',
  52210. reason: info.reason || null,
  52211. originalEvent: info
  52212. };
  52213. renderer.onDeviceLost( deviceLossInfo );
  52214. } );
  52215. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  52216. this.device = device;
  52217. this.context = context;
  52218. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  52219. const toneMappingMode = ColorManagement.getToneMappingMode( this.renderer.outputColorSpace );
  52220. this.context.configure( {
  52221. device: this.device,
  52222. format: this.utils.getPreferredCanvasFormat(),
  52223. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  52224. alphaMode: alphaMode,
  52225. toneMapping: {
  52226. mode: toneMappingMode
  52227. }
  52228. } );
  52229. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  52230. this.updateSize();
  52231. }
  52232. /**
  52233. * The coordinate system of the backend.
  52234. *
  52235. * @type {number}
  52236. * @readonly
  52237. */
  52238. get coordinateSystem() {
  52239. return WebGPUCoordinateSystem;
  52240. }
  52241. /**
  52242. * This method performs a readback operation by moving buffer data from
  52243. * a storage buffer attribute from the GPU to the CPU.
  52244. *
  52245. * @async
  52246. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  52247. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  52248. */
  52249. async getArrayBufferAsync( attribute ) {
  52250. return await this.attributeUtils.getArrayBufferAsync( attribute );
  52251. }
  52252. /**
  52253. * Returns the backend's rendering context.
  52254. *
  52255. * @return {GPUCanvasContext} The rendering context.
  52256. */
  52257. getContext() {
  52258. return this.context;
  52259. }
  52260. /**
  52261. * Returns the default render pass descriptor.
  52262. *
  52263. * In WebGPU, the default framebuffer must be configured
  52264. * like custom framebuffers so the backend needs a render
  52265. * pass descriptor even when rendering directly to screen.
  52266. *
  52267. * @private
  52268. * @return {Object} The render pass descriptor.
  52269. */
  52270. _getDefaultRenderPassDescriptor() {
  52271. let descriptor = this.defaultRenderPassdescriptor;
  52272. if ( descriptor === null ) {
  52273. const renderer = this.renderer;
  52274. descriptor = {
  52275. colorAttachments: [ {
  52276. view: null
  52277. } ],
  52278. };
  52279. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  52280. descriptor.depthStencilAttachment = {
  52281. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  52282. };
  52283. }
  52284. const colorAttachment = descriptor.colorAttachments[ 0 ];
  52285. if ( this.renderer.samples > 0 ) {
  52286. colorAttachment.view = this.colorBuffer.createView();
  52287. } else {
  52288. colorAttachment.resolveTarget = undefined;
  52289. }
  52290. this.defaultRenderPassdescriptor = descriptor;
  52291. }
  52292. const colorAttachment = descriptor.colorAttachments[ 0 ];
  52293. if ( this.renderer.samples > 0 ) {
  52294. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  52295. } else {
  52296. colorAttachment.view = this.context.getCurrentTexture().createView();
  52297. }
  52298. return descriptor;
  52299. }
  52300. /**
  52301. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  52302. *
  52303. * @param {RenderContext} renderContext - The render context.
  52304. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  52305. *
  52306. * @private
  52307. */
  52308. _isRenderCameraDepthArray( renderContext ) {
  52309. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  52310. }
  52311. /**
  52312. * Returns the render pass descriptor for the given render context.
  52313. *
  52314. * @private
  52315. * @param {RenderContext} renderContext - The render context.
  52316. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  52317. * @return {Object} The render pass descriptor.
  52318. */
  52319. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  52320. const renderTarget = renderContext.renderTarget;
  52321. const renderTargetData = this.get( renderTarget );
  52322. let descriptors = renderTargetData.descriptors;
  52323. if ( descriptors === undefined ||
  52324. renderTargetData.width !== renderTarget.width ||
  52325. renderTargetData.height !== renderTarget.height ||
  52326. renderTargetData.samples !== renderTarget.samples
  52327. ) {
  52328. descriptors = {};
  52329. renderTargetData.descriptors = descriptors;
  52330. }
  52331. const cacheKey = renderContext.getCacheKey();
  52332. let descriptorBase = descriptors[ cacheKey ];
  52333. if ( descriptorBase === undefined ) {
  52334. const textures = renderContext.textures;
  52335. const textureViews = [];
  52336. let sliceIndex;
  52337. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  52338. for ( let i = 0; i < textures.length; i ++ ) {
  52339. const textureData = this.get( textures[ i ] );
  52340. const viewDescriptor = {
  52341. label: `colorAttachment_${ i }`,
  52342. baseMipLevel: renderContext.activeMipmapLevel,
  52343. mipLevelCount: 1,
  52344. baseArrayLayer: renderContext.activeCubeFace,
  52345. arrayLayerCount: 1,
  52346. dimension: GPUTextureViewDimension.TwoD
  52347. };
  52348. if ( renderTarget.isRenderTarget3D ) {
  52349. sliceIndex = renderContext.activeCubeFace;
  52350. viewDescriptor.baseArrayLayer = 0;
  52351. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  52352. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  52353. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  52354. if ( isRenderCameraDepthArray === true ) {
  52355. const cameras = renderContext.camera.cameras;
  52356. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  52357. const layerViewDescriptor = {
  52358. ...viewDescriptor,
  52359. baseArrayLayer: layer,
  52360. arrayLayerCount: 1,
  52361. dimension: GPUTextureViewDimension.TwoD
  52362. };
  52363. const textureView = textureData.texture.createView( layerViewDescriptor );
  52364. textureViews.push( {
  52365. view: textureView,
  52366. resolveTarget: undefined,
  52367. depthSlice: undefined
  52368. } );
  52369. }
  52370. } else {
  52371. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  52372. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  52373. }
  52374. }
  52375. if ( isRenderCameraDepthArray !== true ) {
  52376. const textureView = textureData.texture.createView( viewDescriptor );
  52377. let view, resolveTarget;
  52378. if ( textureData.msaaTexture !== undefined ) {
  52379. view = textureData.msaaTexture.createView();
  52380. resolveTarget = textureView;
  52381. } else {
  52382. view = textureView;
  52383. resolveTarget = undefined;
  52384. }
  52385. textureViews.push( {
  52386. view,
  52387. resolveTarget,
  52388. depthSlice: sliceIndex
  52389. } );
  52390. }
  52391. }
  52392. descriptorBase = { textureViews };
  52393. if ( renderContext.depth ) {
  52394. const depthTextureData = this.get( renderContext.depthTexture );
  52395. const options = {};
  52396. if ( renderContext.depthTexture.isArrayTexture ) {
  52397. options.dimension = GPUTextureViewDimension.TwoD;
  52398. options.arrayLayerCount = 1;
  52399. options.baseArrayLayer = renderContext.activeCubeFace;
  52400. }
  52401. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  52402. }
  52403. descriptors[ cacheKey ] = descriptorBase;
  52404. renderTargetData.width = renderTarget.width;
  52405. renderTargetData.height = renderTarget.height;
  52406. renderTargetData.samples = renderTarget.samples;
  52407. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  52408. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  52409. }
  52410. const descriptor = {
  52411. colorAttachments: []
  52412. };
  52413. // Apply dynamic properties to cached views
  52414. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  52415. const viewInfo = descriptorBase.textureViews[ i ];
  52416. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  52417. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  52418. clearValue = colorAttachmentsConfig.clearValue;
  52419. }
  52420. descriptor.colorAttachments.push( {
  52421. view: viewInfo.view,
  52422. depthSlice: viewInfo.depthSlice,
  52423. resolveTarget: viewInfo.resolveTarget,
  52424. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  52425. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  52426. clearValue: clearValue
  52427. } );
  52428. }
  52429. if ( descriptorBase.depthStencilView ) {
  52430. descriptor.depthStencilAttachment = {
  52431. view: descriptorBase.depthStencilView
  52432. };
  52433. }
  52434. return descriptor;
  52435. }
  52436. /**
  52437. * This method is executed at the beginning of a render call and prepares
  52438. * the WebGPU state for upcoming render calls
  52439. *
  52440. * @param {RenderContext} renderContext - The render context.
  52441. */
  52442. beginRender( renderContext ) {
  52443. const renderContextData = this.get( renderContext );
  52444. //
  52445. renderContextData.frameCalls = this.renderer.info.render.frameCalls;
  52446. //
  52447. const device = this.device;
  52448. const occlusionQueryCount = renderContext.occlusionQueryCount;
  52449. let occlusionQuerySet;
  52450. if ( occlusionQueryCount > 0 ) {
  52451. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  52452. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  52453. // Get a reference to the array of objects with queries. The renderContextData property
  52454. // can be changed by another render pass before the buffer.mapAsyc() completes.
  52455. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  52456. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  52457. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  52458. //
  52459. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  52460. renderContextData.occlusionQuerySet = occlusionQuerySet;
  52461. renderContextData.occlusionQueryIndex = 0;
  52462. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  52463. renderContextData.lastOcclusionObject = null;
  52464. }
  52465. let descriptor;
  52466. if ( renderContext.textures === null ) {
  52467. descriptor = this._getDefaultRenderPassDescriptor();
  52468. } else {
  52469. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  52470. }
  52471. this.initTimestampQuery( TimestampQuery.RENDER, this.getTimestampUID( renderContext ), descriptor );
  52472. descriptor.occlusionQuerySet = occlusionQuerySet;
  52473. const depthStencilAttachment = descriptor.depthStencilAttachment;
  52474. if ( renderContext.textures !== null ) {
  52475. const colorAttachments = descriptor.colorAttachments;
  52476. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  52477. const colorAttachment = colorAttachments[ i ];
  52478. if ( renderContext.clearColor ) {
  52479. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  52480. colorAttachment.loadOp = GPULoadOp.Clear;
  52481. } else {
  52482. colorAttachment.loadOp = GPULoadOp.Load;
  52483. }
  52484. colorAttachment.storeOp = GPUStoreOp.Store;
  52485. }
  52486. } else {
  52487. const colorAttachment = descriptor.colorAttachments[ 0 ];
  52488. if ( renderContext.clearColor ) {
  52489. colorAttachment.clearValue = renderContext.clearColorValue;
  52490. colorAttachment.loadOp = GPULoadOp.Clear;
  52491. } else {
  52492. colorAttachment.loadOp = GPULoadOp.Load;
  52493. }
  52494. colorAttachment.storeOp = GPUStoreOp.Store;
  52495. }
  52496. //
  52497. if ( renderContext.depth ) {
  52498. if ( renderContext.clearDepth ) {
  52499. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  52500. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  52501. } else {
  52502. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  52503. }
  52504. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  52505. }
  52506. if ( renderContext.stencil ) {
  52507. if ( renderContext.clearStencil ) {
  52508. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  52509. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  52510. } else {
  52511. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  52512. }
  52513. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  52514. }
  52515. //
  52516. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  52517. // shadow arrays - prepare bundle encoders for each camera in an array camera
  52518. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  52519. const cameras = renderContext.camera.cameras;
  52520. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  52521. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  52522. } else {
  52523. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  52524. }
  52525. // Create bundle encoders for each layer
  52526. renderContextData.bundleEncoders = [];
  52527. renderContextData.bundleSets = [];
  52528. // Create separate bundle encoders for each camera in the array
  52529. for ( let i = 0; i < cameras.length; i ++ ) {
  52530. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  52531. renderContext,
  52532. 'renderBundleArrayCamera_' + i
  52533. );
  52534. // Initialize state tracking for this bundle
  52535. const bundleSets = {
  52536. attributes: {},
  52537. bindingGroups: [],
  52538. pipeline: null,
  52539. index: null
  52540. };
  52541. renderContextData.bundleEncoders.push( bundleEncoder );
  52542. renderContextData.bundleSets.push( bundleSets );
  52543. }
  52544. // We'll complete the bundles in finishRender
  52545. renderContextData.currentPass = null;
  52546. } else {
  52547. const currentPass = encoder.beginRenderPass( descriptor );
  52548. renderContextData.currentPass = currentPass;
  52549. if ( renderContext.viewport ) {
  52550. this.updateViewport( renderContext );
  52551. }
  52552. if ( renderContext.scissor ) {
  52553. const { x, y, width, height } = renderContext.scissorValue;
  52554. currentPass.setScissorRect( x, y, width, height );
  52555. }
  52556. }
  52557. //
  52558. renderContextData.descriptor = descriptor;
  52559. renderContextData.encoder = encoder;
  52560. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  52561. renderContextData.renderBundles = [];
  52562. }
  52563. /**
  52564. * This method creates layer descriptors for each camera in an array camera
  52565. * to prepare for rendering to a depth array texture.
  52566. *
  52567. * @param {RenderContext} renderContext - The render context.
  52568. * @param {Object} renderContextData - The render context data.
  52569. * @param {Object} descriptor - The render pass descriptor.
  52570. * @param {ArrayCamera} cameras - The array camera.
  52571. *
  52572. * @private
  52573. */
  52574. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  52575. const depthStencilAttachment = descriptor.depthStencilAttachment;
  52576. renderContextData.layerDescriptors = [];
  52577. const depthTextureData = this.get( renderContext.depthTexture );
  52578. if ( ! depthTextureData.viewCache ) {
  52579. depthTextureData.viewCache = [];
  52580. }
  52581. for ( let i = 0; i < cameras.length; i ++ ) {
  52582. const layerDescriptor = {
  52583. ...descriptor,
  52584. colorAttachments: [ {
  52585. ...descriptor.colorAttachments[ 0 ],
  52586. view: descriptor.colorAttachments[ i ].view
  52587. } ]
  52588. };
  52589. if ( descriptor.depthStencilAttachment ) {
  52590. const layerIndex = i;
  52591. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  52592. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  52593. dimension: GPUTextureViewDimension.TwoD,
  52594. baseArrayLayer: i,
  52595. arrayLayerCount: 1
  52596. } );
  52597. }
  52598. layerDescriptor.depthStencilAttachment = {
  52599. view: depthTextureData.viewCache[ layerIndex ],
  52600. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  52601. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  52602. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  52603. };
  52604. if ( renderContext.stencil ) {
  52605. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  52606. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  52607. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  52608. }
  52609. } else {
  52610. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  52611. }
  52612. renderContextData.layerDescriptors.push( layerDescriptor );
  52613. }
  52614. }
  52615. /**
  52616. * This method updates the layer descriptors for each camera in an array camera
  52617. * to prepare for rendering to a depth array texture.
  52618. *
  52619. * @param {RenderContext} renderContext - The render context.
  52620. * @param {Object} renderContextData - The render context data.
  52621. * @param {ArrayCamera} cameras - The array camera.
  52622. *
  52623. */
  52624. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  52625. for ( let i = 0; i < cameras.length; i ++ ) {
  52626. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  52627. if ( layerDescriptor.depthStencilAttachment ) {
  52628. const depthAttachment = layerDescriptor.depthStencilAttachment;
  52629. if ( renderContext.depth ) {
  52630. if ( renderContext.clearDepth ) {
  52631. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  52632. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  52633. } else {
  52634. depthAttachment.depthLoadOp = GPULoadOp.Load;
  52635. }
  52636. }
  52637. if ( renderContext.stencil ) {
  52638. if ( renderContext.clearStencil ) {
  52639. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  52640. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  52641. } else {
  52642. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  52643. }
  52644. }
  52645. }
  52646. }
  52647. }
  52648. /**
  52649. * This method is executed at the end of a render call and finalizes work
  52650. * after draw calls.
  52651. *
  52652. * @param {RenderContext} renderContext - The render context.
  52653. */
  52654. finishRender( renderContext ) {
  52655. const renderContextData = this.get( renderContext );
  52656. const occlusionQueryCount = renderContext.occlusionQueryCount;
  52657. if ( renderContextData.renderBundles.length > 0 ) {
  52658. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  52659. }
  52660. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  52661. renderContextData.currentPass.endOcclusionQuery();
  52662. }
  52663. // shadow arrays - Execute bundles for each layer
  52664. const encoder = renderContextData.encoder;
  52665. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  52666. const bundles = [];
  52667. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  52668. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  52669. bundles.push( bundleEncoder.finish() );
  52670. }
  52671. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  52672. if ( i < bundles.length ) {
  52673. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  52674. const renderPass = encoder.beginRenderPass( layerDescriptor );
  52675. if ( renderContext.viewport ) {
  52676. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  52677. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  52678. }
  52679. if ( renderContext.scissor ) {
  52680. const { x, y, width, height } = renderContext.scissorValue;
  52681. renderPass.setScissorRect( x, y, width, height );
  52682. }
  52683. renderPass.executeBundles( [ bundles[ i ] ] );
  52684. renderPass.end();
  52685. }
  52686. }
  52687. } else if ( renderContextData.currentPass ) {
  52688. renderContextData.currentPass.end();
  52689. }
  52690. if ( occlusionQueryCount > 0 ) {
  52691. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  52692. //
  52693. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  52694. if ( queryResolveBuffer === undefined ) {
  52695. queryResolveBuffer = this.device.createBuffer(
  52696. {
  52697. size: bufferSize,
  52698. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  52699. }
  52700. );
  52701. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  52702. }
  52703. //
  52704. const readBuffer = this.device.createBuffer(
  52705. {
  52706. size: bufferSize,
  52707. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  52708. }
  52709. );
  52710. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  52711. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  52712. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  52713. renderContextData.occlusionQueryBuffer = readBuffer;
  52714. //
  52715. this.resolveOccludedAsync( renderContext );
  52716. }
  52717. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  52718. //
  52719. if ( renderContext.textures !== null ) {
  52720. const textures = renderContext.textures;
  52721. for ( let i = 0; i < textures.length; i ++ ) {
  52722. const texture = textures[ i ];
  52723. if ( texture.generateMipmaps === true ) {
  52724. this.textureUtils.generateMipmaps( texture );
  52725. }
  52726. }
  52727. }
  52728. }
  52729. /**
  52730. * Returns `true` if the given 3D object is fully occluded by other
  52731. * 3D objects in the scene.
  52732. *
  52733. * @param {RenderContext} renderContext - The render context.
  52734. * @param {Object3D} object - The 3D object to test.
  52735. * @return {boolean} Whether the 3D object is fully occluded or not.
  52736. */
  52737. isOccluded( renderContext, object ) {
  52738. const renderContextData = this.get( renderContext );
  52739. return renderContextData.occluded && renderContextData.occluded.has( object );
  52740. }
  52741. /**
  52742. * This method processes the result of occlusion queries and writes it
  52743. * into render context data.
  52744. *
  52745. * @async
  52746. * @param {RenderContext} renderContext - The render context.
  52747. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  52748. */
  52749. async resolveOccludedAsync( renderContext ) {
  52750. const renderContextData = this.get( renderContext );
  52751. // handle occlusion query results
  52752. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  52753. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  52754. const occluded = new WeakSet();
  52755. renderContextData.currentOcclusionQueryObjects = null;
  52756. renderContextData.currentOcclusionQueryBuffer = null;
  52757. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  52758. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  52759. const results = new BigUint64Array( buffer );
  52760. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  52761. if ( results[ i ] === BigInt( 0 ) ) {
  52762. occluded.add( currentOcclusionQueryObjects[ i ] );
  52763. }
  52764. }
  52765. currentOcclusionQueryBuffer.destroy();
  52766. renderContextData.occluded = occluded;
  52767. }
  52768. }
  52769. /**
  52770. * Updates the viewport with the values from the given render context.
  52771. *
  52772. * @param {RenderContext} renderContext - The render context.
  52773. */
  52774. updateViewport( renderContext ) {
  52775. const { currentPass } = this.get( renderContext );
  52776. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  52777. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  52778. }
  52779. /**
  52780. * Returns the clear color and alpha into a single
  52781. * color object.
  52782. *
  52783. * @return {Color4} The clear color.
  52784. */
  52785. getClearColor() {
  52786. const clearColor = super.getClearColor();
  52787. // only premultiply alpha when alphaMode is "premultiplied"
  52788. if ( this.renderer.alpha === true ) {
  52789. clearColor.r *= clearColor.a;
  52790. clearColor.g *= clearColor.a;
  52791. clearColor.b *= clearColor.a;
  52792. }
  52793. return clearColor;
  52794. }
  52795. /**
  52796. * Performs a clear operation.
  52797. *
  52798. * @param {boolean} color - Whether the color buffer should be cleared or not.
  52799. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  52800. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  52801. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  52802. */
  52803. clear( color, depth, stencil, renderTargetContext = null ) {
  52804. const device = this.device;
  52805. const renderer = this.renderer;
  52806. let colorAttachments = [];
  52807. let depthStencilAttachment;
  52808. let clearValue;
  52809. let supportsDepth;
  52810. let supportsStencil;
  52811. if ( color ) {
  52812. const clearColor = this.getClearColor();
  52813. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  52814. }
  52815. if ( renderTargetContext === null ) {
  52816. supportsDepth = renderer.depth;
  52817. supportsStencil = renderer.stencil;
  52818. const descriptor = this._getDefaultRenderPassDescriptor();
  52819. if ( color ) {
  52820. colorAttachments = descriptor.colorAttachments;
  52821. const colorAttachment = colorAttachments[ 0 ];
  52822. colorAttachment.clearValue = clearValue;
  52823. colorAttachment.loadOp = GPULoadOp.Clear;
  52824. colorAttachment.storeOp = GPUStoreOp.Store;
  52825. }
  52826. if ( supportsDepth || supportsStencil ) {
  52827. depthStencilAttachment = descriptor.depthStencilAttachment;
  52828. }
  52829. } else {
  52830. supportsDepth = renderTargetContext.depth;
  52831. supportsStencil = renderTargetContext.stencil;
  52832. const clearConfig = {
  52833. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  52834. clearValue: color ? clearValue : undefined
  52835. };
  52836. if ( supportsDepth ) {
  52837. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  52838. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  52839. clearConfig.depthStoreOp = GPUStoreOp.Store;
  52840. }
  52841. if ( supportsStencil ) {
  52842. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  52843. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  52844. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  52845. }
  52846. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  52847. colorAttachments = descriptor.colorAttachments;
  52848. depthStencilAttachment = descriptor.depthStencilAttachment;
  52849. }
  52850. if ( supportsDepth && depthStencilAttachment ) {
  52851. if ( depth ) {
  52852. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  52853. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  52854. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  52855. } else {
  52856. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  52857. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  52858. }
  52859. }
  52860. //
  52861. if ( supportsStencil && depthStencilAttachment ) {
  52862. if ( stencil ) {
  52863. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  52864. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  52865. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  52866. } else {
  52867. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  52868. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  52869. }
  52870. }
  52871. //
  52872. const encoder = device.createCommandEncoder( { label: 'clear' } );
  52873. const currentPass = encoder.beginRenderPass( {
  52874. colorAttachments,
  52875. depthStencilAttachment
  52876. } );
  52877. currentPass.end();
  52878. device.queue.submit( [ encoder.finish() ] );
  52879. }
  52880. // compute
  52881. /**
  52882. * This method is executed at the beginning of a compute call and
  52883. * prepares the state for upcoming compute tasks.
  52884. *
  52885. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  52886. */
  52887. beginCompute( computeGroup ) {
  52888. const groupGPU = this.get( computeGroup );
  52889. //
  52890. groupGPU.frameCalls = this.renderer.info.compute.frameCalls;
  52891. //
  52892. const descriptor = {
  52893. label: 'computeGroup_' + computeGroup.id
  52894. };
  52895. this.initTimestampQuery( TimestampQuery.COMPUTE, this.getTimestampUID( computeGroup ), descriptor );
  52896. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  52897. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  52898. }
  52899. /**
  52900. * Executes a compute command for the given compute node.
  52901. *
  52902. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  52903. * @param {Node} computeNode - The compute node.
  52904. * @param {Array<BindGroup>} bindings - The bindings.
  52905. * @param {ComputePipeline} pipeline - The compute pipeline.
  52906. * @param {?(Array<number>|number)} [dispatchSizeOrCount=null] - Array with [ x, y, z ] values for dispatch or a single number for the count.
  52907. */
  52908. compute( computeGroup, computeNode, bindings, pipeline, dispatchSizeOrCount = null ) {
  52909. const computeNodeData = this.get( computeNode );
  52910. const { passEncoderGPU } = this.get( computeGroup );
  52911. // pipeline
  52912. const pipelineGPU = this.get( pipeline ).pipeline;
  52913. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  52914. // bind groups
  52915. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  52916. const bindGroup = bindings[ i ];
  52917. const bindingsData = this.get( bindGroup );
  52918. passEncoderGPU.setBindGroup( i, bindingsData.group );
  52919. }
  52920. let dispatchSize;
  52921. if ( dispatchSizeOrCount === null ) {
  52922. dispatchSizeOrCount = computeNode.count;
  52923. }
  52924. if ( typeof dispatchSizeOrCount === 'number' ) {
  52925. // If a single number is given, we calculate the dispatch size based on the workgroup size
  52926. const count = dispatchSizeOrCount;
  52927. if ( computeNodeData.dispatchSize === undefined || computeNodeData.count !== count ) {
  52928. // cache dispatch size to avoid recalculating it every time
  52929. computeNodeData.dispatchSize = [ 0, 1, 1 ];
  52930. computeNodeData.count = count;
  52931. const workgroupSize = computeNode.workgroupSize;
  52932. let size = workgroupSize[ 0 ];
  52933. for ( let i = 1; i < workgroupSize.length; i ++ )
  52934. size *= workgroupSize[ i ];
  52935. const dispatchCount = Math.ceil( count / size );
  52936. //
  52937. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  52938. dispatchSize = [ dispatchCount, 1, 1 ];
  52939. if ( dispatchCount > maxComputeWorkgroupsPerDimension ) {
  52940. dispatchSize[ 0 ] = Math.min( dispatchCount, maxComputeWorkgroupsPerDimension );
  52941. dispatchSize[ 1 ] = Math.ceil( dispatchCount / maxComputeWorkgroupsPerDimension );
  52942. }
  52943. computeNodeData.dispatchSize = dispatchSize;
  52944. }
  52945. dispatchSize = computeNodeData.dispatchSize;
  52946. } else {
  52947. dispatchSize = dispatchSizeOrCount;
  52948. }
  52949. //
  52950. passEncoderGPU.dispatchWorkgroups(
  52951. dispatchSize[ 0 ],
  52952. dispatchSize[ 1 ] || 1,
  52953. dispatchSize[ 2 ] || 1
  52954. );
  52955. }
  52956. /**
  52957. * This method is executed at the end of a compute call and
  52958. * finalizes work after compute tasks.
  52959. *
  52960. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  52961. */
  52962. finishCompute( computeGroup ) {
  52963. const groupData = this.get( computeGroup );
  52964. groupData.passEncoderGPU.end();
  52965. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  52966. }
  52967. /**
  52968. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  52969. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  52970. *
  52971. * @async
  52972. * @return {Promise} A Promise that resolves when synchronization has been finished.
  52973. */
  52974. async waitForGPU() {
  52975. await this.device.queue.onSubmittedWorkDone();
  52976. }
  52977. // render object
  52978. /**
  52979. * Executes a draw command for the given render object.
  52980. *
  52981. * @param {RenderObject} renderObject - The render object to draw.
  52982. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  52983. */
  52984. draw( renderObject, info ) {
  52985. const { object, material, context, pipeline } = renderObject;
  52986. const bindings = renderObject.getBindings();
  52987. const renderContextData = this.get( context );
  52988. const pipelineGPU = this.get( pipeline ).pipeline;
  52989. const index = renderObject.getIndex();
  52990. const hasIndex = ( index !== null );
  52991. const drawParams = renderObject.getDrawParameters();
  52992. if ( drawParams === null ) return;
  52993. // pipeline
  52994. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  52995. // pipeline
  52996. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  52997. currentSets.pipeline = pipelineGPU;
  52998. // bind groups
  52999. const currentBindingGroups = currentSets.bindingGroups;
  53000. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  53001. const bindGroup = bindings[ i ];
  53002. const bindingsData = this.get( bindGroup );
  53003. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  53004. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  53005. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  53006. }
  53007. }
  53008. // attributes
  53009. // index
  53010. if ( hasIndex === true ) {
  53011. if ( currentSets.index !== index ) {
  53012. const buffer = this.get( index ).buffer;
  53013. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  53014. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  53015. currentSets.index = index;
  53016. }
  53017. }
  53018. // vertex buffers
  53019. const vertexBuffers = renderObject.getVertexBuffers();
  53020. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  53021. const vertexBuffer = vertexBuffers[ i ];
  53022. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  53023. const buffer = this.get( vertexBuffer ).buffer;
  53024. passEncoderGPU.setVertexBuffer( i, buffer );
  53025. currentSets.attributes[ i ] = vertexBuffer;
  53026. }
  53027. }
  53028. // stencil
  53029. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  53030. passEncoderGPU.setStencilReference( material.stencilRef );
  53031. renderContextData.currentStencilRef = material.stencilRef;
  53032. }
  53033. };
  53034. // Define draw function
  53035. const draw = ( passEncoderGPU, currentSets ) => {
  53036. setPipelineAndBindings( passEncoderGPU, currentSets );
  53037. if ( object.isBatchedMesh === true ) {
  53038. const starts = object._multiDrawStarts;
  53039. const counts = object._multiDrawCounts;
  53040. const drawCount = object._multiDrawCount;
  53041. const drawInstances = object._multiDrawInstances;
  53042. if ( drawInstances !== null ) {
  53043. // @deprecated, r174
  53044. warnOnce( 'THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  53045. }
  53046. for ( let i = 0; i < drawCount; i ++ ) {
  53047. const count = drawInstances ? drawInstances[ i ] : 1;
  53048. const firstInstance = count > 1 ? 0 : i;
  53049. if ( hasIndex === true ) {
  53050. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  53051. } else {
  53052. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  53053. }
  53054. info.update( object, counts[ i ], count );
  53055. }
  53056. } else if ( hasIndex === true ) {
  53057. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  53058. const indirect = renderObject.getIndirect();
  53059. if ( indirect !== null ) {
  53060. const buffer = this.get( indirect ).buffer;
  53061. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  53062. } else {
  53063. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  53064. }
  53065. info.update( object, indexCount, instanceCount );
  53066. } else {
  53067. const { vertexCount, instanceCount, firstVertex } = drawParams;
  53068. const indirect = renderObject.getIndirect();
  53069. if ( indirect !== null ) {
  53070. const buffer = this.get( indirect ).buffer;
  53071. passEncoderGPU.drawIndirect( buffer, 0 );
  53072. } else {
  53073. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  53074. }
  53075. info.update( object, vertexCount, instanceCount );
  53076. }
  53077. };
  53078. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  53079. const cameraData = this.get( renderObject.camera );
  53080. const cameras = renderObject.camera.cameras;
  53081. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  53082. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  53083. const bindingsData = this.get( cameraIndex );
  53084. const indexesGPU = [];
  53085. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  53086. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  53087. data[ 0 ] = i;
  53088. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  53089. indexesGPU.push( bindGroupIndex );
  53090. }
  53091. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  53092. }
  53093. const pixelRatio = this.renderer.getPixelRatio();
  53094. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  53095. const subCamera = cameras[ i ];
  53096. if ( object.layers.test( subCamera.layers ) ) {
  53097. const vp = subCamera.viewport;
  53098. let pass = renderContextData.currentPass;
  53099. let sets = renderContextData.currentSets;
  53100. if ( renderContextData.bundleEncoders ) {
  53101. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  53102. const bundleSets = renderContextData.bundleSets[ i ];
  53103. pass = bundleEncoder;
  53104. sets = bundleSets;
  53105. }
  53106. if ( vp ) {
  53107. pass.setViewport(
  53108. Math.floor( vp.x * pixelRatio ),
  53109. Math.floor( vp.y * pixelRatio ),
  53110. Math.floor( vp.width * pixelRatio ),
  53111. Math.floor( vp.height * pixelRatio ),
  53112. context.viewportValue.minDepth,
  53113. context.viewportValue.maxDepth
  53114. );
  53115. }
  53116. // Set camera index binding for this layer
  53117. if ( cameraIndex && cameraData.indexesGPU ) {
  53118. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  53119. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  53120. }
  53121. draw( pass, sets );
  53122. }
  53123. }
  53124. } else {
  53125. // Regular single camera rendering
  53126. if ( renderContextData.currentPass ) {
  53127. // Handle occlusion queries
  53128. if ( renderContextData.occlusionQuerySet !== undefined ) {
  53129. const lastObject = renderContextData.lastOcclusionObject;
  53130. if ( lastObject !== object ) {
  53131. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  53132. renderContextData.currentPass.endOcclusionQuery();
  53133. renderContextData.occlusionQueryIndex ++;
  53134. }
  53135. if ( object.occlusionTest === true ) {
  53136. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  53137. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  53138. }
  53139. renderContextData.lastOcclusionObject = object;
  53140. }
  53141. }
  53142. draw( renderContextData.currentPass, renderContextData.currentSets );
  53143. }
  53144. }
  53145. }
  53146. // cache key
  53147. /**
  53148. * Returns `true` if the render pipeline requires an update.
  53149. *
  53150. * @param {RenderObject} renderObject - The render object.
  53151. * @return {boolean} Whether the render pipeline requires an update or not.
  53152. */
  53153. needsRenderUpdate( renderObject ) {
  53154. const data = this.get( renderObject );
  53155. const { object, material } = renderObject;
  53156. const utils = this.utils;
  53157. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  53158. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  53159. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  53160. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  53161. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  53162. let needsUpdate = false;
  53163. if ( data.material !== material || data.materialVersion !== material.version ||
  53164. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  53165. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  53166. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  53167. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  53168. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  53169. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  53170. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  53171. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  53172. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  53173. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  53174. data.primitiveTopology !== primitiveTopology ||
  53175. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  53176. ) {
  53177. data.material = material; data.materialVersion = material.version;
  53178. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  53179. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  53180. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  53181. data.colorWrite = material.colorWrite;
  53182. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  53183. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  53184. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  53185. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  53186. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  53187. data.sampleCount = sampleCount;
  53188. data.colorSpace = colorSpace;
  53189. data.colorFormat = colorFormat;
  53190. data.depthStencilFormat = depthStencilFormat;
  53191. data.primitiveTopology = primitiveTopology;
  53192. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  53193. needsUpdate = true;
  53194. }
  53195. return needsUpdate;
  53196. }
  53197. /**
  53198. * Returns a cache key that is used to identify render pipelines.
  53199. *
  53200. * @param {RenderObject} renderObject - The render object.
  53201. * @return {string} The cache key.
  53202. */
  53203. getRenderCacheKey( renderObject ) {
  53204. const { object, material } = renderObject;
  53205. const utils = this.utils;
  53206. const renderContext = renderObject.context;
  53207. // meshes with negative scale have a different frontFace render pipeline
  53208. // descriptor value so the following must be honored in the cache key
  53209. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  53210. return [
  53211. material.transparent, material.blending, material.premultipliedAlpha,
  53212. material.blendSrc, material.blendDst, material.blendEquation,
  53213. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  53214. material.colorWrite,
  53215. material.depthWrite, material.depthTest, material.depthFunc,
  53216. material.stencilWrite, material.stencilFunc,
  53217. material.stencilFail, material.stencilZFail, material.stencilZPass,
  53218. material.stencilFuncMask, material.stencilWriteMask,
  53219. material.side,
  53220. frontFaceCW,
  53221. utils.getSampleCountRenderContext( renderContext ),
  53222. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  53223. utils.getPrimitiveTopology( object, material ),
  53224. renderObject.getGeometryCacheKey(),
  53225. renderObject.clippingContextCacheKey
  53226. ].join();
  53227. }
  53228. // textures
  53229. /**
  53230. * Creates a GPU sampler for the given texture.
  53231. *
  53232. * @param {Texture} texture - The texture to create the sampler for.
  53233. */
  53234. createSampler( texture ) {
  53235. this.textureUtils.createSampler( texture );
  53236. }
  53237. /**
  53238. * Destroys the GPU sampler for the given texture.
  53239. *
  53240. * @param {Texture} texture - The texture to destroy the sampler for.
  53241. */
  53242. destroySampler( texture ) {
  53243. this.textureUtils.destroySampler( texture );
  53244. }
  53245. /**
  53246. * Creates a default texture for the given texture that can be used
  53247. * as a placeholder until the actual texture is ready for usage.
  53248. *
  53249. * @param {Texture} texture - The texture to create a default texture for.
  53250. */
  53251. createDefaultTexture( texture ) {
  53252. this.textureUtils.createDefaultTexture( texture );
  53253. }
  53254. /**
  53255. * Defines a texture on the GPU for the given texture object.
  53256. *
  53257. * @param {Texture} texture - The texture.
  53258. * @param {Object} [options={}] - Optional configuration parameter.
  53259. */
  53260. createTexture( texture, options ) {
  53261. this.textureUtils.createTexture( texture, options );
  53262. }
  53263. /**
  53264. * Uploads the updated texture data to the GPU.
  53265. *
  53266. * @param {Texture} texture - The texture.
  53267. * @param {Object} [options={}] - Optional configuration parameter.
  53268. */
  53269. updateTexture( texture, options ) {
  53270. this.textureUtils.updateTexture( texture, options );
  53271. }
  53272. /**
  53273. * Generates mipmaps for the given texture.
  53274. *
  53275. * @param {Texture} texture - The texture.
  53276. */
  53277. generateMipmaps( texture ) {
  53278. this.textureUtils.generateMipmaps( texture );
  53279. }
  53280. /**
  53281. * Destroys the GPU data for the given texture object.
  53282. *
  53283. * @param {Texture} texture - The texture.
  53284. */
  53285. destroyTexture( texture ) {
  53286. this.textureUtils.destroyTexture( texture );
  53287. }
  53288. /**
  53289. * Returns texture data as a typed array.
  53290. *
  53291. * @async
  53292. * @param {Texture} texture - The texture to copy.
  53293. * @param {number} x - The x coordinate of the copy origin.
  53294. * @param {number} y - The y coordinate of the copy origin.
  53295. * @param {number} width - The width of the copy.
  53296. * @param {number} height - The height of the copy.
  53297. * @param {number} faceIndex - The face index.
  53298. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  53299. */
  53300. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  53301. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  53302. }
  53303. /**
  53304. * Inits a time stamp query for the given render context.
  53305. *
  53306. * @param {string} type - The type of the timestamp query (e.g. 'render', 'compute').
  53307. * @param {number} uid - Unique id for the context (e.g. render context id).
  53308. * @param {Object} descriptor - The query descriptor.
  53309. */
  53310. initTimestampQuery( type, uid, descriptor ) {
  53311. if ( ! this.trackTimestamp ) return;
  53312. if ( ! this.timestampQueryPool[ type ] ) {
  53313. // TODO: Variable maxQueries?
  53314. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  53315. }
  53316. const timestampQueryPool = this.timestampQueryPool[ type ];
  53317. const baseOffset = timestampQueryPool.allocateQueriesForContext( uid );
  53318. descriptor.timestampWrites = {
  53319. querySet: timestampQueryPool.querySet,
  53320. beginningOfPassWriteIndex: baseOffset,
  53321. endOfPassWriteIndex: baseOffset + 1,
  53322. };
  53323. }
  53324. // node builder
  53325. /**
  53326. * Returns a node builder for the given render object.
  53327. *
  53328. * @param {RenderObject} object - The render object.
  53329. * @param {Renderer} renderer - The renderer.
  53330. * @return {WGSLNodeBuilder} The node builder.
  53331. */
  53332. createNodeBuilder( object, renderer ) {
  53333. return new WGSLNodeBuilder( object, renderer );
  53334. }
  53335. // program
  53336. /**
  53337. * Creates a shader program from the given programmable stage.
  53338. *
  53339. * @param {ProgrammableStage} program - The programmable stage.
  53340. */
  53341. createProgram( program ) {
  53342. const programGPU = this.get( program );
  53343. programGPU.module = {
  53344. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  53345. entryPoint: 'main'
  53346. };
  53347. }
  53348. /**
  53349. * Destroys the shader program of the given programmable stage.
  53350. *
  53351. * @param {ProgrammableStage} program - The programmable stage.
  53352. */
  53353. destroyProgram( program ) {
  53354. this.delete( program );
  53355. }
  53356. // pipelines
  53357. /**
  53358. * Creates a render pipeline for the given render object.
  53359. *
  53360. * @param {RenderObject} renderObject - The render object.
  53361. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  53362. */
  53363. createRenderPipeline( renderObject, promises ) {
  53364. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  53365. }
  53366. /**
  53367. * Creates a compute pipeline for the given compute node.
  53368. *
  53369. * @param {ComputePipeline} computePipeline - The compute pipeline.
  53370. * @param {Array<BindGroup>} bindings - The bindings.
  53371. */
  53372. createComputePipeline( computePipeline, bindings ) {
  53373. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  53374. }
  53375. /**
  53376. * Prepares the state for encoding render bundles.
  53377. *
  53378. * @param {RenderContext} renderContext - The render context.
  53379. */
  53380. beginBundle( renderContext ) {
  53381. const renderContextData = this.get( renderContext );
  53382. renderContextData._currentPass = renderContextData.currentPass;
  53383. renderContextData._currentSets = renderContextData.currentSets;
  53384. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  53385. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  53386. }
  53387. /**
  53388. * After processing render bundles this method finalizes related work.
  53389. *
  53390. * @param {RenderContext} renderContext - The render context.
  53391. * @param {RenderBundle} bundle - The render bundle.
  53392. */
  53393. finishBundle( renderContext, bundle ) {
  53394. const renderContextData = this.get( renderContext );
  53395. const bundleEncoder = renderContextData.currentPass;
  53396. const bundleGPU = bundleEncoder.finish();
  53397. this.get( bundle ).bundleGPU = bundleGPU;
  53398. // restore render pass state
  53399. renderContextData.currentSets = renderContextData._currentSets;
  53400. renderContextData.currentPass = renderContextData._currentPass;
  53401. }
  53402. /**
  53403. * Adds a render bundle to the render context data.
  53404. *
  53405. * @param {RenderContext} renderContext - The render context.
  53406. * @param {RenderBundle} bundle - The render bundle to add.
  53407. */
  53408. addBundle( renderContext, bundle ) {
  53409. const renderContextData = this.get( renderContext );
  53410. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  53411. }
  53412. // bindings
  53413. /**
  53414. * Creates bindings from the given bind group definition.
  53415. *
  53416. * @param {BindGroup} bindGroup - The bind group.
  53417. * @param {Array<BindGroup>} bindings - Array of bind groups.
  53418. * @param {number} cacheIndex - The cache index.
  53419. * @param {number} version - The version.
  53420. */
  53421. createBindings( bindGroup, bindings, cacheIndex, version ) {
  53422. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  53423. }
  53424. /**
  53425. * Updates the given bind group definition.
  53426. *
  53427. * @param {BindGroup} bindGroup - The bind group.
  53428. * @param {Array<BindGroup>} bindings - Array of bind groups.
  53429. * @param {number} cacheIndex - The cache index.
  53430. * @param {number} version - The version.
  53431. */
  53432. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  53433. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  53434. }
  53435. /**
  53436. * Updates a buffer binding.
  53437. *
  53438. * @param {Buffer} binding - The buffer binding to update.
  53439. */
  53440. updateBinding( binding ) {
  53441. this.bindingUtils.updateBinding( binding );
  53442. }
  53443. // attributes
  53444. /**
  53445. * Creates the buffer of an indexed shader attribute.
  53446. *
  53447. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  53448. */
  53449. createIndexAttribute( attribute ) {
  53450. let usage = GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST;
  53451. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  53452. usage |= GPUBufferUsage.STORAGE;
  53453. }
  53454. this.attributeUtils.createAttribute( attribute, usage );
  53455. }
  53456. /**
  53457. * Creates the GPU buffer of a shader attribute.
  53458. *
  53459. * @param {BufferAttribute} attribute - The buffer attribute.
  53460. */
  53461. createAttribute( attribute ) {
  53462. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  53463. }
  53464. /**
  53465. * Creates the GPU buffer of a storage attribute.
  53466. *
  53467. * @param {BufferAttribute} attribute - The buffer attribute.
  53468. */
  53469. createStorageAttribute( attribute ) {
  53470. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  53471. }
  53472. /**
  53473. * Creates the GPU buffer of an indirect storage attribute.
  53474. *
  53475. * @param {BufferAttribute} attribute - The buffer attribute.
  53476. */
  53477. createIndirectStorageAttribute( attribute ) {
  53478. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  53479. }
  53480. /**
  53481. * Updates the GPU buffer of a shader attribute.
  53482. *
  53483. * @param {BufferAttribute} attribute - The buffer attribute to update.
  53484. */
  53485. updateAttribute( attribute ) {
  53486. this.attributeUtils.updateAttribute( attribute );
  53487. }
  53488. /**
  53489. * Destroys the GPU buffer of a shader attribute.
  53490. *
  53491. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  53492. */
  53493. destroyAttribute( attribute ) {
  53494. this.attributeUtils.destroyAttribute( attribute );
  53495. }
  53496. // canvas
  53497. /**
  53498. * Triggers an update of the default render pass descriptor.
  53499. */
  53500. updateSize() {
  53501. this.colorBuffer = this.textureUtils.getColorBuffer();
  53502. this.defaultRenderPassdescriptor = null;
  53503. }
  53504. // utils public
  53505. /**
  53506. * Returns the maximum anisotropy texture filtering value.
  53507. *
  53508. * @return {number} The maximum anisotropy texture filtering value.
  53509. */
  53510. getMaxAnisotropy() {
  53511. return 16;
  53512. }
  53513. /**
  53514. * Checks if the given feature is supported by the backend.
  53515. *
  53516. * @param {string} name - The feature's name.
  53517. * @return {boolean} Whether the feature is supported or not.
  53518. */
  53519. hasFeature( name ) {
  53520. return this.device.features.has( name );
  53521. }
  53522. /**
  53523. * Copies data of the given source texture to the given destination texture.
  53524. *
  53525. * @param {Texture} srcTexture - The source texture.
  53526. * @param {Texture} dstTexture - The destination texture.
  53527. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  53528. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  53529. * @param {number} [srcLevel=0] - The mipmap level to copy.
  53530. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  53531. */
  53532. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  53533. let dstX = 0;
  53534. let dstY = 0;
  53535. let dstZ = 0;
  53536. let srcX = 0;
  53537. let srcY = 0;
  53538. let srcZ = 0;
  53539. let srcWidth = srcTexture.image.width;
  53540. let srcHeight = srcTexture.image.height;
  53541. let srcDepth = 1;
  53542. if ( srcRegion !== null ) {
  53543. if ( srcRegion.isBox3 === true ) {
  53544. srcX = srcRegion.min.x;
  53545. srcY = srcRegion.min.y;
  53546. srcZ = srcRegion.min.z;
  53547. srcWidth = srcRegion.max.x - srcRegion.min.x;
  53548. srcHeight = srcRegion.max.y - srcRegion.min.y;
  53549. srcDepth = srcRegion.max.z - srcRegion.min.z;
  53550. } else {
  53551. // Assume it's a Box2
  53552. srcX = srcRegion.min.x;
  53553. srcY = srcRegion.min.y;
  53554. srcWidth = srcRegion.max.x - srcRegion.min.x;
  53555. srcHeight = srcRegion.max.y - srcRegion.min.y;
  53556. srcDepth = 1;
  53557. }
  53558. }
  53559. if ( dstPosition !== null ) {
  53560. dstX = dstPosition.x;
  53561. dstY = dstPosition.y;
  53562. dstZ = dstPosition.z || 0;
  53563. }
  53564. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  53565. const sourceGPU = this.get( srcTexture ).texture;
  53566. const destinationGPU = this.get( dstTexture ).texture;
  53567. encoder.copyTextureToTexture(
  53568. {
  53569. texture: sourceGPU,
  53570. mipLevel: srcLevel,
  53571. origin: { x: srcX, y: srcY, z: srcZ }
  53572. },
  53573. {
  53574. texture: destinationGPU,
  53575. mipLevel: dstLevel,
  53576. origin: { x: dstX, y: dstY, z: dstZ }
  53577. },
  53578. [
  53579. srcWidth,
  53580. srcHeight,
  53581. srcDepth
  53582. ]
  53583. );
  53584. this.device.queue.submit( [ encoder.finish() ] );
  53585. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  53586. this.textureUtils.generateMipmaps( dstTexture );
  53587. }
  53588. }
  53589. /**
  53590. * Copies the current bound framebuffer to the given texture.
  53591. *
  53592. * @param {Texture} texture - The destination texture.
  53593. * @param {RenderContext} renderContext - The render context.
  53594. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  53595. */
  53596. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  53597. const renderContextData = this.get( renderContext );
  53598. let sourceGPU = null;
  53599. if ( renderContext.renderTarget ) {
  53600. if ( texture.isDepthTexture ) {
  53601. sourceGPU = this.get( renderContext.depthTexture ).texture;
  53602. } else {
  53603. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  53604. }
  53605. } else {
  53606. if ( texture.isDepthTexture ) {
  53607. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  53608. } else {
  53609. sourceGPU = this.context.getCurrentTexture();
  53610. }
  53611. }
  53612. const destinationGPU = this.get( texture ).texture;
  53613. if ( sourceGPU.format !== destinationGPU.format ) {
  53614. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  53615. return;
  53616. }
  53617. let encoder;
  53618. if ( renderContextData.currentPass ) {
  53619. renderContextData.currentPass.end();
  53620. encoder = renderContextData.encoder;
  53621. } else {
  53622. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  53623. }
  53624. encoder.copyTextureToTexture(
  53625. {
  53626. texture: sourceGPU,
  53627. origin: [ rectangle.x, rectangle.y, 0 ],
  53628. },
  53629. {
  53630. texture: destinationGPU
  53631. },
  53632. [
  53633. rectangle.z,
  53634. rectangle.w
  53635. ]
  53636. );
  53637. if ( renderContextData.currentPass ) {
  53638. const { descriptor } = renderContextData;
  53639. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  53640. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  53641. }
  53642. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  53643. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  53644. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  53645. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  53646. if ( renderContext.viewport ) {
  53647. this.updateViewport( renderContext );
  53648. }
  53649. if ( renderContext.scissor ) {
  53650. const { x, y, width, height } = renderContext.scissorValue;
  53651. renderContextData.currentPass.setScissorRect( x, y, width, height );
  53652. }
  53653. } else {
  53654. this.device.queue.submit( [ encoder.finish() ] );
  53655. }
  53656. if ( texture.generateMipmaps ) {
  53657. this.textureUtils.generateMipmaps( texture );
  53658. }
  53659. }
  53660. }
  53661. /**
  53662. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  53663. *
  53664. * @augments SpotLight
  53665. */
  53666. class IESSpotLight extends SpotLight {
  53667. /**
  53668. * Constructs a new IES spot light.
  53669. *
  53670. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  53671. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  53672. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  53673. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  53674. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  53675. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  53676. */
  53677. constructor( color, intensity, distance, angle, penumbra, decay ) {
  53678. super( color, intensity, distance, angle, penumbra, decay );
  53679. /**
  53680. * TODO
  53681. *
  53682. * @type {?Texture}
  53683. * @default null
  53684. */
  53685. this.iesMap = null;
  53686. }
  53687. copy( source, recursive ) {
  53688. super.copy( source, recursive );
  53689. this.iesMap = source.iesMap;
  53690. return this;
  53691. }
  53692. }
  53693. /**
  53694. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  53695. *
  53696. * @augments SpotLight
  53697. */
  53698. class ProjectorLight extends SpotLight {
  53699. /**
  53700. * Constructs a new projector light.
  53701. *
  53702. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  53703. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  53704. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  53705. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  53706. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  53707. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  53708. */
  53709. constructor( color, intensity, distance, angle, penumbra, decay ) {
  53710. super( color, intensity, distance, angle, penumbra, decay );
  53711. /**
  53712. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  53713. *
  53714. * @type {?number}
  53715. * @default null
  53716. */
  53717. this.aspect = null;
  53718. }
  53719. copy( source, recursive ) {
  53720. super.copy( source, recursive );
  53721. this.aspect = source.aspect;
  53722. return this;
  53723. }
  53724. }
  53725. /**
  53726. * This version of a node library represents a basic version
  53727. * just focusing on lights and tone mapping techniques.
  53728. *
  53729. * @private
  53730. * @augments NodeLibrary
  53731. */
  53732. class BasicNodeLibrary extends NodeLibrary {
  53733. /**
  53734. * Constructs a new basic node library.
  53735. */
  53736. constructor() {
  53737. super();
  53738. this.addLight( PointLightNode, PointLight );
  53739. this.addLight( DirectionalLightNode, DirectionalLight );
  53740. this.addLight( RectAreaLightNode, RectAreaLight );
  53741. this.addLight( SpotLightNode, SpotLight );
  53742. this.addLight( AmbientLightNode, AmbientLight );
  53743. this.addLight( HemisphereLightNode, HemisphereLight );
  53744. this.addLight( LightProbeNode, LightProbe );
  53745. this.addLight( IESSpotLightNode, IESSpotLight );
  53746. this.addLight( ProjectorLightNode, ProjectorLight );
  53747. this.addToneMapping( linearToneMapping, LinearToneMapping );
  53748. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  53749. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  53750. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  53751. this.addToneMapping( agxToneMapping, AgXToneMapping );
  53752. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  53753. }
  53754. }
  53755. /**
  53756. * This alternative version of {@link WebGPURenderer} only supports node materials.
  53757. * So classes like `MeshBasicMaterial` are not compatible.
  53758. *
  53759. * @private
  53760. * @augments Renderer
  53761. */
  53762. class WebGPURenderer extends Renderer {
  53763. /**
  53764. * Constructs a new WebGPU renderer.
  53765. *
  53766. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  53767. */
  53768. constructor( parameters = {} ) {
  53769. let BackendClass;
  53770. if ( parameters.forceWebGL ) {
  53771. BackendClass = WebGLBackend;
  53772. } else {
  53773. BackendClass = WebGPUBackend;
  53774. parameters.getFallback = () => {
  53775. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  53776. return new WebGLBackend( parameters );
  53777. };
  53778. }
  53779. const backend = new BackendClass( parameters );
  53780. super( backend, parameters );
  53781. /**
  53782. * The generic default value is overwritten with the
  53783. * standard node library for type mapping. Material
  53784. * mapping is not supported with this version.
  53785. *
  53786. * @type {BasicNodeLibrary}
  53787. */
  53788. this.library = new BasicNodeLibrary();
  53789. /**
  53790. * This flag can be used for type testing.
  53791. *
  53792. * @type {boolean}
  53793. * @readonly
  53794. * @default true
  53795. */
  53796. this.isWebGPURenderer = true;
  53797. }
  53798. }
  53799. /**
  53800. * A specialized group which enables applications access to the
  53801. * Render Bundle API of WebGPU. The group with all its descendant nodes
  53802. * are considered as one render bundle and processed as such by
  53803. * the renderer.
  53804. *
  53805. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  53806. * With a WebGL backend, the group can technically be rendered but without
  53807. * any performance improvements.
  53808. *
  53809. * @augments Group
  53810. */
  53811. class BundleGroup extends Group {
  53812. /**
  53813. * Constructs a new bundle group.
  53814. */
  53815. constructor() {
  53816. super();
  53817. /**
  53818. * This flag can be used for type testing.
  53819. *
  53820. * @type {boolean}
  53821. * @readonly
  53822. * @default true
  53823. */
  53824. this.isBundleGroup = true;
  53825. /**
  53826. * This property is only relevant for detecting types
  53827. * during serialization/deserialization. It should always
  53828. * match the class name.
  53829. *
  53830. * @type {string}
  53831. * @readonly
  53832. * @default 'BundleGroup'
  53833. */
  53834. this.type = 'BundleGroup';
  53835. /**
  53836. * Whether the bundle is static or not. When set to `true`, the structure
  53837. * is assumed to be static and does not change. E.g. no new objects are
  53838. * added to the group
  53839. *
  53840. * If a change is required, an update can still be forced by setting the
  53841. * `needsUpdate` flag to `true`.
  53842. *
  53843. * @type {boolean}
  53844. * @default true
  53845. */
  53846. this.static = true;
  53847. /**
  53848. * The bundle group's version.
  53849. *
  53850. * @type {number}
  53851. * @readonly
  53852. * @default 0
  53853. */
  53854. this.version = 0;
  53855. }
  53856. /**
  53857. * Set this property to `true` when the bundle group has changed.
  53858. *
  53859. * @type {boolean}
  53860. * @default false
  53861. * @param {boolean} value
  53862. */
  53863. set needsUpdate( value ) {
  53864. if ( value === true ) this.version ++;
  53865. }
  53866. }
  53867. /**
  53868. * This module is responsible to manage the post processing setups in apps.
  53869. * You usually create a single instance of this class and use it to define
  53870. * the output of your post processing effect chain.
  53871. * ```js
  53872. * const postProcessing = new PostProcessing( renderer );
  53873. *
  53874. * const scenePass = pass( scene, camera );
  53875. *
  53876. * postProcessing.outputNode = scenePass;
  53877. * ```
  53878. *
  53879. * Note: This module can only be used with `WebGPURenderer`.
  53880. */
  53881. class PostProcessing {
  53882. /**
  53883. * Constructs a new post processing management module.
  53884. *
  53885. * @param {Renderer} renderer - A reference to the renderer.
  53886. * @param {Node<vec4>} outputNode - An optional output node.
  53887. */
  53888. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  53889. /**
  53890. * A reference to the renderer.
  53891. *
  53892. * @type {Renderer}
  53893. */
  53894. this.renderer = renderer;
  53895. /**
  53896. * A node which defines the final output of the post
  53897. * processing. This is usually the last node in a chain
  53898. * of effect nodes.
  53899. *
  53900. * @type {Node<vec4>}
  53901. */
  53902. this.outputNode = outputNode;
  53903. /**
  53904. * Whether the default output tone mapping and color
  53905. * space transformation should be enabled or not.
  53906. *
  53907. * It is enabled by default by it must be disabled when
  53908. * effects must be executed after tone mapping and color
  53909. * space conversion. A typical example is FXAA which
  53910. * requires sRGB input.
  53911. *
  53912. * When set to `false`, the app must control the output
  53913. * transformation with `RenderOutputNode`.
  53914. *
  53915. * ```js
  53916. * const outputPass = renderOutput( scenePass );
  53917. * ```
  53918. *
  53919. * @type {boolean}
  53920. */
  53921. this.outputColorTransform = true;
  53922. /**
  53923. * Must be set to `true` when the output node changes.
  53924. *
  53925. * @type {Node<vec4>}
  53926. */
  53927. this.needsUpdate = true;
  53928. const material = new NodeMaterial();
  53929. material.name = 'PostProcessing';
  53930. /**
  53931. * The full screen quad that is used to render
  53932. * the effects.
  53933. *
  53934. * @private
  53935. * @type {QuadMesh}
  53936. */
  53937. this._quadMesh = new QuadMesh( material );
  53938. /**
  53939. * The context of the post processing stack.
  53940. *
  53941. * @private
  53942. * @type {?Object}
  53943. * @default null
  53944. */
  53945. this._context = null;
  53946. }
  53947. /**
  53948. * When `PostProcessing` is used to apply post processing effects,
  53949. * the application must use this version of `render()` inside
  53950. * its animation loop (not the one from the renderer).
  53951. */
  53952. render() {
  53953. const renderer = this.renderer;
  53954. this._update();
  53955. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  53956. const toneMapping = renderer.toneMapping;
  53957. const outputColorSpace = renderer.outputColorSpace;
  53958. renderer.toneMapping = NoToneMapping;
  53959. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  53960. //
  53961. const currentXR = renderer.xr.enabled;
  53962. renderer.xr.enabled = false;
  53963. this._quadMesh.render( renderer );
  53964. renderer.xr.enabled = currentXR;
  53965. //
  53966. renderer.toneMapping = toneMapping;
  53967. renderer.outputColorSpace = outputColorSpace;
  53968. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  53969. }
  53970. /**
  53971. * Returns the current context of the post processing stack.
  53972. *
  53973. * @readonly
  53974. * @type {?Object}
  53975. */
  53976. get context() {
  53977. return this._context;
  53978. }
  53979. /**
  53980. * Frees internal resources.
  53981. */
  53982. dispose() {
  53983. this._quadMesh.material.dispose();
  53984. }
  53985. /**
  53986. * Updates the state of the module.
  53987. *
  53988. * @private
  53989. */
  53990. _update() {
  53991. if ( this.needsUpdate === true ) {
  53992. const renderer = this.renderer;
  53993. const toneMapping = renderer.toneMapping;
  53994. const outputColorSpace = renderer.outputColorSpace;
  53995. const context = {
  53996. postProcessing: this,
  53997. onBeforePostProcessing: null,
  53998. onAfterPostProcessing: null
  53999. };
  54000. let outputNode = this.outputNode;
  54001. if ( this.outputColorTransform === true ) {
  54002. outputNode = outputNode.context( context );
  54003. outputNode = renderOutput( outputNode, toneMapping, outputColorSpace );
  54004. } else {
  54005. context.toneMapping = toneMapping;
  54006. context.outputColorSpace = outputColorSpace;
  54007. outputNode = outputNode.context( context );
  54008. }
  54009. this._context = context;
  54010. this._quadMesh.material.fragmentNode = outputNode;
  54011. this._quadMesh.material.needsUpdate = true;
  54012. this.needsUpdate = false;
  54013. }
  54014. }
  54015. /**
  54016. * When `PostProcessing` is used to apply post processing effects,
  54017. * the application must use this version of `renderAsync()` inside
  54018. * its animation loop (not the one from the renderer).
  54019. *
  54020. * @async
  54021. * @return {Promise} A Promise that resolves when the render has been finished.
  54022. */
  54023. async renderAsync() {
  54024. this._update();
  54025. if ( this._context.onBeforePostProcessing !== null ) this._context.onBeforePostProcessing();
  54026. const renderer = this.renderer;
  54027. const toneMapping = renderer.toneMapping;
  54028. const outputColorSpace = renderer.outputColorSpace;
  54029. renderer.toneMapping = NoToneMapping;
  54030. renderer.outputColorSpace = ColorManagement.workingColorSpace;
  54031. //
  54032. const currentXR = renderer.xr.enabled;
  54033. renderer.xr.enabled = false;
  54034. await this._quadMesh.renderAsync( renderer );
  54035. renderer.xr.enabled = currentXR;
  54036. //
  54037. renderer.toneMapping = toneMapping;
  54038. renderer.outputColorSpace = outputColorSpace;
  54039. if ( this._context.onAfterPostProcessing !== null ) this._context.onAfterPostProcessing();
  54040. }
  54041. }
  54042. /**
  54043. * This special type of texture is intended for compute shaders.
  54044. * It can be used to compute the data of a texture with a compute shader.
  54045. *
  54046. * Note: This type of texture can only be used with `WebGPURenderer`
  54047. * and a WebGPU backend.
  54048. *
  54049. * @augments Texture
  54050. */
  54051. class StorageTexture extends Texture {
  54052. /**
  54053. * Constructs a new storage texture.
  54054. *
  54055. * @param {number} [width=1] - The storage texture's width.
  54056. * @param {number} [height=1] - The storage texture's height.
  54057. */
  54058. constructor( width = 1, height = 1 ) {
  54059. super();
  54060. /**
  54061. * The image object which just represents the texture's dimension.
  54062. *
  54063. * @type {{width: number, height: number}}
  54064. */
  54065. this.image = { width, height };
  54066. /**
  54067. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  54068. *
  54069. * @type {number}
  54070. */
  54071. this.magFilter = LinearFilter;
  54072. /**
  54073. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  54074. *
  54075. * @type {number}
  54076. */
  54077. this.minFilter = LinearFilter;
  54078. /**
  54079. * This flag can be used for type testing.
  54080. *
  54081. * @type {boolean}
  54082. * @readonly
  54083. * @default true
  54084. */
  54085. this.isStorageTexture = true;
  54086. }
  54087. /**
  54088. * Sets the size of the storage texture.
  54089. *
  54090. * @param {number} width - The new width of the storage texture.
  54091. * @param {number} height - The new height of the storage texture.
  54092. */
  54093. setSize( width, height ) {
  54094. if ( this.image.width !== width || this.image.height !== height ) {
  54095. this.image.width = width;
  54096. this.image.height = height;
  54097. this.dispose();
  54098. }
  54099. }
  54100. }
  54101. /**
  54102. * This special type of buffer attribute is intended for compute shaders.
  54103. * It can be used to encode draw parameters for indirect draw calls.
  54104. *
  54105. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  54106. * and a WebGPU backend.
  54107. *
  54108. * @augments StorageBufferAttribute
  54109. */
  54110. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  54111. /**
  54112. * Constructs a new storage buffer attribute.
  54113. *
  54114. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  54115. * The subsequent parameter is then obsolete.
  54116. * @param {number} itemSize - The item size.
  54117. */
  54118. constructor( count, itemSize ) {
  54119. super( count, itemSize, Uint32Array );
  54120. /**
  54121. * This flag can be used for type testing.
  54122. *
  54123. * @type {boolean}
  54124. * @readonly
  54125. * @default true
  54126. */
  54127. this.isIndirectStorageBufferAttribute = true;
  54128. }
  54129. }
  54130. /**
  54131. * A loader for loading node objects in the three.js JSON Object/Scene format.
  54132. *
  54133. * @augments Loader
  54134. */
  54135. class NodeLoader extends Loader {
  54136. /**
  54137. * Constructs a new node loader.
  54138. *
  54139. * @param {LoadingManager} [manager] - A reference to a loading manager.
  54140. */
  54141. constructor( manager ) {
  54142. super( manager );
  54143. /**
  54144. * Represents a dictionary of textures.
  54145. *
  54146. * @type {Object<string,Texture>}
  54147. */
  54148. this.textures = {};
  54149. /**
  54150. * Represents a dictionary of node types.
  54151. *
  54152. * @type {Object<string,Node.constructor>}
  54153. */
  54154. this.nodes = {};
  54155. }
  54156. /**
  54157. * Loads the node definitions from the given URL.
  54158. *
  54159. * @param {string} url - The path/URL of the file to be loaded.
  54160. * @param {Function} onLoad - Will be called when load completes.
  54161. * @param {Function} onProgress - Will be called while load progresses.
  54162. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  54163. */
  54164. load( url, onLoad, onProgress, onError ) {
  54165. const loader = new FileLoader( this.manager );
  54166. loader.setPath( this.path );
  54167. loader.setRequestHeader( this.requestHeader );
  54168. loader.setWithCredentials( this.withCredentials );
  54169. loader.load( url, ( text ) => {
  54170. try {
  54171. onLoad( this.parse( JSON.parse( text ) ) );
  54172. } catch ( e ) {
  54173. if ( onError ) {
  54174. onError( e );
  54175. } else {
  54176. console.error( e );
  54177. }
  54178. this.manager.itemError( url );
  54179. }
  54180. }, onProgress, onError );
  54181. }
  54182. /**
  54183. * Parse the node dependencies for the loaded node.
  54184. *
  54185. * @param {Array<Object>} [json] - The JSON definition
  54186. * @return {Object<string,Node>} A dictionary with node dependencies.
  54187. */
  54188. parseNodes( json ) {
  54189. const nodes = {};
  54190. if ( json !== undefined ) {
  54191. for ( const nodeJSON of json ) {
  54192. const { uuid, type } = nodeJSON;
  54193. nodes[ uuid ] = this.createNodeFromType( type );
  54194. nodes[ uuid ].uuid = uuid;
  54195. }
  54196. const meta = { nodes, textures: this.textures };
  54197. for ( const nodeJSON of json ) {
  54198. nodeJSON.meta = meta;
  54199. const node = nodes[ nodeJSON.uuid ];
  54200. node.deserialize( nodeJSON );
  54201. delete nodeJSON.meta;
  54202. }
  54203. }
  54204. return nodes;
  54205. }
  54206. /**
  54207. * Parses the node from the given JSON.
  54208. *
  54209. * @param {Object} json - The JSON definition
  54210. * @param {string} json.type - The node type.
  54211. * @param {string} json.uuid - The node UUID.
  54212. * @param {Array<Object>} [json.nodes] - The node dependencies.
  54213. * @param {Object} [json.meta] - The meta data.
  54214. * @return {Node} The parsed node.
  54215. */
  54216. parse( json ) {
  54217. const node = this.createNodeFromType( json.type );
  54218. node.uuid = json.uuid;
  54219. const nodes = this.parseNodes( json.nodes );
  54220. const meta = { nodes, textures: this.textures };
  54221. json.meta = meta;
  54222. node.deserialize( json );
  54223. delete json.meta;
  54224. return node;
  54225. }
  54226. /**
  54227. * Defines the dictionary of textures.
  54228. *
  54229. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  54230. * @return {NodeLoader} A reference to this loader.
  54231. */
  54232. setTextures( value ) {
  54233. this.textures = value;
  54234. return this;
  54235. }
  54236. /**
  54237. * Defines the dictionary of node types.
  54238. *
  54239. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  54240. * @return {NodeLoader} A reference to this loader.
  54241. */
  54242. setNodes( value ) {
  54243. this.nodes = value;
  54244. return this;
  54245. }
  54246. /**
  54247. * Creates a node object from the given type.
  54248. *
  54249. * @param {string} type - The node type.
  54250. * @return {Node} The created node instance.
  54251. */
  54252. createNodeFromType( type ) {
  54253. if ( this.nodes[ type ] === undefined ) {
  54254. console.error( 'THREE.NodeLoader: Node type not found:', type );
  54255. return float();
  54256. }
  54257. return nodeObject( new this.nodes[ type ]() );
  54258. }
  54259. }
  54260. /**
  54261. * A special type of material loader for loading node materials.
  54262. *
  54263. * @augments MaterialLoader
  54264. */
  54265. class NodeMaterialLoader extends MaterialLoader {
  54266. /**
  54267. * Constructs a new node material loader.
  54268. *
  54269. * @param {LoadingManager} [manager] - A reference to a loading manager.
  54270. */
  54271. constructor( manager ) {
  54272. super( manager );
  54273. /**
  54274. * Represents a dictionary of node types.
  54275. *
  54276. * @type {Object<string,Node.constructor>}
  54277. */
  54278. this.nodes = {};
  54279. /**
  54280. * Represents a dictionary of node material types.
  54281. *
  54282. * @type {Object<string,NodeMaterial.constructor>}
  54283. */
  54284. this.nodeMaterials = {};
  54285. }
  54286. /**
  54287. * Parses the node material from the given JSON.
  54288. *
  54289. * @param {Object} json - The JSON definition
  54290. * @return {NodeMaterial}. The parsed material.
  54291. */
  54292. parse( json ) {
  54293. const material = super.parse( json );
  54294. const nodes = this.nodes;
  54295. const inputNodes = json.inputNodes;
  54296. for ( const property in inputNodes ) {
  54297. const uuid = inputNodes[ property ];
  54298. material[ property ] = nodes[ uuid ];
  54299. }
  54300. return material;
  54301. }
  54302. /**
  54303. * Defines the dictionary of node types.
  54304. *
  54305. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  54306. * @return {NodeLoader} A reference to this loader.
  54307. */
  54308. setNodes( value ) {
  54309. this.nodes = value;
  54310. return this;
  54311. }
  54312. /**
  54313. * Defines the dictionary of node material types.
  54314. *
  54315. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  54316. * @return {NodeLoader} A reference to this loader.
  54317. */
  54318. setNodeMaterials( value ) {
  54319. this.nodeMaterials = value;
  54320. return this;
  54321. }
  54322. /**
  54323. * Creates a node material from the given type.
  54324. *
  54325. * @param {string} type - The node material type.
  54326. * @return {Node} The created node material instance.
  54327. */
  54328. createMaterialFromType( type ) {
  54329. const materialClass = this.nodeMaterials[ type ];
  54330. if ( materialClass !== undefined ) {
  54331. return new materialClass();
  54332. }
  54333. return super.createMaterialFromType( type );
  54334. }
  54335. }
  54336. /**
  54337. * A special type of object loader for loading 3D objects using
  54338. * node materials.
  54339. *
  54340. * @augments ObjectLoader
  54341. */
  54342. class NodeObjectLoader extends ObjectLoader {
  54343. /**
  54344. * Constructs a new node object loader.
  54345. *
  54346. * @param {LoadingManager} [manager] - A reference to a loading manager.
  54347. */
  54348. constructor( manager ) {
  54349. super( manager );
  54350. /**
  54351. * Represents a dictionary of node types.
  54352. *
  54353. * @type {Object<string,Node.constructor>}
  54354. */
  54355. this.nodes = {};
  54356. /**
  54357. * Represents a dictionary of node material types.
  54358. *
  54359. * @type {Object<string,NodeMaterial.constructor>}
  54360. */
  54361. this.nodeMaterials = {};
  54362. /**
  54363. * A reference to hold the `nodes` JSON property.
  54364. *
  54365. * @private
  54366. * @type {?Object[]}
  54367. */
  54368. this._nodesJSON = null;
  54369. }
  54370. /**
  54371. * Defines the dictionary of node types.
  54372. *
  54373. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  54374. * @return {NodeObjectLoader} A reference to this loader.
  54375. */
  54376. setNodes( value ) {
  54377. this.nodes = value;
  54378. return this;
  54379. }
  54380. /**
  54381. * Defines the dictionary of node material types.
  54382. *
  54383. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  54384. * @return {NodeObjectLoader} A reference to this loader.
  54385. */
  54386. setNodeMaterials( value ) {
  54387. this.nodeMaterials = value;
  54388. return this;
  54389. }
  54390. /**
  54391. * Parses the node objects from the given JSON.
  54392. *
  54393. * @param {Object} json - The JSON definition
  54394. * @param {Function} onLoad - The onLoad callback function.
  54395. * @return {Object3D}. The parsed 3D object.
  54396. */
  54397. parse( json, onLoad ) {
  54398. this._nodesJSON = json.nodes;
  54399. const data = super.parse( json, onLoad );
  54400. this._nodesJSON = null; // dispose
  54401. return data;
  54402. }
  54403. /**
  54404. * Parses the node objects from the given JSON and textures.
  54405. *
  54406. * @param {Object[]} json - The JSON definition
  54407. * @param {Object<string,Texture>} textures - The texture library.
  54408. * @return {Object<string,Node>}. The parsed nodes.
  54409. */
  54410. parseNodes( json, textures ) {
  54411. if ( json !== undefined ) {
  54412. const loader = new NodeLoader();
  54413. loader.setNodes( this.nodes );
  54414. loader.setTextures( textures );
  54415. return loader.parseNodes( json );
  54416. }
  54417. return {};
  54418. }
  54419. /**
  54420. * Parses the node objects from the given JSON and textures.
  54421. *
  54422. * @param {Object} json - The JSON definition
  54423. * @param {Object<string,Texture>} textures - The texture library.
  54424. * @return {Object<string,NodeMaterial>}. The parsed materials.
  54425. */
  54426. parseMaterials( json, textures ) {
  54427. const materials = {};
  54428. if ( json !== undefined ) {
  54429. const nodes = this.parseNodes( this._nodesJSON, textures );
  54430. const loader = new NodeMaterialLoader();
  54431. loader.setTextures( textures );
  54432. loader.setNodes( nodes );
  54433. loader.setNodeMaterials( this.nodeMaterials );
  54434. for ( let i = 0, l = json.length; i < l; i ++ ) {
  54435. const data = json[ i ];
  54436. materials[ data.uuid ] = loader.parse( data );
  54437. }
  54438. }
  54439. return materials;
  54440. }
  54441. }
  54442. /**
  54443. * In earlier three.js versions, clipping was defined globally
  54444. * on the renderer or on material level. This special version of
  54445. * `THREE.Group` allows to encode the clipping state into the scene
  54446. * graph. Meaning if you create an instance of this group, all
  54447. * descendant 3D objects will be affected by the respective clipping
  54448. * planes.
  54449. *
  54450. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  54451. *
  54452. * @augments Group
  54453. */
  54454. class ClippingGroup extends Group {
  54455. /**
  54456. * Constructs a new clipping group.
  54457. */
  54458. constructor() {
  54459. super();
  54460. /**
  54461. * This flag can be used for type testing.
  54462. *
  54463. * @type {boolean}
  54464. * @readonly
  54465. * @default true
  54466. */
  54467. this.isClippingGroup = true;
  54468. /**
  54469. * An array with clipping planes.
  54470. *
  54471. * @type {Array<Plane>}
  54472. */
  54473. this.clippingPlanes = [];
  54474. /**
  54475. * Whether clipping should be enabled or not.
  54476. *
  54477. * @type {boolean}
  54478. * @default true
  54479. */
  54480. this.enabled = true;
  54481. /**
  54482. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  54483. *
  54484. * @type {boolean}
  54485. * @default false
  54486. */
  54487. this.clipIntersection = false;
  54488. /**
  54489. * Whether shadows should be clipped or not.
  54490. *
  54491. * @type {boolean}
  54492. * @default false
  54493. */
  54494. this.clipShadows = false;
  54495. }
  54496. }
  54497. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BitcastNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, 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, TimestampQuery, ToneMappingNode, ToonOutlinePassNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt101111Type, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号