three.webgpu.nodes.js 1.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623
  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, 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, DoubleSide, Camera, DepthStencilFormat, DepthFormat, UnsignedInt248Type, UnsignedByteType, Plane, Object3D, LinearMipMapLinearFilter, Float32BufferAttribute, UVMapping, VSMShadowMap, LessCompare, RGFormat, BasicShadowMap, SphereGeometry, LinearMipmapNearestFilter, NearestMipmapLinearFilter, Float16BufferAttribute, REVISION, ArrayCamera, PlaneGeometry, FrontSide, CustomBlending, AddEquation, ZeroFactor, CylinderGeometry, Quaternion, WebXRController, RAD2DEG, PCFShadowMap, FrustumArray, Frustum, DataTexture, RedIntegerFormat, RedFormat, ShortType, ByteType, UnsignedShortType, RGIntegerFormat, RGBIntegerFormat, RGBFormat, RGBAIntegerFormat, warnOnce, createCanvasElement, ReverseSubtractEquation, SubtractEquation, OneMinusDstAlphaFactor, OneMinusDstColorFactor, OneMinusSrcAlphaFactor, OneMinusSrcColorFactor, DstAlphaFactor, DstColorFactor, SrcAlphaSaturateFactor, SrcAlphaFactor, SrcColorFactor, OneFactor, CullFaceNone, CullFaceBack, CullFaceFront, MultiplyBlending, SubtractiveBlending, AdditiveBlending, NotEqualDepth, GreaterDepth, GreaterEqualDepth, EqualDepth, LessEqualDepth, LessDepth, AlwaysDepth, NeverDepth, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedInt5999Type, AlphaFormat, RGB_S3TC_DXT1_Format, RGBA_S3TC_DXT1_Format, RGBA_S3TC_DXT3_Format, RGBA_S3TC_DXT5_Format, RGB_PVRTC_4BPPV1_Format, RGB_PVRTC_2BPPV1_Format, RGBA_PVRTC_4BPPV1_Format, RGBA_PVRTC_2BPPV1_Format, RGB_ETC1_Format, RGB_ETC2_Format, RGBA_ETC2_EAC_Format, RGBA_ASTC_4x4_Format, RGBA_ASTC_5x4_Format, RGBA_ASTC_5x5_Format, RGBA_ASTC_6x5_Format, RGBA_ASTC_6x6_Format, RGBA_ASTC_8x5_Format, RGBA_ASTC_8x6_Format, RGBA_ASTC_8x8_Format, RGBA_ASTC_10x5_Format, RGBA_ASTC_10x6_Format, RGBA_ASTC_10x8_Format, RGBA_ASTC_10x10_Format, RGBA_ASTC_12x10_Format, RGBA_ASTC_12x12_Format, RGBA_BPTC_Format, RED_RGTC1_Format, SIGNED_RED_RGTC1_Format, RED_GREEN_RGTC2_Format, SIGNED_RED_GREEN_RGTC2_Format, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, NearestMipmapNearestFilter, NotEqualCompare, GreaterCompare, GreaterEqualCompare, EqualCompare, LessEqualCompare, AlwaysCompare, NeverCompare, LinearTransfer, NotEqualStencilFunc, GreaterStencilFunc, GreaterEqualStencilFunc, EqualStencilFunc, LessEqualStencilFunc, LessStencilFunc, AlwaysStencilFunc, NeverStencilFunc, DecrementWrapStencilOp, IncrementWrapStencilOp, DecrementStencilOp, IncrementStencilOp, InvertStencilOp, ReplaceStencilOp, ZeroStencilOp, KeepStencilOp, MaxEquation, MinEquation, SpotLight, PointLight, DirectionalLight, RectAreaLight, AmbientLight, HemisphereLight, LightProbe, LinearToneMapping, ReinhardToneMapping, CineonToneMapping, ACESFilmicToneMapping, AgXToneMapping, NeutralToneMapping, Group, Loader, FileLoader, MaterialLoader, ObjectLoader } from './three.core.js';
  7. export { AdditiveAnimationBlendMode, AnimationAction, AnimationClip, AnimationLoader, AnimationMixer, AnimationObjectGroup, AnimationUtils, ArcCurve, ArrowHelper, AttachedBindMode, Audio, AudioAnalyser, AudioContext, AudioListener, AudioLoader, AxesHelper, BasicDepthPacking, BatchedMesh, Bone, BooleanKeyframeTrack, Box2, Box3, Box3Helper, BoxHelper, BufferGeometryLoader, Cache, CameraHelper, CanvasTexture, CapsuleGeometry, CatmullRomCurve3, CircleGeometry, Clock, ColorKeyframeTrack, CompressedArrayTexture, CompressedCubeTexture, CompressedTexture, CompressedTextureLoader, ConeGeometry, ConstantAlphaFactor, ConstantColorFactor, Controls, CubeTextureLoader, CubicBezierCurve, CubicBezierCurve3, CubicInterpolant, CullFaceFrontBack, Curve, CurvePath, CustomToneMapping, Cylindrical, Data3DTexture, DataTextureLoader, DataUtils, DefaultLoadingManager, DetachedBindMode, DirectionalLightHelper, DiscreteInterpolant, DodecahedronGeometry, DynamicCopyUsage, DynamicReadUsage, EdgesGeometry, EllipseCurve, ExtrudeGeometry, Fog, FogExp2, GLBufferAttribute, GLSL1, GLSL3, GridHelper, HemisphereLightHelper, IcosahedronGeometry, ImageBitmapLoader, ImageLoader, ImageUtils, InstancedBufferGeometry, InstancedMesh, Int16BufferAttribute, Int32BufferAttribute, Int8BufferAttribute, Interpolant, InterpolateDiscrete, InterpolateLinear, InterpolateSmooth, InterpolationSamplingMode, InterpolationSamplingType, KeyframeTrack, LOD, LatheGeometry, Layers, Light, Line, Line3, LineCurve, LineCurve3, LineLoop, LineSegments, LinearInterpolant, LinearMipMapNearestFilter, LoaderUtils, LoadingManager, LoopOnce, LoopPingPong, LoopRepeat, MOUSE, MeshDepthMaterial, MeshDistanceMaterial, NearestMipMapLinearFilter, NearestMipMapNearestFilter, NormalAnimationBlendMode, NumberKeyframeTrack, OctahedronGeometry, OneMinusConstantAlphaFactor, OneMinusConstantColorFactor, PCFSoftShadowMap, Path, PlaneHelper, PointLightHelper, Points, PolarGridHelper, PolyhedronGeometry, PositionalAudio, PropertyBinding, PropertyMixer, QuadraticBezierCurve, QuadraticBezierCurve3, QuaternionKeyframeTrack, QuaternionLinearInterpolant, RGBADepthPacking, RGBDepthPacking, RGB_BPTC_SIGNED_Format, RGB_BPTC_UNSIGNED_Format, RGDepthPacking, RawShaderMaterial, Ray, Raycaster, RenderTarget3D, RingGeometry, ShaderMaterial, Shape, ShapeGeometry, ShapePath, ShapeUtils, Skeleton, SkeletonHelper, SkinnedMesh, Source, Spherical, SphericalHarmonics3, SplineCurve, SpotLightHelper, Sprite, StaticCopyUsage, StaticReadUsage, StereoCamera, StreamCopyUsage, StreamDrawUsage, StreamReadUsage, StringKeyframeTrack, TOUCH, TetrahedronGeometry, TextureLoader, TextureUtils, TimestampQuery, TorusGeometry, TorusKnotGeometry, Triangle, TriangleFanDrawMode, TriangleStripDrawMode, TrianglesDrawMode, TubeGeometry, Uint8BufferAttribute, Uint8ClampedBufferAttribute, Uniform, UniformsGroup, VectorKeyframeTrack, VideoFrameTexture, VideoTexture, WebGL3DRenderTarget, WebGLArrayRenderTarget, WebGLRenderTarget, WireframeGeometry, WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding } from './three.core.js';
  8. const refreshUniforms = [
  9. 'alphaMap',
  10. 'alphaTest',
  11. 'anisotropy',
  12. 'anisotropyMap',
  13. 'anisotropyRotation',
  14. 'aoMap',
  15. 'aoMapIntensity',
  16. 'attenuationColor',
  17. 'attenuationDistance',
  18. 'bumpMap',
  19. 'clearcoat',
  20. 'clearcoatMap',
  21. 'clearcoatNormalMap',
  22. 'clearcoatNormalScale',
  23. 'clearcoatRoughness',
  24. 'color',
  25. 'dispersion',
  26. 'displacementMap',
  27. 'emissive',
  28. 'emissiveIntensity',
  29. 'emissiveMap',
  30. 'envMap',
  31. 'envMapIntensity',
  32. 'gradientMap',
  33. 'ior',
  34. 'iridescence',
  35. 'iridescenceIOR',
  36. 'iridescenceMap',
  37. 'iridescenceThicknessMap',
  38. 'lightMap',
  39. 'lightMapIntensity',
  40. 'map',
  41. 'matcap',
  42. 'metalness',
  43. 'metalnessMap',
  44. 'normalMap',
  45. 'normalScale',
  46. 'opacity',
  47. 'roughness',
  48. 'roughnessMap',
  49. 'sheen',
  50. 'sheenColor',
  51. 'sheenColorMap',
  52. 'sheenRoughnessMap',
  53. 'shininess',
  54. 'specular',
  55. 'specularColor',
  56. 'specularColorMap',
  57. 'specularIntensity',
  58. 'specularIntensityMap',
  59. 'specularMap',
  60. 'thickness',
  61. 'transmission',
  62. 'transmissionMap'
  63. ];
  64. /**
  65. * This class is used by {@link WebGPURenderer} as management component.
  66. * It's primary purpose is to determine whether render objects require a
  67. * refresh right before they are going to be rendered or not.
  68. */
  69. class NodeMaterialObserver {
  70. /**
  71. * Constructs a new node material observer.
  72. *
  73. * @param {NodeBuilder} builder - The node builder.
  74. */
  75. constructor( builder ) {
  76. /**
  77. * A node material can be used by more than one render object so the
  78. * monitor must maintain a list of render objects.
  79. *
  80. * @type {WeakMap<RenderObject,Object>}
  81. */
  82. this.renderObjects = new WeakMap();
  83. /**
  84. * Whether the material uses node objects or not.
  85. *
  86. * @type {boolean}
  87. */
  88. this.hasNode = this.containsNode( builder );
  89. /**
  90. * Whether the node builder's 3D object is animated or not.
  91. *
  92. * @type {boolean}
  93. */
  94. this.hasAnimation = builder.object.isSkinnedMesh === true;
  95. /**
  96. * A list of all possible material uniforms
  97. *
  98. * @type {Array<string>}
  99. */
  100. this.refreshUniforms = refreshUniforms;
  101. /**
  102. * Holds the current render ID from the node frame.
  103. *
  104. * @type {number}
  105. * @default 0
  106. */
  107. this.renderId = 0;
  108. }
  109. /**
  110. * Returns `true` if the given render object is verified for the first time of this observer.
  111. *
  112. * @param {RenderObject} renderObject - The render object.
  113. * @return {boolean} Whether the given render object is verified for the first time of this observer.
  114. */
  115. firstInitialization( renderObject ) {
  116. const hasInitialized = this.renderObjects.has( renderObject );
  117. if ( hasInitialized === false ) {
  118. this.getRenderObjectData( renderObject );
  119. return true;
  120. }
  121. return false;
  122. }
  123. /**
  124. * Returns `true` if the current rendering produces motion vectors.
  125. *
  126. * @param {Renderer} renderer - The renderer.
  127. * @return {boolean} Whether the current rendering produces motion vectors or not.
  128. */
  129. needsVelocity( renderer ) {
  130. const mrt = renderer.getMRT();
  131. return ( mrt !== null && mrt.has( 'velocity' ) );
  132. }
  133. /**
  134. * Returns monitoring data for the given render object.
  135. *
  136. * @param {RenderObject} renderObject - The render object.
  137. * @return {Object} The monitoring data.
  138. */
  139. getRenderObjectData( renderObject ) {
  140. let data = this.renderObjects.get( renderObject );
  141. if ( data === undefined ) {
  142. const { geometry, material, object } = renderObject;
  143. data = {
  144. material: this.getMaterialData( material ),
  145. geometry: {
  146. id: geometry.id,
  147. attributes: this.getAttributesData( geometry.attributes ),
  148. indexVersion: geometry.index ? geometry.index.version : null,
  149. drawRange: { start: geometry.drawRange.start, count: geometry.drawRange.count }
  150. },
  151. worldMatrix: object.matrixWorld.clone()
  152. };
  153. if ( object.center ) {
  154. data.center = object.center.clone();
  155. }
  156. if ( object.morphTargetInfluences ) {
  157. data.morphTargetInfluences = object.morphTargetInfluences.slice();
  158. }
  159. if ( renderObject.bundle !== null ) {
  160. data.version = renderObject.bundle.version;
  161. }
  162. if ( data.material.transmission > 0 ) {
  163. const { width, height } = renderObject.context;
  164. data.bufferWidth = width;
  165. data.bufferHeight = height;
  166. }
  167. this.renderObjects.set( renderObject, data );
  168. }
  169. return data;
  170. }
  171. /**
  172. * Returns an attribute data structure holding the attributes versions for
  173. * monitoring.
  174. *
  175. * @param {Object} attributes - The geometry attributes.
  176. * @return {Object} An object for monitoring the versions of attributes.
  177. */
  178. getAttributesData( attributes ) {
  179. const attributesData = {};
  180. for ( const name in attributes ) {
  181. const attribute = attributes[ name ];
  182. attributesData[ name ] = {
  183. version: attribute.version
  184. };
  185. }
  186. return attributesData;
  187. }
  188. /**
  189. * Returns `true` if the node builder's material uses
  190. * node properties.
  191. *
  192. * @param {NodeBuilder} builder - The current node builder.
  193. * @return {boolean} Whether the node builder's material uses node properties or not.
  194. */
  195. containsNode( builder ) {
  196. const material = builder.material;
  197. for ( const property in material ) {
  198. if ( material[ property ] && material[ property ].isNode )
  199. return true;
  200. }
  201. if ( builder.renderer.overrideNodes.modelViewMatrix !== null || builder.renderer.overrideNodes.modelNormalViewMatrix !== null )
  202. return true;
  203. return false;
  204. }
  205. /**
  206. * Returns a material data structure holding the material property values for
  207. * monitoring.
  208. *
  209. * @param {Material} material - The material.
  210. * @return {Object} An object for monitoring material properties.
  211. */
  212. getMaterialData( material ) {
  213. const data = {};
  214. for ( const property of this.refreshUniforms ) {
  215. const value = material[ property ];
  216. if ( value === null || value === undefined ) continue;
  217. if ( typeof value === 'object' && value.clone !== undefined ) {
  218. if ( value.isTexture === true ) {
  219. data[ property ] = { id: value.id, version: value.version };
  220. } else {
  221. data[ property ] = value.clone();
  222. }
  223. } else {
  224. data[ property ] = value;
  225. }
  226. }
  227. return data;
  228. }
  229. /**
  230. * Returns `true` if the given render object has not changed its state.
  231. *
  232. * @param {RenderObject} renderObject - The render object.
  233. * @return {boolean} Whether the given render object has changed its state or not.
  234. */
  235. equals( renderObject ) {
  236. const { object, material, geometry } = renderObject;
  237. const renderObjectData = this.getRenderObjectData( renderObject );
  238. // world matrix
  239. if ( renderObjectData.worldMatrix.equals( object.matrixWorld ) !== true ) {
  240. renderObjectData.worldMatrix.copy( object.matrixWorld );
  241. return false;
  242. }
  243. // material
  244. const materialData = renderObjectData.material;
  245. for ( const property in materialData ) {
  246. const value = materialData[ property ];
  247. const mtlValue = material[ property ];
  248. if ( value.equals !== undefined ) {
  249. if ( value.equals( mtlValue ) === false ) {
  250. value.copy( mtlValue );
  251. return false;
  252. }
  253. } else if ( mtlValue.isTexture === true ) {
  254. if ( value.id !== mtlValue.id || value.version !== mtlValue.version ) {
  255. value.id = mtlValue.id;
  256. value.version = mtlValue.version;
  257. return false;
  258. }
  259. } else if ( value !== mtlValue ) {
  260. materialData[ property ] = mtlValue;
  261. return false;
  262. }
  263. }
  264. if ( materialData.transmission > 0 ) {
  265. const { width, height } = renderObject.context;
  266. if ( renderObjectData.bufferWidth !== width || renderObjectData.bufferHeight !== height ) {
  267. renderObjectData.bufferWidth = width;
  268. renderObjectData.bufferHeight = height;
  269. return false;
  270. }
  271. }
  272. // geometry
  273. const storedGeometryData = renderObjectData.geometry;
  274. const attributes = geometry.attributes;
  275. const storedAttributes = storedGeometryData.attributes;
  276. const storedAttributeNames = Object.keys( storedAttributes );
  277. const currentAttributeNames = Object.keys( attributes );
  278. if ( storedGeometryData.id !== geometry.id ) {
  279. storedGeometryData.id = geometry.id;
  280. return false;
  281. }
  282. if ( storedAttributeNames.length !== currentAttributeNames.length ) {
  283. renderObjectData.geometry.attributes = this.getAttributesData( attributes );
  284. return false;
  285. }
  286. // compare each attribute
  287. for ( const name of storedAttributeNames ) {
  288. const storedAttributeData = storedAttributes[ name ];
  289. const attribute = attributes[ name ];
  290. if ( attribute === undefined ) {
  291. // attribute was removed
  292. delete storedAttributes[ name ];
  293. return false;
  294. }
  295. if ( storedAttributeData.version !== attribute.version ) {
  296. storedAttributeData.version = attribute.version;
  297. return false;
  298. }
  299. }
  300. // check index
  301. const index = geometry.index;
  302. const storedIndexVersion = storedGeometryData.indexVersion;
  303. const currentIndexVersion = index ? index.version : null;
  304. if ( storedIndexVersion !== currentIndexVersion ) {
  305. storedGeometryData.indexVersion = currentIndexVersion;
  306. return false;
  307. }
  308. // check drawRange
  309. if ( storedGeometryData.drawRange.start !== geometry.drawRange.start || storedGeometryData.drawRange.count !== geometry.drawRange.count ) {
  310. storedGeometryData.drawRange.start = geometry.drawRange.start;
  311. storedGeometryData.drawRange.count = geometry.drawRange.count;
  312. return false;
  313. }
  314. // morph targets
  315. if ( renderObjectData.morphTargetInfluences ) {
  316. let morphChanged = false;
  317. for ( let i = 0; i < renderObjectData.morphTargetInfluences.length; i ++ ) {
  318. if ( renderObjectData.morphTargetInfluences[ i ] !== object.morphTargetInfluences[ i ] ) {
  319. morphChanged = true;
  320. }
  321. }
  322. if ( morphChanged ) return true;
  323. }
  324. // center
  325. if ( renderObjectData.center ) {
  326. if ( renderObjectData.center.equals( object.center ) === false ) {
  327. renderObjectData.center.copy( object.center );
  328. return true;
  329. }
  330. }
  331. // bundle
  332. if ( renderObject.bundle !== null ) {
  333. renderObjectData.version = renderObject.bundle.version;
  334. }
  335. return true;
  336. }
  337. /**
  338. * Checks if the given render object requires a refresh.
  339. *
  340. * @param {RenderObject} renderObject - The render object.
  341. * @param {NodeFrame} nodeFrame - The current node frame.
  342. * @return {boolean} Whether the given render object requires a refresh or not.
  343. */
  344. needsRefresh( renderObject, nodeFrame ) {
  345. if ( this.hasNode || this.hasAnimation || this.firstInitialization( renderObject ) || this.needsVelocity( nodeFrame.renderer ) )
  346. return true;
  347. const { renderId } = nodeFrame;
  348. if ( this.renderId !== renderId ) {
  349. this.renderId = renderId;
  350. return true;
  351. }
  352. const isStatic = renderObject.object.static === true;
  353. const isBundle = renderObject.bundle !== null && renderObject.bundle.static === true && this.getRenderObjectData( renderObject ).version === renderObject.bundle.version;
  354. if ( isStatic || isBundle )
  355. return false;
  356. const notEqual = this.equals( renderObject ) !== true;
  357. return notEqual;
  358. }
  359. }
  360. // cyrb53 (c) 2018 bryc (github.com/bryc). License: Public domain. Attribution appreciated.
  361. // A fast and simple 64-bit (or 53-bit) string hash function with decent collision resistance.
  362. // Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
  363. // See https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript/52171480#52171480
  364. // https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
  365. function cyrb53( value, seed = 0 ) {
  366. let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
  367. if ( value instanceof Array ) {
  368. for ( let i = 0, val; i < value.length; i ++ ) {
  369. val = value[ i ];
  370. h1 = Math.imul( h1 ^ val, 2654435761 );
  371. h2 = Math.imul( h2 ^ val, 1597334677 );
  372. }
  373. } else {
  374. for ( let i = 0, ch; i < value.length; i ++ ) {
  375. ch = value.charCodeAt( i );
  376. h1 = Math.imul( h1 ^ ch, 2654435761 );
  377. h2 = Math.imul( h2 ^ ch, 1597334677 );
  378. }
  379. }
  380. h1 = Math.imul( h1 ^ ( h1 >>> 16 ), 2246822507 );
  381. h1 ^= Math.imul( h2 ^ ( h2 >>> 13 ), 3266489909 );
  382. h2 = Math.imul( h2 ^ ( h2 >>> 16 ), 2246822507 );
  383. h2 ^= Math.imul( h1 ^ ( h1 >>> 13 ), 3266489909 );
  384. return 4294967296 * ( 2097151 & h2 ) + ( h1 >>> 0 );
  385. }
  386. /**
  387. * Computes a hash for the given string.
  388. *
  389. * @method
  390. * @param {string} str - The string to be hashed.
  391. * @return {number} The hash.
  392. */
  393. const hashString = ( str ) => cyrb53( str );
  394. /**
  395. * Computes a hash for the given array.
  396. *
  397. * @method
  398. * @param {Array<number>} array - The array to be hashed.
  399. * @return {number} The hash.
  400. */
  401. const hashArray = ( array ) => cyrb53( array );
  402. /**
  403. * Computes a hash for the given list of parameters.
  404. *
  405. * @method
  406. * @param {...number} params - A list of parameters.
  407. * @return {number} The hash.
  408. */
  409. const hash$1 = ( ...params ) => cyrb53( params );
  410. /**
  411. * Computes a cache key for the given node.
  412. *
  413. * @method
  414. * @param {Object|Node} object - The object to be hashed.
  415. * @param {boolean} [force=false] - Whether to force a cache key computation or not.
  416. * @return {number} The hash.
  417. */
  418. function getCacheKey$1( object, force = false ) {
  419. const values = [];
  420. if ( object.isNode === true ) {
  421. values.push( object.id );
  422. object = object.getSelf();
  423. }
  424. for ( const { property, childNode } of getNodeChildren( object ) ) {
  425. values.push( cyrb53( property.slice( 0, -4 ) ), childNode.getCacheKey( force ) );
  426. }
  427. return cyrb53( values );
  428. }
  429. /**
  430. * This generator function can be used to iterate over the node children
  431. * of the given object.
  432. *
  433. * @generator
  434. * @param {Object} node - The object to be hashed.
  435. * @param {boolean} [toJSON=false] - Whether to return JSON or not.
  436. * @yields {Object} A result node holding the property, index (if available) and the child node.
  437. */
  438. function* getNodeChildren( node, toJSON = false ) {
  439. for ( const property in node ) {
  440. // Ignore private properties.
  441. if ( property.startsWith( '_' ) === true ) continue;
  442. const object = node[ property ];
  443. if ( Array.isArray( object ) === true ) {
  444. for ( let i = 0; i < object.length; i ++ ) {
  445. const child = object[ i ];
  446. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  447. yield { property, index: i, childNode: child };
  448. }
  449. }
  450. } else if ( object && object.isNode === true ) {
  451. yield { property, childNode: object };
  452. } else if ( typeof object === 'object' ) {
  453. for ( const subProperty in object ) {
  454. const child = object[ subProperty ];
  455. if ( child && ( child.isNode === true || toJSON && typeof child.toJSON === 'function' ) ) {
  456. yield { property, index: subProperty, childNode: child };
  457. }
  458. }
  459. }
  460. }
  461. }
  462. const typeFromLength = /*@__PURE__*/ new Map( [
  463. [ 1, 'float' ],
  464. [ 2, 'vec2' ],
  465. [ 3, 'vec3' ],
  466. [ 4, 'vec4' ],
  467. [ 9, 'mat3' ],
  468. [ 16, 'mat4' ]
  469. ] );
  470. const dataFromObject = /*@__PURE__*/ new WeakMap();
  471. /**
  472. * Returns the data type for the given the length.
  473. *
  474. * @method
  475. * @param {number} length - The length.
  476. * @return {string} The data type.
  477. */
  478. function getTypeFromLength( length ) {
  479. return typeFromLength.get( length );
  480. }
  481. /**
  482. * Returns the typed array for the given data type.
  483. *
  484. * @method
  485. * @param {string} type - The data type.
  486. * @return {TypedArray} The typed array.
  487. */
  488. function getTypedArrayFromType( type ) {
  489. // Handle component type for vectors and matrices
  490. if ( /[iu]?vec\d/.test( type ) ) {
  491. // Handle int vectors
  492. if ( type.startsWith( 'ivec' ) ) return Int32Array;
  493. // Handle uint vectors
  494. if ( type.startsWith( 'uvec' ) ) return Uint32Array;
  495. // Default to float vectors
  496. return Float32Array;
  497. }
  498. // Handle matrices (always float)
  499. if ( /mat\d/.test( type ) ) return Float32Array;
  500. // Basic types
  501. if ( /float/.test( type ) ) return Float32Array;
  502. if ( /uint/.test( type ) ) return Uint32Array;
  503. if ( /int/.test( type ) ) return Int32Array;
  504. throw new Error( `THREE.NodeUtils: Unsupported type: ${type}` );
  505. }
  506. /**
  507. * Returns the length for the given data type.
  508. *
  509. * @method
  510. * @param {string} type - The data type.
  511. * @return {number} The length.
  512. */
  513. function getLengthFromType( type ) {
  514. if ( /float|int|uint/.test( type ) ) return 1;
  515. if ( /vec2/.test( type ) ) return 2;
  516. if ( /vec3/.test( type ) ) return 3;
  517. if ( /vec4/.test( type ) ) return 4;
  518. if ( /mat2/.test( type ) ) return 4;
  519. if ( /mat3/.test( type ) ) return 9;
  520. if ( /mat4/.test( type ) ) return 16;
  521. console.error( 'THREE.TSL: Unsupported type:', type );
  522. }
  523. /**
  524. * Returns the gpu memory length for the given data type.
  525. *
  526. * @method
  527. * @param {string} type - The data type.
  528. * @return {number} The length.
  529. */
  530. function getMemoryLengthFromType( type ) {
  531. if ( /float|int|uint/.test( type ) ) return 1;
  532. if ( /vec2/.test( type ) ) return 2;
  533. if ( /vec3/.test( type ) ) return 3;
  534. if ( /vec4/.test( type ) ) return 4;
  535. if ( /mat2/.test( type ) ) return 4;
  536. if ( /mat3/.test( type ) ) return 12;
  537. if ( /mat4/.test( type ) ) return 16;
  538. console.error( 'THREE.TSL: Unsupported type:', type );
  539. }
  540. /**
  541. * Returns the byte boundary for the given data type.
  542. *
  543. * @method
  544. * @param {string} type - The data type.
  545. * @return {number} The byte boundary.
  546. */
  547. function getByteBoundaryFromType( type ) {
  548. if ( /float|int|uint/.test( type ) ) return 4;
  549. if ( /vec2/.test( type ) ) return 8;
  550. if ( /vec3/.test( type ) ) return 16;
  551. if ( /vec4/.test( type ) ) return 16;
  552. if ( /mat2/.test( type ) ) return 8;
  553. if ( /mat3/.test( type ) ) return 48;
  554. if ( /mat4/.test( type ) ) return 64;
  555. console.error( 'THREE.TSL: Unsupported type:', type );
  556. }
  557. /**
  558. * Returns the data type for the given value.
  559. *
  560. * @method
  561. * @param {any} value - The value.
  562. * @return {?string} The data type.
  563. */
  564. function getValueType( value ) {
  565. if ( value === undefined || value === null ) return null;
  566. const typeOf = typeof value;
  567. if ( value.isNode === true ) {
  568. return 'node';
  569. } else if ( typeOf === 'number' ) {
  570. return 'float';
  571. } else if ( typeOf === 'boolean' ) {
  572. return 'bool';
  573. } else if ( typeOf === 'string' ) {
  574. return 'string';
  575. } else if ( typeOf === 'function' ) {
  576. return 'shader';
  577. } else if ( value.isVector2 === true ) {
  578. return 'vec2';
  579. } else if ( value.isVector3 === true ) {
  580. return 'vec3';
  581. } else if ( value.isVector4 === true ) {
  582. return 'vec4';
  583. } else if ( value.isMatrix2 === true ) {
  584. return 'mat2';
  585. } else if ( value.isMatrix3 === true ) {
  586. return 'mat3';
  587. } else if ( value.isMatrix4 === true ) {
  588. return 'mat4';
  589. } else if ( value.isColor === true ) {
  590. return 'color';
  591. } else if ( value instanceof ArrayBuffer ) {
  592. return 'ArrayBuffer';
  593. }
  594. return null;
  595. }
  596. /**
  597. * Returns the value/object for the given data type and parameters.
  598. *
  599. * @method
  600. * @param {string} type - The given type.
  601. * @param {...any} params - A parameter list.
  602. * @return {any} The value/object.
  603. */
  604. function getValueFromType( type, ...params ) {
  605. const last4 = type ? type.slice( -4 ) : undefined;
  606. if ( params.length === 1 ) { // ensure same behaviour as in NodeBuilder.format()
  607. if ( last4 === 'vec2' ) params = [ params[ 0 ], params[ 0 ] ];
  608. else if ( last4 === 'vec3' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ] ];
  609. else if ( last4 === 'vec4' ) params = [ params[ 0 ], params[ 0 ], params[ 0 ], params[ 0 ] ];
  610. }
  611. if ( type === 'color' ) {
  612. return new Color( ...params );
  613. } else if ( last4 === 'vec2' ) {
  614. return new Vector2( ...params );
  615. } else if ( last4 === 'vec3' ) {
  616. return new Vector3( ...params );
  617. } else if ( last4 === 'vec4' ) {
  618. return new Vector4( ...params );
  619. } else if ( last4 === 'mat2' ) {
  620. return new Matrix2( ...params );
  621. } else if ( last4 === 'mat3' ) {
  622. return new Matrix3( ...params );
  623. } else if ( last4 === 'mat4' ) {
  624. return new Matrix4( ...params );
  625. } else if ( type === 'bool' ) {
  626. return params[ 0 ] || false;
  627. } else if ( ( type === 'float' ) || ( type === 'int' ) || ( type === 'uint' ) ) {
  628. return params[ 0 ] || 0;
  629. } else if ( type === 'string' ) {
  630. return params[ 0 ] || '';
  631. } else if ( type === 'ArrayBuffer' ) {
  632. return base64ToArrayBuffer( params[ 0 ] );
  633. }
  634. return null;
  635. }
  636. /**
  637. * Gets the object data that can be shared between different rendering steps.
  638. *
  639. * @param {Object} object - The object to get the data for.
  640. * @return {Object} The object data.
  641. */
  642. function getDataFromObject( object ) {
  643. let data = dataFromObject.get( object );
  644. if ( data === undefined ) {
  645. data = {};
  646. dataFromObject.set( object, data );
  647. }
  648. return data;
  649. }
  650. /**
  651. * Converts the given array buffer to a Base64 string.
  652. *
  653. * @method
  654. * @param {ArrayBuffer} arrayBuffer - The array buffer.
  655. * @return {string} The Base64 string.
  656. */
  657. function arrayBufferToBase64( arrayBuffer ) {
  658. let chars = '';
  659. const array = new Uint8Array( arrayBuffer );
  660. for ( let i = 0; i < array.length; i ++ ) {
  661. chars += String.fromCharCode( array[ i ] );
  662. }
  663. return btoa( chars );
  664. }
  665. /**
  666. * Converts the given Base64 string to an array buffer.
  667. *
  668. * @method
  669. * @param {string} base64 - The Base64 string.
  670. * @return {ArrayBuffer} The array buffer.
  671. */
  672. function base64ToArrayBuffer( base64 ) {
  673. return Uint8Array.from( atob( base64 ), c => c.charCodeAt( 0 ) ).buffer;
  674. }
  675. var NodeUtils = /*#__PURE__*/Object.freeze({
  676. __proto__: null,
  677. arrayBufferToBase64: arrayBufferToBase64,
  678. base64ToArrayBuffer: base64ToArrayBuffer,
  679. getByteBoundaryFromType: getByteBoundaryFromType,
  680. getCacheKey: getCacheKey$1,
  681. getDataFromObject: getDataFromObject,
  682. getLengthFromType: getLengthFromType,
  683. getMemoryLengthFromType: getMemoryLengthFromType,
  684. getNodeChildren: getNodeChildren,
  685. getTypeFromLength: getTypeFromLength,
  686. getTypedArrayFromType: getTypedArrayFromType,
  687. getValueFromType: getValueFromType,
  688. getValueType: getValueType,
  689. hash: hash$1,
  690. hashArray: hashArray,
  691. hashString: hashString
  692. });
  693. /**
  694. * Possible shader stages.
  695. *
  696. * @property {string} VERTEX The vertex shader stage.
  697. * @property {string} FRAGMENT The fragment shader stage.
  698. */
  699. const NodeShaderStage = {
  700. VERTEX: 'vertex',
  701. FRAGMENT: 'fragment'
  702. };
  703. /**
  704. * Update types of a node.
  705. *
  706. * @property {string} NONE The update method is not executed.
  707. * @property {string} FRAME The update method is executed per frame.
  708. * @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.
  709. * @property {string} OBJECT The update method is executed per {@link Object3D} that uses the node for rendering.
  710. */
  711. const NodeUpdateType = {
  712. NONE: 'none',
  713. FRAME: 'frame',
  714. RENDER: 'render',
  715. OBJECT: 'object'
  716. };
  717. /**
  718. * Data types of a node.
  719. *
  720. * @property {string} BOOLEAN Boolean type.
  721. * @property {string} INTEGER Integer type.
  722. * @property {string} FLOAT Float type.
  723. * @property {string} VECTOR2 Two-dimensional vector type.
  724. * @property {string} VECTOR3 Three-dimensional vector type.
  725. * @property {string} VECTOR4 Four-dimensional vector type.
  726. * @property {string} MATRIX2 2x2 matrix type.
  727. * @property {string} MATRIX3 3x3 matrix type.
  728. * @property {string} MATRIX4 4x4 matrix type.
  729. */
  730. const NodeType = {
  731. BOOLEAN: 'bool',
  732. INTEGER: 'int',
  733. FLOAT: 'float',
  734. VECTOR2: 'vec2',
  735. VECTOR3: 'vec3',
  736. VECTOR4: 'vec4',
  737. MATRIX2: 'mat2',
  738. MATRIX3: 'mat3',
  739. MATRIX4: 'mat4'
  740. };
  741. /**
  742. * Access types of a node. These are relevant for compute and storage usage.
  743. *
  744. * @property {string} READ_ONLY Read-only access
  745. * @property {string} WRITE_ONLY Write-only access.
  746. * @property {string} READ_WRITE Read and write access.
  747. */
  748. const NodeAccess = {
  749. READ_ONLY: 'readOnly',
  750. WRITE_ONLY: 'writeOnly',
  751. READ_WRITE: 'readWrite',
  752. };
  753. const defaultShaderStages = [ 'fragment', 'vertex' ];
  754. const defaultBuildStages = [ 'setup', 'analyze', 'generate' ];
  755. const shaderStages = [ ...defaultShaderStages, 'compute' ];
  756. const vectorComponents = [ 'x', 'y', 'z', 'w' ];
  757. const _parentBuildStage = {
  758. analyze: 'setup',
  759. generate: 'analyze'
  760. };
  761. let _nodeId = 0;
  762. /**
  763. * Base class for all nodes.
  764. *
  765. * @augments EventDispatcher
  766. */
  767. class Node extends EventDispatcher {
  768. static get type() {
  769. return 'Node';
  770. }
  771. /**
  772. * Constructs a new node.
  773. *
  774. * @param {?string} nodeType - The node type.
  775. */
  776. constructor( nodeType = null ) {
  777. super();
  778. /**
  779. * The node type. This represents the result type of the node (e.g. `float` or `vec3`).
  780. *
  781. * @type {?string}
  782. * @default null
  783. */
  784. this.nodeType = nodeType;
  785. /**
  786. * The update type of the node's {@link Node#update} method. Possible values are listed in {@link NodeUpdateType}.
  787. *
  788. * @type {string}
  789. * @default 'none'
  790. */
  791. this.updateType = NodeUpdateType.NONE;
  792. /**
  793. * The update type of the node's {@link Node#updateBefore} method. Possible values are listed in {@link NodeUpdateType}.
  794. *
  795. * @type {string}
  796. * @default 'none'
  797. */
  798. this.updateBeforeType = NodeUpdateType.NONE;
  799. /**
  800. * The update type of the node's {@link Node#updateAfter} method. Possible values are listed in {@link NodeUpdateType}.
  801. *
  802. * @type {string}
  803. * @default 'none'
  804. */
  805. this.updateAfterType = NodeUpdateType.NONE;
  806. /**
  807. * The UUID of the node.
  808. *
  809. * @type {string}
  810. * @readonly
  811. */
  812. this.uuid = MathUtils.generateUUID();
  813. /**
  814. * The version of the node. The version automatically is increased when {@link Node#needsUpdate} is set to `true`.
  815. *
  816. * @type {number}
  817. * @readonly
  818. * @default 0
  819. */
  820. this.version = 0;
  821. /**
  822. * Whether this node is global or not. This property is relevant for the internal
  823. * node caching system. All nodes which should be declared just once should
  824. * set this flag to `true` (a typical example is {@link AttributeNode}).
  825. *
  826. * @type {boolean}
  827. * @default false
  828. */
  829. this.global = false;
  830. /**
  831. * Create a list of parents for this node during the build process.
  832. *
  833. * @type {boolean}
  834. * @default false
  835. */
  836. this.parents = false;
  837. /**
  838. * This flag can be used for type testing.
  839. *
  840. * @type {boolean}
  841. * @readonly
  842. * @default true
  843. */
  844. this.isNode = true;
  845. // private
  846. /**
  847. * The cache key of this node.
  848. *
  849. * @private
  850. * @type {?number}
  851. * @default null
  852. */
  853. this._cacheKey = null;
  854. /**
  855. * The cache key 's version.
  856. *
  857. * @private
  858. * @type {number}
  859. * @default 0
  860. */
  861. this._cacheKeyVersion = 0;
  862. Object.defineProperty( this, 'id', { value: _nodeId ++ } );
  863. }
  864. /**
  865. * Set this property to `true` when the node should be regenerated.
  866. *
  867. * @type {boolean}
  868. * @default false
  869. * @param {boolean} value
  870. */
  871. set needsUpdate( value ) {
  872. if ( value === true ) {
  873. this.version ++;
  874. }
  875. }
  876. /**
  877. * The type of the class. The value is usually the constructor name.
  878. *
  879. * @type {string}
  880. * @readonly
  881. */
  882. get type() {
  883. return this.constructor.type;
  884. }
  885. /**
  886. * Convenient method for defining {@link Node#update}.
  887. *
  888. * @param {Function} callback - The update method.
  889. * @param {string} updateType - The update type.
  890. * @return {Node} A reference to this node.
  891. */
  892. onUpdate( callback, updateType ) {
  893. this.updateType = updateType;
  894. this.update = callback.bind( this.getSelf() );
  895. return this;
  896. }
  897. /**
  898. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  899. * this method automatically sets the update type to `FRAME`.
  900. *
  901. * @param {Function} callback - The update method.
  902. * @return {Node} A reference to this node.
  903. */
  904. onFrameUpdate( callback ) {
  905. return this.onUpdate( callback, NodeUpdateType.FRAME );
  906. }
  907. /**
  908. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  909. * this method automatically sets the update type to `RENDER`.
  910. *
  911. * @param {Function} callback - The update method.
  912. * @return {Node} A reference to this node.
  913. */
  914. onRenderUpdate( callback ) {
  915. return this.onUpdate( callback, NodeUpdateType.RENDER );
  916. }
  917. /**
  918. * Convenient method for defining {@link Node#update}. Similar to {@link Node#onUpdate}, but
  919. * this method automatically sets the update type to `OBJECT`.
  920. *
  921. * @param {Function} callback - The update method.
  922. * @return {Node} A reference to this node.
  923. */
  924. onObjectUpdate( callback ) {
  925. return this.onUpdate( callback, NodeUpdateType.OBJECT );
  926. }
  927. /**
  928. * Convenient method for defining {@link Node#updateReference}.
  929. *
  930. * @param {Function} callback - The update method.
  931. * @return {Node} A reference to this node.
  932. */
  933. onReference( callback ) {
  934. this.updateReference = callback.bind( this.getSelf() );
  935. return this;
  936. }
  937. /**
  938. * The `this` reference might point to a Proxy so this method can be used
  939. * to get the reference to the actual node instance.
  940. *
  941. * @return {Node} A reference to the node.
  942. */
  943. getSelf() {
  944. // Returns non-node object.
  945. return this.self || this;
  946. }
  947. /**
  948. * Nodes might refer to other objects like materials. This method allows to dynamically update the reference
  949. * to such objects based on a given state (e.g. the current node frame or builder).
  950. *
  951. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  952. * @return {any} The updated reference.
  953. */
  954. updateReference( /*state*/ ) {
  955. return this;
  956. }
  957. /**
  958. * By default this method returns the value of the {@link Node#global} flag. This method
  959. * can be overwritten in derived classes if an analytical way is required to determine the
  960. * global cache referring to the current shader-stage.
  961. *
  962. * @param {NodeBuilder} builder - The current node builder.
  963. * @return {boolean} Whether this node is global or not.
  964. */
  965. isGlobal( /*builder*/ ) {
  966. return this.global;
  967. }
  968. /**
  969. * Generator function that can be used to iterate over the child nodes.
  970. *
  971. * @generator
  972. * @yields {Node} A child node.
  973. */
  974. * getChildren() {
  975. for ( const { childNode } of getNodeChildren( this ) ) {
  976. yield childNode;
  977. }
  978. }
  979. /**
  980. * Calling this method dispatches the `dispose` event. This event can be used
  981. * to register event listeners for clean up tasks.
  982. */
  983. dispose() {
  984. this.dispatchEvent( { type: 'dispose' } );
  985. }
  986. /**
  987. * Callback for {@link Node#traverse}.
  988. *
  989. * @callback traverseCallback
  990. * @param {Node} node - The current node.
  991. */
  992. /**
  993. * Can be used to traverse through the node's hierarchy.
  994. *
  995. * @param {traverseCallback} callback - A callback that is executed per node.
  996. */
  997. traverse( callback ) {
  998. callback( this );
  999. for ( const childNode of this.getChildren() ) {
  1000. childNode.traverse( callback );
  1001. }
  1002. }
  1003. /**
  1004. * Returns the cache key for this node.
  1005. *
  1006. * @param {boolean} [force=false] - When set to `true`, a recomputation of the cache key is forced.
  1007. * @return {number} The cache key of the node.
  1008. */
  1009. getCacheKey( force = false ) {
  1010. force = force || this.version !== this._cacheKeyVersion;
  1011. if ( force === true || this._cacheKey === null ) {
  1012. this._cacheKey = hash$1( getCacheKey$1( this, force ), this.customCacheKey() );
  1013. this._cacheKeyVersion = this.version;
  1014. }
  1015. return this._cacheKey;
  1016. }
  1017. /**
  1018. * Generate a custom cache key for this node.
  1019. *
  1020. * @return {number} The cache key of the node.
  1021. */
  1022. customCacheKey() {
  1023. return 0;
  1024. }
  1025. /**
  1026. * Returns the references to this node which is by default `this`.
  1027. *
  1028. * @return {Node} A reference to this node.
  1029. */
  1030. getScope() {
  1031. return this;
  1032. }
  1033. /**
  1034. * Returns the hash of the node which is used to identify the node. By default it's
  1035. * the {@link Node#uuid} however derived node classes might have to overwrite this method
  1036. * depending on their implementation.
  1037. *
  1038. * @param {NodeBuilder} builder - The current node builder.
  1039. * @return {string} The hash.
  1040. */
  1041. getHash( /*builder*/ ) {
  1042. return this.uuid;
  1043. }
  1044. /**
  1045. * Returns the update type of {@link Node#update}.
  1046. *
  1047. * @return {NodeUpdateType} The update type.
  1048. */
  1049. getUpdateType() {
  1050. return this.updateType;
  1051. }
  1052. /**
  1053. * Returns the update type of {@link Node#updateBefore}.
  1054. *
  1055. * @return {NodeUpdateType} The update type.
  1056. */
  1057. getUpdateBeforeType() {
  1058. return this.updateBeforeType;
  1059. }
  1060. /**
  1061. * Returns the update type of {@link Node#updateAfter}.
  1062. *
  1063. * @return {NodeUpdateType} The update type.
  1064. */
  1065. getUpdateAfterType() {
  1066. return this.updateAfterType;
  1067. }
  1068. /**
  1069. * Certain types are composed of multiple elements. For example a `vec3`
  1070. * is composed of three `float` values. This method returns the type of
  1071. * these elements.
  1072. *
  1073. * @param {NodeBuilder} builder - The current node builder.
  1074. * @return {string} The type of the node.
  1075. */
  1076. getElementType( builder ) {
  1077. const type = this.getNodeType( builder );
  1078. const elementType = builder.getElementType( type );
  1079. return elementType;
  1080. }
  1081. /**
  1082. * Returns the node member type for the given name.
  1083. *
  1084. * @param {NodeBuilder} builder - The current node builder.
  1085. * @param {string} name - The name of the member.
  1086. * @return {string} The type of the node.
  1087. */
  1088. getMemberType( /*builder, name*/ ) {
  1089. return 'void';
  1090. }
  1091. /**
  1092. * Returns the node's type.
  1093. *
  1094. * @param {NodeBuilder} builder - The current node builder.
  1095. * @return {string} The type of the node.
  1096. */
  1097. getNodeType( builder ) {
  1098. const nodeProperties = builder.getNodeProperties( this );
  1099. if ( nodeProperties.outputNode ) {
  1100. return nodeProperties.outputNode.getNodeType( builder );
  1101. }
  1102. return this.nodeType;
  1103. }
  1104. /**
  1105. * This method is used during the build process of a node and ensures
  1106. * equal nodes are not built multiple times but just once. For example if
  1107. * `attribute( 'uv' )` is used multiple times by the user, the build
  1108. * process makes sure to process just the first node.
  1109. *
  1110. * @param {NodeBuilder} builder - The current node builder.
  1111. * @return {Node} The shared node if possible. Otherwise `this` is returned.
  1112. */
  1113. getShared( builder ) {
  1114. const hash = this.getHash( builder );
  1115. const nodeFromHash = builder.getNodeFromHash( hash );
  1116. return nodeFromHash || this;
  1117. }
  1118. /**
  1119. * Represents the setup stage which is the first step of the build process, see {@link Node#build} method.
  1120. * This method is often overwritten in derived modules to prepare the node which is used as the output/result.
  1121. * The output node must be returned in the `return` statement.
  1122. *
  1123. * @param {NodeBuilder} builder - The current node builder.
  1124. * @return {?Node} The output node.
  1125. */
  1126. setup( builder ) {
  1127. const nodeProperties = builder.getNodeProperties( this );
  1128. let index = 0;
  1129. for ( const childNode of this.getChildren() ) {
  1130. nodeProperties[ 'node' + index ++ ] = childNode;
  1131. }
  1132. // return a outputNode if exists or null
  1133. return nodeProperties.outputNode || null;
  1134. }
  1135. /**
  1136. * Represents the analyze stage which is the second step of the build process, see {@link Node#build} method.
  1137. * This stage analyzes the node hierarchy and ensures descendent nodes are built.
  1138. *
  1139. * @param {NodeBuilder} builder - The current node builder.
  1140. * @param {?Node} output - The target output node.
  1141. */
  1142. analyze( builder, output = null ) {
  1143. const usageCount = builder.increaseUsage( this );
  1144. if ( this.parents === true ) {
  1145. const nodeData = builder.getDataFromNode( this, 'any' );
  1146. nodeData.stages = nodeData.stages || {};
  1147. nodeData.stages[ builder.shaderStage ] = nodeData.stages[ builder.shaderStage ] || [];
  1148. nodeData.stages[ builder.shaderStage ].push( output );
  1149. }
  1150. if ( usageCount === 1 ) {
  1151. // node flow children
  1152. const nodeProperties = builder.getNodeProperties( this );
  1153. for ( const childNode of Object.values( nodeProperties ) ) {
  1154. if ( childNode && childNode.isNode === true ) {
  1155. childNode.build( builder, this );
  1156. }
  1157. }
  1158. }
  1159. }
  1160. /**
  1161. * Represents the generate stage which is the third step of the build process, see {@link Node#build} method.
  1162. * This state builds the output node and returns the resulting shader string.
  1163. *
  1164. * @param {NodeBuilder} builder - The current node builder.
  1165. * @param {?string} output - Can be used to define the output type.
  1166. * @return {?string} The generated shader string.
  1167. */
  1168. generate( builder, output ) {
  1169. const { outputNode } = builder.getNodeProperties( this );
  1170. if ( outputNode && outputNode.isNode === true ) {
  1171. return outputNode.build( builder, output );
  1172. }
  1173. }
  1174. /**
  1175. * The method can be implemented to update the node's internal state before it is used to render an object.
  1176. * The {@link Node#updateBeforeType} property defines how often the update is executed.
  1177. *
  1178. * @abstract
  1179. * @param {NodeFrame} frame - A reference to the current node frame.
  1180. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1181. */
  1182. updateBefore( /*frame*/ ) {
  1183. console.warn( 'Abstract function.' );
  1184. }
  1185. /**
  1186. * The method can be implemented to update the node's internal state after it was used to render an object.
  1187. * The {@link Node#updateAfterType} property defines how often the update is executed.
  1188. *
  1189. * @abstract
  1190. * @param {NodeFrame} frame - A reference to the current node frame.
  1191. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1192. */
  1193. updateAfter( /*frame*/ ) {
  1194. console.warn( 'Abstract function.' );
  1195. }
  1196. /**
  1197. * The method can be implemented to update the node's internal state when it is used to render an object.
  1198. * The {@link Node#updateType} property defines how often the update is executed.
  1199. *
  1200. * @abstract
  1201. * @param {NodeFrame} frame - A reference to the current node frame.
  1202. * @return {?boolean} An optional bool that indicates whether the implementation actually performed an update or not (e.g. due to caching).
  1203. */
  1204. update( /*frame*/ ) {
  1205. console.warn( 'Abstract function.' );
  1206. }
  1207. /**
  1208. * This method performs the build of a node. The behavior and return value depend on the current build stage:
  1209. * - **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.
  1210. * - **analyze**: Analyzes the node hierarchy for optimizations in the code generation stage. Returns `null`.
  1211. * - **generate**: Generates the shader code for the node. Returns the generated shader string.
  1212. *
  1213. * @param {NodeBuilder} builder - The current node builder.
  1214. * @param {string|Node|null} [output=null] - Can be used to define the output type.
  1215. * @return {Node|string|null} The result of the build process, depending on the build stage.
  1216. */
  1217. build( builder, output = null ) {
  1218. const refNode = this.getShared( builder );
  1219. if ( this !== refNode ) {
  1220. return refNode.build( builder, output );
  1221. }
  1222. //
  1223. const nodeData = builder.getDataFromNode( this );
  1224. nodeData.buildStages = nodeData.buildStages || {};
  1225. nodeData.buildStages[ builder.buildStage ] = true;
  1226. const parentBuildStage = _parentBuildStage[ builder.buildStage ];
  1227. if ( parentBuildStage && nodeData.buildStages[ parentBuildStage ] !== true ) {
  1228. // force parent build stage (setup or analyze)
  1229. const previousBuildStage = builder.getBuildStage();
  1230. builder.setBuildStage( parentBuildStage );
  1231. this.build( builder );
  1232. builder.setBuildStage( previousBuildStage );
  1233. }
  1234. //
  1235. builder.addNode( this );
  1236. builder.addChain( this );
  1237. /* Build stages expected results:
  1238. - "setup" -> Node
  1239. - "analyze" -> null
  1240. - "generate" -> String
  1241. */
  1242. let result = null;
  1243. const buildStage = builder.getBuildStage();
  1244. if ( buildStage === 'setup' ) {
  1245. this.updateReference( builder );
  1246. const properties = builder.getNodeProperties( this );
  1247. if ( properties.initialized !== true ) {
  1248. //const stackNodesBeforeSetup = builder.stack.nodes.length;
  1249. properties.initialized = true;
  1250. properties.outputNode = this.setup( builder ) || properties.outputNode || null;
  1251. /*if ( isNodeOutput && builder.stack.nodes.length !== stackNodesBeforeSetup ) {
  1252. // !! no outputNode !!
  1253. //outputNode = builder.stack;
  1254. }*/
  1255. for ( const childNode of Object.values( properties ) ) {
  1256. if ( childNode && childNode.isNode === true ) {
  1257. if ( childNode.parents === true ) {
  1258. const childProperties = builder.getNodeProperties( childNode );
  1259. childProperties.parents = childProperties.parents || [];
  1260. childProperties.parents.push( this );
  1261. }
  1262. childNode.build( builder );
  1263. }
  1264. }
  1265. }
  1266. result = properties.outputNode;
  1267. } else if ( buildStage === 'analyze' ) {
  1268. this.analyze( builder, output );
  1269. } else if ( buildStage === 'generate' ) {
  1270. const isGenerateOnce = this.generate.length === 1;
  1271. if ( isGenerateOnce ) {
  1272. const type = this.getNodeType( builder );
  1273. const nodeData = builder.getDataFromNode( this );
  1274. result = nodeData.snippet;
  1275. if ( result === undefined ) {
  1276. if ( nodeData.generated === undefined ) {
  1277. nodeData.generated = true;
  1278. result = this.generate( builder ) || '';
  1279. nodeData.snippet = result;
  1280. } else {
  1281. console.warn( 'THREE.Node: Recursion detected.', this );
  1282. result = '';
  1283. }
  1284. } else if ( nodeData.flowCodes !== undefined && builder.context.nodeBlock !== undefined ) {
  1285. builder.addFlowCodeHierarchy( this, builder.context.nodeBlock );
  1286. }
  1287. result = builder.format( result, type, output );
  1288. } else {
  1289. result = this.generate( builder, output ) || '';
  1290. }
  1291. }
  1292. builder.removeChain( this );
  1293. builder.addSequentialNode( this );
  1294. return result;
  1295. }
  1296. /**
  1297. * Returns the child nodes as a JSON object.
  1298. *
  1299. * @return {Array<Object>} An iterable list of serialized child objects as JSON.
  1300. */
  1301. getSerializeChildren() {
  1302. return getNodeChildren( this );
  1303. }
  1304. /**
  1305. * Serializes the node to JSON.
  1306. *
  1307. * @param {Object} json - The output JSON object.
  1308. */
  1309. serialize( json ) {
  1310. const nodeChildren = this.getSerializeChildren();
  1311. const inputNodes = {};
  1312. for ( const { property, index, childNode } of nodeChildren ) {
  1313. if ( index !== undefined ) {
  1314. if ( inputNodes[ property ] === undefined ) {
  1315. inputNodes[ property ] = Number.isInteger( index ) ? [] : {};
  1316. }
  1317. inputNodes[ property ][ index ] = childNode.toJSON( json.meta ).uuid;
  1318. } else {
  1319. inputNodes[ property ] = childNode.toJSON( json.meta ).uuid;
  1320. }
  1321. }
  1322. if ( Object.keys( inputNodes ).length > 0 ) {
  1323. json.inputNodes = inputNodes;
  1324. }
  1325. }
  1326. /**
  1327. * Deserializes the node from the given JSON.
  1328. *
  1329. * @param {Object} json - The JSON object.
  1330. */
  1331. deserialize( json ) {
  1332. if ( json.inputNodes !== undefined ) {
  1333. const nodes = json.meta.nodes;
  1334. for ( const property in json.inputNodes ) {
  1335. if ( Array.isArray( json.inputNodes[ property ] ) ) {
  1336. const inputArray = [];
  1337. for ( const uuid of json.inputNodes[ property ] ) {
  1338. inputArray.push( nodes[ uuid ] );
  1339. }
  1340. this[ property ] = inputArray;
  1341. } else if ( typeof json.inputNodes[ property ] === 'object' ) {
  1342. const inputObject = {};
  1343. for ( const subProperty in json.inputNodes[ property ] ) {
  1344. const uuid = json.inputNodes[ property ][ subProperty ];
  1345. inputObject[ subProperty ] = nodes[ uuid ];
  1346. }
  1347. this[ property ] = inputObject;
  1348. } else {
  1349. const uuid = json.inputNodes[ property ];
  1350. this[ property ] = nodes[ uuid ];
  1351. }
  1352. }
  1353. }
  1354. }
  1355. /**
  1356. * Serializes the node into the three.js JSON Object/Scene format.
  1357. *
  1358. * @param {?Object} meta - An optional JSON object that already holds serialized data from other scene objects.
  1359. * @return {Object} The serialized node.
  1360. */
  1361. toJSON( meta ) {
  1362. const { uuid, type } = this;
  1363. const isRoot = ( meta === undefined || typeof meta === 'string' );
  1364. if ( isRoot ) {
  1365. meta = {
  1366. textures: {},
  1367. images: {},
  1368. nodes: {}
  1369. };
  1370. }
  1371. // serialize
  1372. let data = meta.nodes[ uuid ];
  1373. if ( data === undefined ) {
  1374. data = {
  1375. uuid,
  1376. type,
  1377. meta,
  1378. metadata: {
  1379. version: 4.7,
  1380. type: 'Node',
  1381. generator: 'Node.toJSON'
  1382. }
  1383. };
  1384. if ( isRoot !== true ) meta.nodes[ data.uuid ] = data;
  1385. this.serialize( data );
  1386. delete data.meta;
  1387. }
  1388. // TODO: Copied from Object3D.toJSON
  1389. function extractFromCache( cache ) {
  1390. const values = [];
  1391. for ( const key in cache ) {
  1392. const data = cache[ key ];
  1393. delete data.metadata;
  1394. values.push( data );
  1395. }
  1396. return values;
  1397. }
  1398. if ( isRoot ) {
  1399. const textures = extractFromCache( meta.textures );
  1400. const images = extractFromCache( meta.images );
  1401. const nodes = extractFromCache( meta.nodes );
  1402. if ( textures.length > 0 ) data.textures = textures;
  1403. if ( images.length > 0 ) data.images = images;
  1404. if ( nodes.length > 0 ) data.nodes = nodes;
  1405. }
  1406. return data;
  1407. }
  1408. }
  1409. /**
  1410. * Base class for representing element access on an array-like
  1411. * node data structures.
  1412. *
  1413. * @augments Node
  1414. */
  1415. class ArrayElementNode extends Node { // @TODO: If extending from TempNode it breaks webgpu_compute
  1416. static get type() {
  1417. return 'ArrayElementNode';
  1418. }
  1419. /**
  1420. * Constructs an array element node.
  1421. *
  1422. * @param {Node} node - The array-like node.
  1423. * @param {Node} indexNode - The index node that defines the element access.
  1424. */
  1425. constructor( node, indexNode ) {
  1426. super();
  1427. /**
  1428. * The array-like node.
  1429. *
  1430. * @type {Node}
  1431. */
  1432. this.node = node;
  1433. /**
  1434. * The index node that defines the element access.
  1435. *
  1436. * @type {Node}
  1437. */
  1438. this.indexNode = indexNode;
  1439. /**
  1440. * This flag can be used for type testing.
  1441. *
  1442. * @type {boolean}
  1443. * @readonly
  1444. * @default true
  1445. */
  1446. this.isArrayElementNode = true;
  1447. }
  1448. /**
  1449. * This method is overwritten since the node type is inferred from the array-like node.
  1450. *
  1451. * @param {NodeBuilder} builder - The current node builder.
  1452. * @return {string} The node type.
  1453. */
  1454. getNodeType( builder ) {
  1455. return this.node.getElementType( builder );
  1456. }
  1457. generate( builder ) {
  1458. const indexType = this.indexNode.getNodeType( builder );
  1459. const nodeSnippet = this.node.build( builder );
  1460. const indexSnippet = this.indexNode.build( builder, ! builder.isVector( indexType ) && builder.isInteger( indexType ) ? indexType : 'uint' );
  1461. return `${ nodeSnippet }[ ${ indexSnippet } ]`;
  1462. }
  1463. }
  1464. /**
  1465. * This module is part of the TSL core and usually not used in app level code.
  1466. * It represents a convert operation during the shader generation process
  1467. * meaning it converts the data type of a node to a target data type.
  1468. *
  1469. * @augments Node
  1470. */
  1471. class ConvertNode extends Node {
  1472. static get type() {
  1473. return 'ConvertNode';
  1474. }
  1475. /**
  1476. * Constructs a new convert node.
  1477. *
  1478. * @param {Node} node - The node which type should be converted.
  1479. * @param {string} convertTo - The target node type. Multiple types can be defined by separating them with a `|` sign.
  1480. */
  1481. constructor( node, convertTo ) {
  1482. super();
  1483. /**
  1484. * The node which type should be converted.
  1485. *
  1486. * @type {Node}
  1487. */
  1488. this.node = node;
  1489. /**
  1490. * The target node type. Multiple types can be defined by separating them with a `|` sign.
  1491. *
  1492. * @type {string}
  1493. */
  1494. this.convertTo = convertTo;
  1495. }
  1496. /**
  1497. * This method is overwritten since the implementation tries to infer the best
  1498. * matching type from the {@link ConvertNode#convertTo} property.
  1499. *
  1500. * @param {NodeBuilder} builder - The current node builder.
  1501. * @return {string} The node type.
  1502. */
  1503. getNodeType( builder ) {
  1504. const requestType = this.node.getNodeType( builder );
  1505. let convertTo = null;
  1506. for ( const overloadingType of this.convertTo.split( '|' ) ) {
  1507. if ( convertTo === null || builder.getTypeLength( requestType ) === builder.getTypeLength( overloadingType ) ) {
  1508. convertTo = overloadingType;
  1509. }
  1510. }
  1511. return convertTo;
  1512. }
  1513. serialize( data ) {
  1514. super.serialize( data );
  1515. data.convertTo = this.convertTo;
  1516. }
  1517. deserialize( data ) {
  1518. super.deserialize( data );
  1519. this.convertTo = data.convertTo;
  1520. }
  1521. generate( builder, output ) {
  1522. const node = this.node;
  1523. const type = this.getNodeType( builder );
  1524. const snippet = node.build( builder, type );
  1525. return builder.format( snippet, type, output );
  1526. }
  1527. }
  1528. /**
  1529. * This module uses cache management to create temporary variables
  1530. * if the node is used more than once to prevent duplicate calculations.
  1531. *
  1532. * The class acts as a base class for many other nodes types.
  1533. *
  1534. * @augments Node
  1535. */
  1536. class TempNode extends Node {
  1537. static get type() {
  1538. return 'TempNode';
  1539. }
  1540. /**
  1541. * Constructs a temp node.
  1542. *
  1543. * @param {?string} nodeType - The node type.
  1544. */
  1545. constructor( nodeType = null ) {
  1546. super( nodeType );
  1547. /**
  1548. * This flag can be used for type testing.
  1549. *
  1550. * @type {boolean}
  1551. * @readonly
  1552. * @default true
  1553. */
  1554. this.isTempNode = true;
  1555. }
  1556. /**
  1557. * Whether this node is used more than once in context of other nodes.
  1558. *
  1559. * @param {NodeBuilder} builder - The node builder.
  1560. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes.
  1561. */
  1562. hasDependencies( builder ) {
  1563. return builder.getDataFromNode( this ).usageCount > 1;
  1564. }
  1565. build( builder, output ) {
  1566. const buildStage = builder.getBuildStage();
  1567. if ( buildStage === 'generate' ) {
  1568. const type = builder.getVectorType( this.getNodeType( builder, output ) );
  1569. const nodeData = builder.getDataFromNode( this );
  1570. if ( nodeData.propertyName !== undefined ) {
  1571. return builder.format( nodeData.propertyName, type, output );
  1572. } else if ( type !== 'void' && output !== 'void' && this.hasDependencies( builder ) ) {
  1573. const snippet = super.build( builder, type );
  1574. const nodeVar = builder.getVarFromNode( this, null, type );
  1575. const propertyName = builder.getPropertyName( nodeVar );
  1576. builder.addLineFlowCode( `${ propertyName } = ${ snippet }`, this );
  1577. nodeData.snippet = snippet;
  1578. nodeData.propertyName = propertyName;
  1579. return builder.format( nodeData.propertyName, type, output );
  1580. }
  1581. }
  1582. return super.build( builder, output );
  1583. }
  1584. }
  1585. /**
  1586. * This module is part of the TSL core and usually not used in app level code.
  1587. * It represents a join operation during the shader generation process.
  1588. * For example in can compose/join two single floats into a `vec2` type.
  1589. *
  1590. * @augments TempNode
  1591. */
  1592. class JoinNode extends TempNode {
  1593. static get type() {
  1594. return 'JoinNode';
  1595. }
  1596. /**
  1597. * Constructs a new join node.
  1598. *
  1599. * @param {Array<Node>} nodes - An array of nodes that should be joined.
  1600. * @param {?string} [nodeType=null] - The node type.
  1601. */
  1602. constructor( nodes = [], nodeType = null ) {
  1603. super( nodeType );
  1604. /**
  1605. * An array of nodes that should be joined.
  1606. *
  1607. * @type {Array<Node>}
  1608. */
  1609. this.nodes = nodes;
  1610. }
  1611. /**
  1612. * This method is overwritten since the node type must be inferred from the
  1613. * joined data length if not explicitly defined.
  1614. *
  1615. * @param {NodeBuilder} builder - The current node builder.
  1616. * @return {string} The node type.
  1617. */
  1618. getNodeType( builder ) {
  1619. if ( this.nodeType !== null ) {
  1620. return builder.getVectorType( this.nodeType );
  1621. }
  1622. return builder.getTypeFromLength( this.nodes.reduce( ( count, cur ) => count + builder.getTypeLength( cur.getNodeType( builder ) ), 0 ) );
  1623. }
  1624. generate( builder, output ) {
  1625. const type = this.getNodeType( builder );
  1626. const maxLength = builder.getTypeLength( type );
  1627. const nodes = this.nodes;
  1628. const primitiveType = builder.getComponentType( type );
  1629. const snippetValues = [];
  1630. let length = 0;
  1631. for ( const input of nodes ) {
  1632. if ( length >= maxLength ) {
  1633. console.error( `THREE.TSL: Length of parameters exceeds maximum length of function '${ type }()' type.` );
  1634. break;
  1635. }
  1636. let inputType = input.getNodeType( builder );
  1637. let inputTypeLength = builder.getTypeLength( inputType );
  1638. let inputSnippet;
  1639. if ( length + inputTypeLength > maxLength ) {
  1640. console.error( `THREE.TSL: Length of '${ type }()' data exceeds maximum length of output type.` );
  1641. inputTypeLength = maxLength - length;
  1642. inputType = builder.getTypeFromLength( inputTypeLength );
  1643. }
  1644. length += inputTypeLength;
  1645. inputSnippet = input.build( builder, inputType );
  1646. const inputPrimitiveType = builder.getComponentType( inputType );
  1647. if ( inputPrimitiveType !== primitiveType ) {
  1648. inputSnippet = builder.format( inputSnippet, inputPrimitiveType, primitiveType );
  1649. }
  1650. snippetValues.push( inputSnippet );
  1651. }
  1652. const snippet = `${ builder.getType( type ) }( ${ snippetValues.join( ', ' ) } )`;
  1653. return builder.format( snippet, type, output );
  1654. }
  1655. }
  1656. const _stringVectorComponents = vectorComponents.join( '' );
  1657. /**
  1658. * This module is part of the TSL core and usually not used in app level code.
  1659. * `SplitNode` represents a property access operation which means it is
  1660. * used to implement any `.xyzw`, `.rgba` and `stpq` usage on node objects.
  1661. * For example:
  1662. * ```js
  1663. * const redValue = color.r;
  1664. * ```
  1665. *
  1666. * @augments Node
  1667. */
  1668. class SplitNode extends Node {
  1669. static get type() {
  1670. return 'SplitNode';
  1671. }
  1672. /**
  1673. * Constructs a new split node.
  1674. *
  1675. * @param {Node} node - The node that should be accessed.
  1676. * @param {string} [components='x'] - The components that should be accessed.
  1677. */
  1678. constructor( node, components = 'x' ) {
  1679. super();
  1680. /**
  1681. * The node that should be accessed.
  1682. *
  1683. * @type {Node}
  1684. */
  1685. this.node = node;
  1686. /**
  1687. * The components that should be accessed.
  1688. *
  1689. * @type {string}
  1690. */
  1691. this.components = components;
  1692. /**
  1693. * This flag can be used for type testing.
  1694. *
  1695. * @type {boolean}
  1696. * @readonly
  1697. * @default true
  1698. */
  1699. this.isSplitNode = true;
  1700. }
  1701. /**
  1702. * Returns the vector length which is computed based on the requested components.
  1703. *
  1704. * @return {number} The vector length.
  1705. */
  1706. getVectorLength() {
  1707. let vectorLength = this.components.length;
  1708. for ( const c of this.components ) {
  1709. vectorLength = Math.max( vectorComponents.indexOf( c ) + 1, vectorLength );
  1710. }
  1711. return vectorLength;
  1712. }
  1713. /**
  1714. * Returns the component type of the node's type.
  1715. *
  1716. * @param {NodeBuilder} builder - The current node builder.
  1717. * @return {string} The component type.
  1718. */
  1719. getComponentType( builder ) {
  1720. return builder.getComponentType( this.node.getNodeType( builder ) );
  1721. }
  1722. /**
  1723. * This method is overwritten since the node type is inferred from requested components.
  1724. *
  1725. * @param {NodeBuilder} builder - The current node builder.
  1726. * @return {string} The node type.
  1727. */
  1728. getNodeType( builder ) {
  1729. return builder.getTypeFromLength( this.components.length, this.getComponentType( builder ) );
  1730. }
  1731. generate( builder, output ) {
  1732. const node = this.node;
  1733. const nodeTypeLength = builder.getTypeLength( node.getNodeType( builder ) );
  1734. let snippet = null;
  1735. if ( nodeTypeLength > 1 ) {
  1736. let type = null;
  1737. const componentsLength = this.getVectorLength();
  1738. if ( componentsLength >= nodeTypeLength ) {
  1739. // needed expand the input node
  1740. type = builder.getTypeFromLength( this.getVectorLength(), this.getComponentType( builder ) );
  1741. }
  1742. const nodeSnippet = node.build( builder, type );
  1743. if ( this.components.length === nodeTypeLength && this.components === _stringVectorComponents.slice( 0, this.components.length ) ) {
  1744. // unnecessary swizzle
  1745. snippet = builder.format( nodeSnippet, type, output );
  1746. } else {
  1747. snippet = builder.format( `${nodeSnippet}.${this.components}`, this.getNodeType( builder ), output );
  1748. }
  1749. } else {
  1750. // ignore .components if .node returns float/integer
  1751. snippet = node.build( builder, output );
  1752. }
  1753. return snippet;
  1754. }
  1755. serialize( data ) {
  1756. super.serialize( data );
  1757. data.components = this.components;
  1758. }
  1759. deserialize( data ) {
  1760. super.deserialize( data );
  1761. this.components = data.components;
  1762. }
  1763. }
  1764. /**
  1765. * This module is part of the TSL core and usually not used in app level code.
  1766. * `SetNode` represents a set operation which means it is used to implement any
  1767. * `setXYZW()`, `setRGBA()` and `setSTPQ()` method invocations on node objects.
  1768. * For example:
  1769. * ```js
  1770. * materialLine.colorNode = color( 0, 0, 0 ).setR( float( 1 ) );
  1771. * ```
  1772. *
  1773. * @augments TempNode
  1774. */
  1775. class SetNode extends TempNode {
  1776. static get type() {
  1777. return 'SetNode';
  1778. }
  1779. /**
  1780. * Constructs a new set node.
  1781. *
  1782. * @param {Node} sourceNode - The node that should be updated.
  1783. * @param {string} components - The components that should be updated.
  1784. * @param {Node} targetNode - The value node.
  1785. */
  1786. constructor( sourceNode, components, targetNode ) {
  1787. super();
  1788. /**
  1789. * The node that should be updated.
  1790. *
  1791. * @type {Node}
  1792. */
  1793. this.sourceNode = sourceNode;
  1794. /**
  1795. * The components that should be updated.
  1796. *
  1797. * @type {string}
  1798. */
  1799. this.components = components;
  1800. /**
  1801. * The value node.
  1802. *
  1803. * @type {Node}
  1804. */
  1805. this.targetNode = targetNode;
  1806. }
  1807. /**
  1808. * This method is overwritten since the node type is inferred from {@link SetNode#sourceNode}.
  1809. *
  1810. * @param {NodeBuilder} builder - The current node builder.
  1811. * @return {string} The node type.
  1812. */
  1813. getNodeType( builder ) {
  1814. return this.sourceNode.getNodeType( builder );
  1815. }
  1816. generate( builder ) {
  1817. const { sourceNode, components, targetNode } = this;
  1818. const sourceType = this.getNodeType( builder );
  1819. const componentType = builder.getComponentType( targetNode.getNodeType( builder ) );
  1820. const targetType = builder.getTypeFromLength( components.length, componentType );
  1821. const targetSnippet = targetNode.build( builder, targetType );
  1822. const sourceSnippet = sourceNode.build( builder, sourceType );
  1823. const length = builder.getTypeLength( sourceType );
  1824. const snippetValues = [];
  1825. for ( let i = 0; i < length; i ++ ) {
  1826. const component = vectorComponents[ i ];
  1827. if ( component === components[ 0 ] ) {
  1828. snippetValues.push( targetSnippet );
  1829. i += components.length - 1;
  1830. } else {
  1831. snippetValues.push( sourceSnippet + '.' + component );
  1832. }
  1833. }
  1834. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1835. }
  1836. }
  1837. /**
  1838. * This module is part of the TSL core and usually not used in app level code.
  1839. * It represents a flip operation during the shader generation process
  1840. * meaning it flips normalized values with the following formula:
  1841. * ```
  1842. * x = 1 - x;
  1843. * ```
  1844. * `FlipNode` is internally used to implement any `flipXYZW()`, `flipRGBA()` and
  1845. * `flipSTPQ()` method invocations on node objects. For example:
  1846. * ```js
  1847. * uvNode = uvNode.flipY();
  1848. * ```
  1849. *
  1850. * @augments TempNode
  1851. */
  1852. class FlipNode extends TempNode {
  1853. static get type() {
  1854. return 'FlipNode';
  1855. }
  1856. /**
  1857. * Constructs a new flip node.
  1858. *
  1859. * @param {Node} sourceNode - The node which component(s) should be flipped.
  1860. * @param {string} components - The components that should be flipped e.g. `'x'` or `'xy'`.
  1861. */
  1862. constructor( sourceNode, components ) {
  1863. super();
  1864. /**
  1865. * The node which component(s) should be flipped.
  1866. *
  1867. * @type {Node}
  1868. */
  1869. this.sourceNode = sourceNode;
  1870. /**
  1871. * The components that should be flipped e.g. `'x'` or `'xy'`.
  1872. *
  1873. * @type {string}
  1874. */
  1875. this.components = components;
  1876. }
  1877. /**
  1878. * This method is overwritten since the node type is inferred from the source node.
  1879. *
  1880. * @param {NodeBuilder} builder - The current node builder.
  1881. * @return {string} The node type.
  1882. */
  1883. getNodeType( builder ) {
  1884. return this.sourceNode.getNodeType( builder );
  1885. }
  1886. generate( builder ) {
  1887. const { components, sourceNode } = this;
  1888. const sourceType = this.getNodeType( builder );
  1889. const sourceSnippet = sourceNode.build( builder );
  1890. const sourceCache = builder.getVarFromNode( this );
  1891. const sourceProperty = builder.getPropertyName( sourceCache );
  1892. builder.addLineFlowCode( sourceProperty + ' = ' + sourceSnippet, this );
  1893. const length = builder.getTypeLength( sourceType );
  1894. const snippetValues = [];
  1895. let componentIndex = 0;
  1896. for ( let i = 0; i < length; i ++ ) {
  1897. const component = vectorComponents[ i ];
  1898. if ( component === components[ componentIndex ] ) {
  1899. snippetValues.push( '1.0 - ' + ( sourceProperty + '.' + component ) );
  1900. componentIndex ++;
  1901. } else {
  1902. snippetValues.push( sourceProperty + '.' + component );
  1903. }
  1904. }
  1905. return `${ builder.getType( sourceType ) }( ${ snippetValues.join( ', ' ) } )`;
  1906. }
  1907. }
  1908. /**
  1909. * Base class for representing data input nodes.
  1910. *
  1911. * @augments Node
  1912. */
  1913. class InputNode extends Node {
  1914. static get type() {
  1915. return 'InputNode';
  1916. }
  1917. /**
  1918. * Constructs a new input node.
  1919. *
  1920. * @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).
  1921. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  1922. */
  1923. constructor( value, nodeType = null ) {
  1924. super( nodeType );
  1925. /**
  1926. * This flag can be used for type testing.
  1927. *
  1928. * @type {boolean}
  1929. * @readonly
  1930. * @default true
  1931. */
  1932. this.isInputNode = true;
  1933. /**
  1934. * The value of this node. This can be any JS primitive, functions, array buffers or even three.js objects (vector, matrices, colors).
  1935. *
  1936. * @type {any}
  1937. */
  1938. this.value = value;
  1939. /**
  1940. * The precision of the value in the shader.
  1941. *
  1942. * @type {?('low'|'medium'|'high')}
  1943. * @default null
  1944. */
  1945. this.precision = null;
  1946. }
  1947. getNodeType( /*builder*/ ) {
  1948. if ( this.nodeType === null ) {
  1949. return getValueType( this.value );
  1950. }
  1951. return this.nodeType;
  1952. }
  1953. /**
  1954. * Returns the input type of the node which is by default the node type. Derived modules
  1955. * might overwrite this method and use a fixed type or compute one analytically.
  1956. *
  1957. * A typical example for different input and node types are textures. The input type of a
  1958. * normal RGBA texture is `texture` whereas its node type is `vec4`.
  1959. *
  1960. * @param {NodeBuilder} builder - The current node builder.
  1961. * @return {string} The input type.
  1962. */
  1963. getInputType( builder ) {
  1964. return this.getNodeType( builder );
  1965. }
  1966. /**
  1967. * Sets the precision to the given value. The method can be
  1968. * overwritten in derived classes if the final precision must be computed
  1969. * analytically.
  1970. *
  1971. * @param {('low'|'medium'|'high')} precision - The precision of the input value in the shader.
  1972. * @return {InputNode} A reference to this node.
  1973. */
  1974. setPrecision( precision ) {
  1975. this.precision = precision;
  1976. return this;
  1977. }
  1978. serialize( data ) {
  1979. super.serialize( data );
  1980. data.value = this.value;
  1981. if ( this.value && this.value.toArray ) data.value = this.value.toArray();
  1982. data.valueType = getValueType( this.value );
  1983. data.nodeType = this.nodeType;
  1984. if ( data.valueType === 'ArrayBuffer' ) data.value = arrayBufferToBase64( data.value );
  1985. data.precision = this.precision;
  1986. }
  1987. deserialize( data ) {
  1988. super.deserialize( data );
  1989. this.nodeType = data.nodeType;
  1990. this.value = Array.isArray( data.value ) ? getValueFromType( data.valueType, ...data.value ) : data.value;
  1991. this.precision = data.precision || null;
  1992. if ( this.value && this.value.fromArray ) this.value = this.value.fromArray( data.value );
  1993. }
  1994. generate( /*builder, output*/ ) {
  1995. console.warn( 'Abstract function.' );
  1996. }
  1997. }
  1998. const _regNum = /float|u?int/;
  1999. /**
  2000. * Class for representing a constant value in the shader.
  2001. *
  2002. * @augments InputNode
  2003. */
  2004. class ConstNode extends InputNode {
  2005. static get type() {
  2006. return 'ConstNode';
  2007. }
  2008. /**
  2009. * Constructs a new input node.
  2010. *
  2011. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color).
  2012. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2013. */
  2014. constructor( value, nodeType = null ) {
  2015. super( value, nodeType );
  2016. /**
  2017. * This flag can be used for type testing.
  2018. *
  2019. * @type {boolean}
  2020. * @readonly
  2021. * @default true
  2022. */
  2023. this.isConstNode = true;
  2024. }
  2025. /**
  2026. * Generates the shader string of the value with the current node builder.
  2027. *
  2028. * @param {NodeBuilder} builder - The current node builder.
  2029. * @return {string} The generated value as a shader string.
  2030. */
  2031. generateConst( builder ) {
  2032. return builder.generateConst( this.getNodeType( builder ), this.value );
  2033. }
  2034. generate( builder, output ) {
  2035. const type = this.getNodeType( builder );
  2036. if ( _regNum.test( type ) && _regNum.test( output ) ) {
  2037. return builder.generateConst( output, this.value );
  2038. }
  2039. return builder.format( this.generateConst( builder ), type, output );
  2040. }
  2041. }
  2042. /**
  2043. * Base class for representing member access on an object-like
  2044. * node data structures.
  2045. *
  2046. * @augments Node
  2047. */
  2048. class MemberNode extends Node {
  2049. static get type() {
  2050. return 'MemberNode';
  2051. }
  2052. /**
  2053. * Constructs an array element node.
  2054. *
  2055. * @param {Node} node - The array-like node.
  2056. * @param {string} property - The property name.
  2057. */
  2058. constructor( node, property ) {
  2059. super();
  2060. /**
  2061. * The array-like node.
  2062. *
  2063. * @type {Node}
  2064. */
  2065. this.node = node;
  2066. /**
  2067. * The property name.
  2068. *
  2069. * @type {Node}
  2070. */
  2071. this.property = property;
  2072. /**
  2073. * This flag can be used for type testing.
  2074. *
  2075. * @type {boolean}
  2076. * @readonly
  2077. * @default true
  2078. */
  2079. this.isMemberNode = true;
  2080. }
  2081. getNodeType( builder ) {
  2082. return this.node.getMemberType( builder, this.property );
  2083. }
  2084. generate( builder ) {
  2085. const propertyName = this.node.build( builder );
  2086. return propertyName + '.' + this.property;
  2087. }
  2088. }
  2089. let currentStack = null;
  2090. const NodeElements = new Map();
  2091. function addMethodChaining( name, nodeElement ) {
  2092. if ( NodeElements.has( name ) ) {
  2093. console.warn( `THREE.TSL: Redefinition of method chaining '${ name }'.` );
  2094. return;
  2095. }
  2096. if ( typeof nodeElement !== 'function' ) throw new Error( `THREE.TSL: Node element ${ name } is not a function` );
  2097. NodeElements.set( name, nodeElement );
  2098. }
  2099. const parseSwizzle = ( props ) => props.replace( /r|s/g, 'x' ).replace( /g|t/g, 'y' ).replace( /b|p/g, 'z' ).replace( /a|q/g, 'w' );
  2100. const parseSwizzleAndSort = ( props ) => parseSwizzle( props ).split( '' ).sort().join( '' );
  2101. const shaderNodeHandler = {
  2102. setup( NodeClosure, params ) {
  2103. const inputs = params.shift();
  2104. return NodeClosure( nodeObjects( inputs ), ...params );
  2105. },
  2106. get( node, prop, nodeObj ) {
  2107. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2108. if ( node.isStackNode !== true && prop === 'assign' ) {
  2109. return ( ...params ) => {
  2110. currentStack.assign( nodeObj, ...params );
  2111. return nodeObj;
  2112. };
  2113. } else if ( NodeElements.has( prop ) ) {
  2114. const nodeElement = NodeElements.get( prop );
  2115. return node.isStackNode ? ( ...params ) => nodeObj.add( nodeElement( ...params ) ) : ( ...params ) => nodeElement( nodeObj, ...params );
  2116. } else if ( prop === 'self' ) {
  2117. return node;
  2118. } else if ( prop.endsWith( 'Assign' ) && NodeElements.has( prop.slice( 0, prop.length - 'Assign'.length ) ) ) {
  2119. const nodeElement = NodeElements.get( prop.slice( 0, prop.length - 'Assign'.length ) );
  2120. return node.isStackNode ? ( ...params ) => nodeObj.assign( params[ 0 ], nodeElement( ...params ) ) : ( ...params ) => nodeObj.assign( nodeElement( nodeObj, ...params ) );
  2121. } else if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true ) {
  2122. // accessing properties ( swizzle )
  2123. prop = parseSwizzle( prop );
  2124. return nodeObject( new SplitNode( nodeObj, prop ) );
  2125. } else if ( /^set[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2126. // set properties ( swizzle ) and sort to xyzw sequence
  2127. prop = parseSwizzleAndSort( prop.slice( 3 ).toLowerCase() );
  2128. return ( value ) => nodeObject( new SetNode( node, prop, nodeObject( value ) ) );
  2129. } else if ( /^flip[XYZWRGBASTPQ]{1,4}$/.test( prop ) === true ) {
  2130. // set properties ( swizzle ) and sort to xyzw sequence
  2131. prop = parseSwizzleAndSort( prop.slice( 4 ).toLowerCase() );
  2132. return () => nodeObject( new FlipNode( nodeObject( node ), prop ) );
  2133. } else if ( prop === 'width' || prop === 'height' || prop === 'depth' ) {
  2134. // accessing property
  2135. if ( prop === 'width' ) prop = 'x';
  2136. else if ( prop === 'height' ) prop = 'y';
  2137. else if ( prop === 'depth' ) prop = 'z';
  2138. return nodeObject( new SplitNode( node, prop ) );
  2139. } else if ( /^\d+$/.test( prop ) === true ) {
  2140. // accessing array
  2141. return nodeObject( new ArrayElementNode( nodeObj, new ConstNode( Number( prop ), 'uint' ) ) );
  2142. } else if ( /^get$/.test( prop ) === true ) {
  2143. // accessing properties
  2144. return ( value ) => nodeObject( new MemberNode( nodeObj, value ) );
  2145. }
  2146. }
  2147. return Reflect.get( node, prop, nodeObj );
  2148. },
  2149. set( node, prop, value, nodeObj ) {
  2150. if ( typeof prop === 'string' && node[ prop ] === undefined ) {
  2151. // setting properties
  2152. if ( /^[xyzwrgbastpq]{1,4}$/.test( prop ) === true || prop === 'width' || prop === 'height' || prop === 'depth' || /^\d+$/.test( prop ) === true ) {
  2153. nodeObj[ prop ].assign( value );
  2154. return true;
  2155. }
  2156. }
  2157. return Reflect.set( node, prop, value, nodeObj );
  2158. }
  2159. };
  2160. const nodeObjectsCacheMap = new WeakMap();
  2161. const nodeBuilderFunctionsCacheMap = new WeakMap();
  2162. const ShaderNodeObject = function ( obj, altType = null ) {
  2163. const type = getValueType( obj );
  2164. if ( type === 'node' ) {
  2165. let nodeObject = nodeObjectsCacheMap.get( obj );
  2166. if ( nodeObject === undefined ) {
  2167. nodeObject = new Proxy( obj, shaderNodeHandler );
  2168. nodeObjectsCacheMap.set( obj, nodeObject );
  2169. nodeObjectsCacheMap.set( nodeObject, nodeObject );
  2170. }
  2171. return nodeObject;
  2172. } else if ( ( altType === null && ( type === 'float' || type === 'boolean' ) ) || ( type && type !== 'shader' && type !== 'string' ) ) {
  2173. return nodeObject( getConstNode( obj, altType ) );
  2174. } else if ( type === 'shader' ) {
  2175. return obj.isFn ? obj : Fn( obj );
  2176. }
  2177. return obj;
  2178. };
  2179. const ShaderNodeObjects = function ( objects, altType = null ) {
  2180. for ( const name in objects ) {
  2181. objects[ name ] = nodeObject( objects[ name ], altType );
  2182. }
  2183. return objects;
  2184. };
  2185. const ShaderNodeArray = function ( array, altType = null ) {
  2186. const len = array.length;
  2187. for ( let i = 0; i < len; i ++ ) {
  2188. array[ i ] = nodeObject( array[ i ], altType );
  2189. }
  2190. return array;
  2191. };
  2192. const ShaderNodeProxy = function ( NodeClass, scope = null, factor = null, settings = null ) {
  2193. const assignNode = ( node ) => nodeObject( settings !== null ? Object.assign( node, settings ) : node );
  2194. let fn, name = scope, minParams, maxParams;
  2195. function verifyParamsLimit( params ) {
  2196. let tslName;
  2197. if ( name ) tslName = /[a-z]/i.test( name ) ? name + '()' : name;
  2198. else tslName = NodeClass.type;
  2199. if ( minParams !== undefined && params.length < minParams ) {
  2200. console.error( `THREE.TSL: "${ tslName }" parameter length is less than minimum required.` );
  2201. return params.concat( new Array( minParams - params.length ).fill( 0 ) );
  2202. } else if ( maxParams !== undefined && params.length > maxParams ) {
  2203. console.error( `THREE.TSL: "${ tslName }" parameter length exceeds limit.` );
  2204. return params.slice( 0, maxParams );
  2205. }
  2206. return params;
  2207. }
  2208. if ( scope === null ) {
  2209. fn = ( ...params ) => {
  2210. return assignNode( new NodeClass( ...nodeArray( verifyParamsLimit( params ) ) ) );
  2211. };
  2212. } else if ( factor !== null ) {
  2213. factor = nodeObject( factor );
  2214. fn = ( ...params ) => {
  2215. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ), factor ) );
  2216. };
  2217. } else {
  2218. fn = ( ...params ) => {
  2219. return assignNode( new NodeClass( scope, ...nodeArray( verifyParamsLimit( params ) ) ) );
  2220. };
  2221. }
  2222. fn.setParameterLength = ( ...params ) => {
  2223. if ( params.length === 1 ) minParams = maxParams = params[ 0 ];
  2224. else if ( params.length === 2 ) [ minParams, maxParams ] = params;
  2225. return fn;
  2226. };
  2227. fn.setName = ( value ) => {
  2228. name = value;
  2229. return fn;
  2230. };
  2231. return fn;
  2232. };
  2233. const ShaderNodeImmutable = function ( NodeClass, ...params ) {
  2234. return nodeObject( new NodeClass( ...nodeArray( params ) ) );
  2235. };
  2236. class ShaderCallNodeInternal extends Node {
  2237. constructor( shaderNode, inputNodes ) {
  2238. super();
  2239. this.shaderNode = shaderNode;
  2240. this.inputNodes = inputNodes;
  2241. this.isShaderCallNodeInternal = true;
  2242. }
  2243. getNodeType( builder ) {
  2244. return this.shaderNode.nodeType || this.getOutputNode( builder ).getNodeType( builder );
  2245. }
  2246. getMemberType( builder, name ) {
  2247. return this.getOutputNode( builder ).getMemberType( builder, name );
  2248. }
  2249. call( builder ) {
  2250. const { shaderNode, inputNodes } = this;
  2251. const properties = builder.getNodeProperties( shaderNode );
  2252. const onceNS = shaderNode.namespace && shaderNode.namespace === builder.namespace ? builder.getNamespace( 'once' ) : 'once';
  2253. if ( properties[ onceNS ] ) {
  2254. return properties[ onceNS ];
  2255. }
  2256. //
  2257. let result = null;
  2258. if ( shaderNode.layout ) {
  2259. let functionNodesCacheMap = nodeBuilderFunctionsCacheMap.get( builder.constructor );
  2260. if ( functionNodesCacheMap === undefined ) {
  2261. functionNodesCacheMap = new WeakMap();
  2262. nodeBuilderFunctionsCacheMap.set( builder.constructor, functionNodesCacheMap );
  2263. }
  2264. let functionNode = functionNodesCacheMap.get( shaderNode );
  2265. if ( functionNode === undefined ) {
  2266. functionNode = nodeObject( builder.buildFunctionNode( shaderNode ) );
  2267. functionNodesCacheMap.set( shaderNode, functionNode );
  2268. }
  2269. builder.addInclude( functionNode );
  2270. result = nodeObject( functionNode.call( inputNodes ) );
  2271. } else {
  2272. const jsFunc = shaderNode.jsFunc;
  2273. const outputNode = inputNodes !== null || jsFunc.length > 1 ? jsFunc( inputNodes || [], builder ) : jsFunc( builder );
  2274. result = nodeObject( outputNode );
  2275. }
  2276. if ( shaderNode.once ) {
  2277. properties[ onceNS ] = result;
  2278. }
  2279. return result;
  2280. }
  2281. setupOutput( builder ) {
  2282. builder.addStack();
  2283. builder.stack.outputNode = this.call( builder );
  2284. return builder.removeStack();
  2285. }
  2286. getOutputNode( builder ) {
  2287. const properties = builder.getNodeProperties( this );
  2288. const outputNamespace = builder.getOutputNamespace();
  2289. properties[ outputNamespace ] = properties[ outputNamespace ] || this.setupOutput( builder );
  2290. return properties[ outputNamespace ];
  2291. }
  2292. build( builder, output = null ) {
  2293. let result = null;
  2294. const buildStage = builder.getBuildStage();
  2295. const properties = builder.getNodeProperties( this );
  2296. const outputNamespace = builder.getOutputNamespace();
  2297. const outputNode = this.getOutputNode( builder );
  2298. if ( buildStage === 'setup' ) {
  2299. const initializedNamespace = builder.getNamespace( 'initialized' );
  2300. if ( properties[ initializedNamespace ] !== true ) {
  2301. properties[ initializedNamespace ] = true;
  2302. properties[ outputNamespace ] = this.getOutputNode( builder );
  2303. properties[ outputNamespace ].build( builder );
  2304. }
  2305. result = properties[ outputNamespace ];
  2306. } else if ( buildStage === 'analyze' ) {
  2307. outputNode.build( builder, output );
  2308. } else if ( buildStage === 'generate' ) {
  2309. result = outputNode.build( builder, output ) || '';
  2310. }
  2311. return result;
  2312. }
  2313. }
  2314. class ShaderNodeInternal extends Node {
  2315. constructor( jsFunc, nodeType ) {
  2316. super( nodeType );
  2317. this.jsFunc = jsFunc;
  2318. this.layout = null;
  2319. this.global = true;
  2320. this.once = false;
  2321. this.namespace = null;
  2322. }
  2323. setLayout( layout ) {
  2324. this.layout = layout;
  2325. return this;
  2326. }
  2327. call( inputs = null ) {
  2328. nodeObjects( inputs );
  2329. return nodeObject( new ShaderCallNodeInternal( this, inputs ) );
  2330. }
  2331. setup() {
  2332. return this.call();
  2333. }
  2334. }
  2335. const bools = [ false, true ];
  2336. const uints = [ 0, 1, 2, 3 ];
  2337. const ints = [ -1, -2 ];
  2338. 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 ];
  2339. const boolsCacheMap = new Map();
  2340. for ( const bool of bools ) boolsCacheMap.set( bool, new ConstNode( bool ) );
  2341. const uintsCacheMap = new Map();
  2342. for ( const uint of uints ) uintsCacheMap.set( uint, new ConstNode( uint, 'uint' ) );
  2343. const intsCacheMap = new Map( [ ...uintsCacheMap ].map( el => new ConstNode( el.value, 'int' ) ) );
  2344. for ( const int of ints ) intsCacheMap.set( int, new ConstNode( int, 'int' ) );
  2345. const floatsCacheMap = new Map( [ ...intsCacheMap ].map( el => new ConstNode( el.value ) ) );
  2346. for ( const float of floats ) floatsCacheMap.set( float, new ConstNode( float ) );
  2347. for ( const float of floats ) floatsCacheMap.set( - float, new ConstNode( - float ) );
  2348. const cacheMaps = { bool: boolsCacheMap, uint: uintsCacheMap, ints: intsCacheMap, float: floatsCacheMap };
  2349. const constNodesCacheMap = new Map( [ ...boolsCacheMap, ...floatsCacheMap ] );
  2350. const getConstNode = ( value, type ) => {
  2351. if ( constNodesCacheMap.has( value ) ) {
  2352. return constNodesCacheMap.get( value );
  2353. } else if ( value.isNode === true ) {
  2354. return value;
  2355. } else {
  2356. return new ConstNode( value, type );
  2357. }
  2358. };
  2359. const safeGetNodeType = ( node ) => {
  2360. try {
  2361. return node.getNodeType();
  2362. } catch ( _ ) {
  2363. return undefined;
  2364. }
  2365. };
  2366. const ConvertType = function ( type, cacheMap = null ) {
  2367. return ( ...params ) => {
  2368. if ( params.length === 0 || ( ! [ 'bool', 'float', 'int', 'uint' ].includes( type ) && params.every( param => typeof param !== 'object' ) ) ) {
  2369. params = [ getValueFromType( type, ...params ) ];
  2370. }
  2371. if ( params.length === 1 && cacheMap !== null && cacheMap.has( params[ 0 ] ) ) {
  2372. return nodeObject( cacheMap.get( params[ 0 ] ) );
  2373. }
  2374. if ( params.length === 1 ) {
  2375. const node = getConstNode( params[ 0 ], type );
  2376. if ( safeGetNodeType( node ) === type ) return nodeObject( node );
  2377. return nodeObject( new ConvertNode( node, type ) );
  2378. }
  2379. const nodes = params.map( param => getConstNode( param ) );
  2380. return nodeObject( new JoinNode( nodes, type ) );
  2381. };
  2382. };
  2383. // exports
  2384. const defined = ( v ) => typeof v === 'object' && v !== null ? v.value : v; // TODO: remove boolean conversion and defined function
  2385. // utils
  2386. const getConstNodeType = ( value ) => ( value !== undefined && value !== null ) ? ( value.nodeType || value.convertTo || ( typeof value === 'string' ? value : null ) ) : null;
  2387. // shader node base
  2388. function ShaderNode( jsFunc, nodeType ) {
  2389. return new Proxy( new ShaderNodeInternal( jsFunc, nodeType ), shaderNodeHandler );
  2390. }
  2391. const nodeObject = ( val, altType = null ) => /* new */ ShaderNodeObject( val, altType );
  2392. const nodeObjects = ( val, altType = null ) => new ShaderNodeObjects( val, altType );
  2393. const nodeArray = ( val, altType = null ) => new ShaderNodeArray( val, altType );
  2394. const nodeProxy = ( ...params ) => new ShaderNodeProxy( ...params );
  2395. const nodeImmutable = ( ...params ) => new ShaderNodeImmutable( ...params );
  2396. let fnId = 0;
  2397. const Fn = ( jsFunc, layout = null ) => {
  2398. let nodeType = null;
  2399. if ( layout !== null ) {
  2400. if ( typeof layout === 'object' ) {
  2401. nodeType = layout.return;
  2402. } else {
  2403. if ( typeof layout === 'string' ) {
  2404. nodeType = layout;
  2405. } else {
  2406. console.error( 'THREE.TSL: Invalid layout type.' );
  2407. }
  2408. layout = null;
  2409. }
  2410. }
  2411. const shaderNode = new ShaderNode( jsFunc, nodeType );
  2412. const fn = ( ...params ) => {
  2413. let inputs;
  2414. nodeObjects( params );
  2415. const isArrayAsParameter = params[ 0 ] && ( params[ 0 ].isNode || Object.getPrototypeOf( params[ 0 ] ) !== Object.prototype );
  2416. if ( isArrayAsParameter ) {
  2417. inputs = [ ...params ];
  2418. } else {
  2419. inputs = params[ 0 ];
  2420. }
  2421. const fnCall = shaderNode.call( inputs );
  2422. if ( nodeType === 'void' ) fnCall.toStack();
  2423. return fnCall;
  2424. };
  2425. fn.shaderNode = shaderNode;
  2426. fn.id = shaderNode.id;
  2427. fn.isFn = true;
  2428. fn.getNodeType = ( ...params ) => shaderNode.getNodeType( ...params );
  2429. fn.getCacheKey = ( ...params ) => shaderNode.getCacheKey( ...params );
  2430. fn.setLayout = ( layout ) => {
  2431. shaderNode.setLayout( layout );
  2432. return fn;
  2433. };
  2434. fn.once = ( namespace = null ) => {
  2435. shaderNode.once = true;
  2436. shaderNode.namespace = namespace;
  2437. return fn;
  2438. };
  2439. if ( layout !== null ) {
  2440. if ( typeof layout.inputs !== 'object' ) {
  2441. const fullLayout = {
  2442. name: 'fn' + fnId ++,
  2443. type: nodeType,
  2444. inputs: []
  2445. };
  2446. for ( const name in layout ) {
  2447. if ( name === 'return' ) continue;
  2448. fullLayout.inputs.push( {
  2449. name: name,
  2450. type: layout[ name ]
  2451. } );
  2452. }
  2453. layout = fullLayout;
  2454. }
  2455. fn.setLayout( layout );
  2456. }
  2457. return fn;
  2458. };
  2459. //
  2460. const setCurrentStack = ( stack ) => {
  2461. currentStack = stack;
  2462. };
  2463. const getCurrentStack = () => currentStack;
  2464. /**
  2465. * Represent a conditional node using if/else statements.
  2466. *
  2467. * ```js
  2468. * If( condition, function )
  2469. * .ElseIf( condition, function )
  2470. * .Else( function )
  2471. * ```
  2472. * @tsl
  2473. * @function
  2474. * @param {...any} params - The parameters for the conditional node.
  2475. * @returns {StackNode} The conditional node.
  2476. */
  2477. const If = ( ...params ) => currentStack.If( ...params );
  2478. /**
  2479. * Represent a conditional node using switch/case statements.
  2480. *
  2481. * ```js
  2482. * Switch( value )
  2483. * .Case( 1, function )
  2484. * .Case( 2, 3, 4, function )
  2485. * .Default( function )
  2486. * ```
  2487. * @tsl
  2488. * @function
  2489. * @param {...any} params - The parameters for the conditional node.
  2490. * @returns {StackNode} The conditional node.
  2491. */
  2492. const Switch = ( ...params ) => currentStack.Switch( ...params );
  2493. /**
  2494. * Add the given node to the current stack.
  2495. *
  2496. * @param {Node} node - The node to add.
  2497. * @returns {Node} The node that was added to the stack.
  2498. */
  2499. function Stack( node ) {
  2500. if ( currentStack ) currentStack.add( node );
  2501. return node;
  2502. }
  2503. addMethodChaining( 'toStack', Stack );
  2504. // types
  2505. const color = new ConvertType( 'color' );
  2506. const float = new ConvertType( 'float', cacheMaps.float );
  2507. const int = new ConvertType( 'int', cacheMaps.ints );
  2508. const uint = new ConvertType( 'uint', cacheMaps.uint );
  2509. const bool = new ConvertType( 'bool', cacheMaps.bool );
  2510. const vec2 = new ConvertType( 'vec2' );
  2511. const ivec2 = new ConvertType( 'ivec2' );
  2512. const uvec2 = new ConvertType( 'uvec2' );
  2513. const bvec2 = new ConvertType( 'bvec2' );
  2514. const vec3 = new ConvertType( 'vec3' );
  2515. const ivec3 = new ConvertType( 'ivec3' );
  2516. const uvec3 = new ConvertType( 'uvec3' );
  2517. const bvec3 = new ConvertType( 'bvec3' );
  2518. const vec4 = new ConvertType( 'vec4' );
  2519. const ivec4 = new ConvertType( 'ivec4' );
  2520. const uvec4 = new ConvertType( 'uvec4' );
  2521. const bvec4 = new ConvertType( 'bvec4' );
  2522. const mat2 = new ConvertType( 'mat2' );
  2523. const mat3 = new ConvertType( 'mat3' );
  2524. const mat4 = new ConvertType( 'mat4' );
  2525. const string = ( value = '' ) => nodeObject( new ConstNode( value, 'string' ) );
  2526. const arrayBuffer = ( value ) => nodeObject( new ConstNode( value, 'ArrayBuffer' ) );
  2527. addMethodChaining( 'toColor', color );
  2528. addMethodChaining( 'toFloat', float );
  2529. addMethodChaining( 'toInt', int );
  2530. addMethodChaining( 'toUint', uint );
  2531. addMethodChaining( 'toBool', bool );
  2532. addMethodChaining( 'toVec2', vec2 );
  2533. addMethodChaining( 'toIVec2', ivec2 );
  2534. addMethodChaining( 'toUVec2', uvec2 );
  2535. addMethodChaining( 'toBVec2', bvec2 );
  2536. addMethodChaining( 'toVec3', vec3 );
  2537. addMethodChaining( 'toIVec3', ivec3 );
  2538. addMethodChaining( 'toUVec3', uvec3 );
  2539. addMethodChaining( 'toBVec3', bvec3 );
  2540. addMethodChaining( 'toVec4', vec4 );
  2541. addMethodChaining( 'toIVec4', ivec4 );
  2542. addMethodChaining( 'toUVec4', uvec4 );
  2543. addMethodChaining( 'toBVec4', bvec4 );
  2544. addMethodChaining( 'toMat2', mat2 );
  2545. addMethodChaining( 'toMat3', mat3 );
  2546. addMethodChaining( 'toMat4', mat4 );
  2547. // basic nodes
  2548. const element = /*@__PURE__*/ nodeProxy( ArrayElementNode ).setParameterLength( 2 );
  2549. const convert = ( node, types ) => nodeObject( new ConvertNode( nodeObject( node ), types ) );
  2550. const split = ( node, channels ) => nodeObject( new SplitNode( nodeObject( node ), channels ) );
  2551. addMethodChaining( 'element', element );
  2552. addMethodChaining( 'convert', convert );
  2553. // deprecated
  2554. /**
  2555. * @tsl
  2556. * @function
  2557. * @deprecated since r176. Use {@link Stack} instead.
  2558. *
  2559. * @param {Node} node - The node to add.
  2560. * @returns {Function}
  2561. */
  2562. const append = ( node ) => { // @deprecated, r176
  2563. console.warn( 'THREE.TSL: append() has been renamed to Stack().' );
  2564. return Stack( node );
  2565. };
  2566. addMethodChaining( 'append', ( node ) => { // @deprecated, r176
  2567. console.warn( 'THREE.TSL: .append() has been renamed to .toStack().' );
  2568. return Stack( node );
  2569. } );
  2570. /**
  2571. * @tsl
  2572. * @function
  2573. * @deprecated since r168. Use {@link Fn} instead.
  2574. *
  2575. * @param {...any} params
  2576. * @returns {Function}
  2577. */
  2578. const tslFn = ( ...params ) => { // @deprecated, r168
  2579. console.warn( 'THREE.TSL: tslFn() has been renamed to Fn().' );
  2580. return Fn( ...params );
  2581. };
  2582. /**
  2583. * This class represents a shader property. It can be used
  2584. * to explicitly define a property and assign a value to it.
  2585. *
  2586. * ```js
  2587. * const threshold = property( 'float', 'threshold' ).assign( THRESHOLD );
  2588. *```
  2589. * `PropertyNode` is used by the engine to predefined common material properties
  2590. * for TSL code.
  2591. *
  2592. * @augments Node
  2593. */
  2594. class PropertyNode extends Node {
  2595. static get type() {
  2596. return 'PropertyNode';
  2597. }
  2598. /**
  2599. * Constructs a new property node.
  2600. *
  2601. * @param {string} nodeType - The type of the node.
  2602. * @param {?string} [name=null] - The name of the property in the shader.
  2603. * @param {boolean} [varying=false] - Whether this property is a varying or not.
  2604. */
  2605. constructor( nodeType, name = null, varying = false ) {
  2606. super( nodeType );
  2607. /**
  2608. * The name of the property in the shader. If no name is defined,
  2609. * the node system auto-generates one.
  2610. *
  2611. * @type {?string}
  2612. * @default null
  2613. */
  2614. this.name = name;
  2615. /**
  2616. * Whether this property is a varying or not.
  2617. *
  2618. * @type {boolean}
  2619. * @default false
  2620. */
  2621. this.varying = varying;
  2622. /**
  2623. * This flag can be used for type testing.
  2624. *
  2625. * @type {boolean}
  2626. * @readonly
  2627. * @default true
  2628. */
  2629. this.isPropertyNode = true;
  2630. /**
  2631. * This flag is used for global cache.
  2632. *
  2633. * @type {boolean}
  2634. * @default true
  2635. */
  2636. this.global = true;
  2637. }
  2638. getHash( builder ) {
  2639. return this.name || super.getHash( builder );
  2640. }
  2641. generate( builder ) {
  2642. let nodeVar;
  2643. if ( this.varying === true ) {
  2644. nodeVar = builder.getVaryingFromNode( this, this.name );
  2645. nodeVar.needsInterpolation = true;
  2646. } else {
  2647. nodeVar = builder.getVarFromNode( this, this.name );
  2648. }
  2649. return builder.getPropertyName( nodeVar );
  2650. }
  2651. }
  2652. /**
  2653. * TSL function for creating a property node.
  2654. *
  2655. * @tsl
  2656. * @function
  2657. * @param {string} type - The type of the node.
  2658. * @param {?string} [name=null] - The name of the property in the shader.
  2659. * @returns {PropertyNode}
  2660. */
  2661. const property = ( type, name ) => nodeObject( new PropertyNode( type, name ) );
  2662. /**
  2663. * TSL function for creating a varying property node.
  2664. *
  2665. * @tsl
  2666. * @function
  2667. * @param {string} type - The type of the node.
  2668. * @param {?string} [name=null] - The name of the varying in the shader.
  2669. * @returns {PropertyNode}
  2670. */
  2671. const varyingProperty = ( type, name ) => nodeObject( new PropertyNode( type, name, true ) );
  2672. /**
  2673. * TSL object that represents the shader variable `DiffuseColor`.
  2674. *
  2675. * @tsl
  2676. * @type {PropertyNode<vec4>}
  2677. */
  2678. const diffuseColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'DiffuseColor' );
  2679. /**
  2680. * TSL object that represents the shader variable `EmissiveColor`.
  2681. *
  2682. * @tsl
  2683. * @type {PropertyNode<vec3>}
  2684. */
  2685. const emissive = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'EmissiveColor' );
  2686. /**
  2687. * TSL object that represents the shader variable `Roughness`.
  2688. *
  2689. * @tsl
  2690. * @type {PropertyNode<float>}
  2691. */
  2692. const roughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Roughness' );
  2693. /**
  2694. * TSL object that represents the shader variable `Metalness`.
  2695. *
  2696. * @tsl
  2697. * @type {PropertyNode<float>}
  2698. */
  2699. const metalness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Metalness' );
  2700. /**
  2701. * TSL object that represents the shader variable `Clearcoat`.
  2702. *
  2703. * @tsl
  2704. * @type {PropertyNode<float>}
  2705. */
  2706. const clearcoat = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Clearcoat' );
  2707. /**
  2708. * TSL object that represents the shader variable `ClearcoatRoughness`.
  2709. *
  2710. * @tsl
  2711. * @type {PropertyNode<float>}
  2712. */
  2713. const clearcoatRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'ClearcoatRoughness' );
  2714. /**
  2715. * TSL object that represents the shader variable `Sheen`.
  2716. *
  2717. * @tsl
  2718. * @type {PropertyNode<vec3>}
  2719. */
  2720. const sheen = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'Sheen' );
  2721. /**
  2722. * TSL object that represents the shader variable `SheenRoughness`.
  2723. *
  2724. * @tsl
  2725. * @type {PropertyNode<float>}
  2726. */
  2727. const sheenRoughness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SheenRoughness' );
  2728. /**
  2729. * TSL object that represents the shader variable `Iridescence`.
  2730. *
  2731. * @tsl
  2732. * @type {PropertyNode<float>}
  2733. */
  2734. const iridescence = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Iridescence' );
  2735. /**
  2736. * TSL object that represents the shader variable `IridescenceIOR`.
  2737. *
  2738. * @tsl
  2739. * @type {PropertyNode<float>}
  2740. */
  2741. const iridescenceIOR = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceIOR' );
  2742. /**
  2743. * TSL object that represents the shader variable `IridescenceThickness`.
  2744. *
  2745. * @tsl
  2746. * @type {PropertyNode<float>}
  2747. */
  2748. const iridescenceThickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IridescenceThickness' );
  2749. /**
  2750. * TSL object that represents the shader variable `AlphaT`.
  2751. *
  2752. * @tsl
  2753. * @type {PropertyNode<float>}
  2754. */
  2755. const alphaT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AlphaT' );
  2756. /**
  2757. * TSL object that represents the shader variable `Anisotropy`.
  2758. *
  2759. * @tsl
  2760. * @type {PropertyNode<float>}
  2761. */
  2762. const anisotropy = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Anisotropy' );
  2763. /**
  2764. * TSL object that represents the shader variable `AnisotropyT`.
  2765. *
  2766. * @tsl
  2767. * @type {PropertyNode<vec3>}
  2768. */
  2769. const anisotropyT = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyT' );
  2770. /**
  2771. * TSL object that represents the shader variable `AnisotropyB`.
  2772. *
  2773. * @tsl
  2774. * @type {PropertyNode<vec3>}
  2775. */
  2776. const anisotropyB = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec3', 'AnisotropyB' );
  2777. /**
  2778. * TSL object that represents the shader variable `SpecularColor`.
  2779. *
  2780. * @tsl
  2781. * @type {PropertyNode<color>}
  2782. */
  2783. const specularColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'SpecularColor' );
  2784. /**
  2785. * TSL object that represents the shader variable `SpecularF90`.
  2786. *
  2787. * @tsl
  2788. * @type {PropertyNode<float>}
  2789. */
  2790. const specularF90 = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'SpecularF90' );
  2791. /**
  2792. * TSL object that represents the shader variable `Shininess`.
  2793. *
  2794. * @tsl
  2795. * @type {PropertyNode<float>}
  2796. */
  2797. const shininess = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Shininess' );
  2798. /**
  2799. * TSL object that represents the shader variable `Output`.
  2800. *
  2801. * @tsl
  2802. * @type {PropertyNode<vec4>}
  2803. */
  2804. const output = /*@__PURE__*/ nodeImmutable( PropertyNode, 'vec4', 'Output' );
  2805. /**
  2806. * TSL object that represents the shader variable `dashSize`.
  2807. *
  2808. * @tsl
  2809. * @type {PropertyNode<float>}
  2810. */
  2811. const dashSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'dashSize' );
  2812. /**
  2813. * TSL object that represents the shader variable `gapSize`.
  2814. *
  2815. * @tsl
  2816. * @type {PropertyNode<float>}
  2817. */
  2818. const gapSize = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'gapSize' );
  2819. /**
  2820. * TSL object that represents the shader variable `pointWidth`.
  2821. *
  2822. * @tsl
  2823. * @type {PropertyNode<float>}
  2824. */
  2825. const pointWidth = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'pointWidth' );
  2826. /**
  2827. * TSL object that represents the shader variable `IOR`.
  2828. *
  2829. * @tsl
  2830. * @type {PropertyNode<float>}
  2831. */
  2832. const ior = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'IOR' );
  2833. /**
  2834. * TSL object that represents the shader variable `Transmission`.
  2835. *
  2836. * @tsl
  2837. * @type {PropertyNode<float>}
  2838. */
  2839. const transmission = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Transmission' );
  2840. /**
  2841. * TSL object that represents the shader variable `Thickness`.
  2842. *
  2843. * @tsl
  2844. * @type {PropertyNode<float>}
  2845. */
  2846. const thickness = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Thickness' );
  2847. /**
  2848. * TSL object that represents the shader variable `AttenuationDistance`.
  2849. *
  2850. * @tsl
  2851. * @type {PropertyNode<float>}
  2852. */
  2853. const attenuationDistance = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'AttenuationDistance' );
  2854. /**
  2855. * TSL object that represents the shader variable `AttenuationColor`.
  2856. *
  2857. * @tsl
  2858. * @type {PropertyNode<color>}
  2859. */
  2860. const attenuationColor = /*@__PURE__*/ nodeImmutable( PropertyNode, 'color', 'AttenuationColor' );
  2861. /**
  2862. * TSL object that represents the shader variable `Dispersion`.
  2863. *
  2864. * @tsl
  2865. * @type {PropertyNode<float>}
  2866. */
  2867. const dispersion = /*@__PURE__*/ nodeImmutable( PropertyNode, 'float', 'Dispersion' );
  2868. /**
  2869. * This node can be used to group single instances of {@link UniformNode}
  2870. * and manage them as a uniform buffer.
  2871. *
  2872. * In most cases, the predefined nodes `objectGroup`, `renderGroup` and `frameGroup`
  2873. * will be used when defining the {@link UniformNode#groupNode} property.
  2874. *
  2875. * - `objectGroup`: Uniform buffer per object.
  2876. * - `renderGroup`: Shared uniform buffer, updated once per render call.
  2877. * - `frameGroup`: Shared uniform buffer, updated once per frame.
  2878. *
  2879. * @augments Node
  2880. */
  2881. class UniformGroupNode extends Node {
  2882. static get type() {
  2883. return 'UniformGroupNode';
  2884. }
  2885. /**
  2886. * Constructs a new uniform group node.
  2887. *
  2888. * @param {string} name - The name of the uniform group node.
  2889. * @param {boolean} [shared=false] - Whether this uniform group node is shared or not.
  2890. * @param {number} [order=1] - Influences the internal sorting.
  2891. */
  2892. constructor( name, shared = false, order = 1 ) {
  2893. super( 'string' );
  2894. /**
  2895. * The name of the uniform group node.
  2896. *
  2897. * @type {string}
  2898. */
  2899. this.name = name;
  2900. /**
  2901. * Whether this uniform group node is shared or not.
  2902. *
  2903. * @type {boolean}
  2904. * @default false
  2905. */
  2906. this.shared = shared;
  2907. /**
  2908. * Influences the internal sorting.
  2909. * TODO: Add details when this property should be changed.
  2910. *
  2911. * @type {number}
  2912. * @default 1
  2913. */
  2914. this.order = order;
  2915. /**
  2916. * This flag can be used for type testing.
  2917. *
  2918. * @type {boolean}
  2919. * @readonly
  2920. * @default true
  2921. */
  2922. this.isUniformGroup = true;
  2923. }
  2924. serialize( data ) {
  2925. super.serialize( data );
  2926. data.name = this.name;
  2927. data.version = this.version;
  2928. data.shared = this.shared;
  2929. }
  2930. deserialize( data ) {
  2931. super.deserialize( data );
  2932. this.name = data.name;
  2933. this.version = data.version;
  2934. this.shared = data.shared;
  2935. }
  2936. }
  2937. /**
  2938. * TSL function for creating a uniform group node with the given name.
  2939. *
  2940. * @tsl
  2941. * @function
  2942. * @param {string} name - The name of the uniform group node.
  2943. * @returns {UniformGroupNode}
  2944. */
  2945. const uniformGroup = ( name ) => new UniformGroupNode( name );
  2946. /**
  2947. * TSL function for creating a shared uniform group node with the given name and order.
  2948. *
  2949. * @tsl
  2950. * @function
  2951. * @param {string} name - The name of the uniform group node.
  2952. * @param {number} [order=0] - Influences the internal sorting.
  2953. * @returns {UniformGroupNode}
  2954. */
  2955. const sharedUniformGroup = ( name, order = 0 ) => new UniformGroupNode( name, true, order );
  2956. /**
  2957. * TSL object that represents a shared uniform group node which is updated once per frame.
  2958. *
  2959. * @tsl
  2960. * @type {UniformGroupNode}
  2961. */
  2962. const frameGroup = /*@__PURE__*/ sharedUniformGroup( 'frame' );
  2963. /**
  2964. * TSL object that represents a shared uniform group node which is updated once per render.
  2965. *
  2966. * @tsl
  2967. * @type {UniformGroupNode}
  2968. */
  2969. const renderGroup = /*@__PURE__*/ sharedUniformGroup( 'render' );
  2970. /**
  2971. * TSL object that represents a uniform group node which is updated once per object.
  2972. *
  2973. * @tsl
  2974. * @type {UniformGroupNode}
  2975. */
  2976. const objectGroup = /*@__PURE__*/ uniformGroup( 'object' );
  2977. /**
  2978. * Class for representing a uniform.
  2979. *
  2980. * @augments InputNode
  2981. */
  2982. class UniformNode extends InputNode {
  2983. static get type() {
  2984. return 'UniformNode';
  2985. }
  2986. /**
  2987. * Constructs a new uniform node.
  2988. *
  2989. * @param {any} value - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  2990. * @param {?string} nodeType - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  2991. */
  2992. constructor( value, nodeType = null ) {
  2993. super( value, nodeType );
  2994. /**
  2995. * This flag can be used for type testing.
  2996. *
  2997. * @type {boolean}
  2998. * @readonly
  2999. * @default true
  3000. */
  3001. this.isUniformNode = true;
  3002. /**
  3003. * The name or label of the uniform.
  3004. *
  3005. * @type {string}
  3006. * @default ''
  3007. */
  3008. this.name = '';
  3009. /**
  3010. * The uniform group of this uniform. By default, uniforms are
  3011. * managed per object but they might belong to a shared group
  3012. * which is updated per frame or render call.
  3013. *
  3014. * @type {UniformGroupNode}
  3015. */
  3016. this.groupNode = objectGroup;
  3017. }
  3018. /**
  3019. * Sets the {@link UniformNode#name} property.
  3020. *
  3021. * @param {string} name - The name of the uniform.
  3022. * @return {UniformNode} A reference to this node.
  3023. */
  3024. label( name ) {
  3025. this.name = name;
  3026. return this;
  3027. }
  3028. /**
  3029. * Sets the {@link UniformNode#groupNode} property.
  3030. *
  3031. * @param {UniformGroupNode} group - The uniform group.
  3032. * @return {UniformNode} A reference to this node.
  3033. */
  3034. setGroup( group ) {
  3035. this.groupNode = group;
  3036. return this;
  3037. }
  3038. /**
  3039. * Returns the {@link UniformNode#groupNode}.
  3040. *
  3041. * @return {UniformGroupNode} The uniform group.
  3042. */
  3043. getGroup() {
  3044. return this.groupNode;
  3045. }
  3046. /**
  3047. * By default, this method returns the result of {@link Node#getHash} but derived
  3048. * classes might overwrite this method with a different implementation.
  3049. *
  3050. * @param {NodeBuilder} builder - The current node builder.
  3051. * @return {string} The uniform hash.
  3052. */
  3053. getUniformHash( builder ) {
  3054. return this.getHash( builder );
  3055. }
  3056. onUpdate( callback, updateType ) {
  3057. const self = this.getSelf();
  3058. callback = callback.bind( self );
  3059. return super.onUpdate( ( frame ) => {
  3060. const value = callback( frame, self );
  3061. if ( value !== undefined ) {
  3062. this.value = value;
  3063. }
  3064. }, updateType );
  3065. }
  3066. generate( builder, output ) {
  3067. const type = this.getNodeType( builder );
  3068. const hash = this.getUniformHash( builder );
  3069. let sharedNode = builder.getNodeFromHash( hash );
  3070. if ( sharedNode === undefined ) {
  3071. builder.setHashNode( this, hash );
  3072. sharedNode = this;
  3073. }
  3074. const sharedNodeType = sharedNode.getInputType( builder );
  3075. const nodeUniform = builder.getUniformFromNode( sharedNode, sharedNodeType, builder.shaderStage, this.name || builder.context.label );
  3076. const propertyName = builder.getPropertyName( nodeUniform );
  3077. if ( builder.context.label !== undefined ) delete builder.context.label;
  3078. return builder.format( propertyName, type, output );
  3079. }
  3080. }
  3081. /**
  3082. * TSL function for creating a uniform node.
  3083. *
  3084. * @tsl
  3085. * @function
  3086. * @param {any} arg1 - The value of this node. Usually a JS primitive or three.js object (vector, matrix, color, texture).
  3087. * @param {string} [arg2] - The node type. If no explicit type is defined, the node tries to derive the type from its value.
  3088. * @returns {UniformNode}
  3089. */
  3090. const uniform = ( arg1, arg2 ) => {
  3091. const nodeType = getConstNodeType( arg2 || arg1 );
  3092. // @TODO: get ConstNode from .traverse() in the future
  3093. const value = ( arg1 && arg1.isNode === true ) ? ( arg1.node && arg1.node.value ) || arg1.value : arg1;
  3094. return nodeObject( new UniformNode( value, nodeType ) );
  3095. };
  3096. /**
  3097. * ArrayNode represents a collection of nodes, typically created using the {@link array} function.
  3098. * ```js
  3099. * const colors = array( [
  3100. * vec3( 1, 0, 0 ),
  3101. * vec3( 0, 1, 0 ),
  3102. * vec3( 0, 0, 1 )
  3103. * ] );
  3104. *
  3105. * const redColor = tintColors.element( 0 );
  3106. *
  3107. * @augments TempNode
  3108. */
  3109. class ArrayNode extends TempNode {
  3110. static get type() {
  3111. return 'ArrayNode';
  3112. }
  3113. /**
  3114. * Constructs a new array node.
  3115. *
  3116. * @param {?string} nodeType - The data type of the elements.
  3117. * @param {number} count - Size of the array.
  3118. * @param {?Array<Node>} [values=null] - Array default values.
  3119. */
  3120. constructor( nodeType, count, values = null ) {
  3121. super( nodeType );
  3122. /**
  3123. * Array size.
  3124. *
  3125. * @type {number}
  3126. */
  3127. this.count = count;
  3128. /**
  3129. * Array default values.
  3130. *
  3131. * @type {?Array<Node>}
  3132. */
  3133. this.values = values;
  3134. /**
  3135. * This flag can be used for type testing.
  3136. *
  3137. * @type {boolean}
  3138. * @readonly
  3139. * @default true
  3140. */
  3141. this.isArrayNode = true;
  3142. }
  3143. /**
  3144. * Returns the node's type.
  3145. *
  3146. * @param {NodeBuilder} builder - The current node builder.
  3147. * @return {string} The type of the node.
  3148. */
  3149. getNodeType( builder ) {
  3150. if ( this.nodeType === null ) {
  3151. this.nodeType = this.values[ 0 ].getNodeType( builder );
  3152. }
  3153. return this.nodeType;
  3154. }
  3155. /**
  3156. * Returns the node's type.
  3157. *
  3158. * @param {NodeBuilder} builder - The current node builder.
  3159. * @return {string} The type of the node.
  3160. */
  3161. getElementType( builder ) {
  3162. return this.getNodeType( builder );
  3163. }
  3164. /**
  3165. * This method builds the output node and returns the resulting array as a shader string.
  3166. *
  3167. * @param {NodeBuilder} builder - The current node builder.
  3168. * @return {string} The generated shader string.
  3169. */
  3170. generate( builder ) {
  3171. const type = this.getNodeType( builder );
  3172. return builder.generateArray( type, this.count, this.values );
  3173. }
  3174. }
  3175. /**
  3176. * TSL function for creating an array node.
  3177. *
  3178. * @tsl
  3179. * @function
  3180. * @param {string|Array<Node>} nodeTypeOrValues - A string representing the element type (e.g., 'vec3')
  3181. * or an array containing the default values (e.g., [ vec3() ]).
  3182. * @param {?number} [count] - Size of the array.
  3183. * @returns {ArrayNode}
  3184. */
  3185. const array = ( ...params ) => {
  3186. let node;
  3187. if ( params.length === 1 ) {
  3188. const values = params[ 0 ];
  3189. node = new ArrayNode( null, values.length, values );
  3190. } else {
  3191. const nodeType = params[ 0 ];
  3192. const count = params[ 1 ];
  3193. node = new ArrayNode( nodeType, count );
  3194. }
  3195. return nodeObject( node );
  3196. };
  3197. addMethodChaining( 'toArray', ( node, count ) => array( Array( count ).fill( node ) ) );
  3198. /**
  3199. * These node represents an assign operation. Meaning a node is assigned
  3200. * to another node.
  3201. *
  3202. * @augments TempNode
  3203. */
  3204. class AssignNode extends TempNode {
  3205. static get type() {
  3206. return 'AssignNode';
  3207. }
  3208. /**
  3209. * Constructs a new assign node.
  3210. *
  3211. * @param {Node} targetNode - The target node.
  3212. * @param {Node} sourceNode - The source type.
  3213. */
  3214. constructor( targetNode, sourceNode ) {
  3215. super();
  3216. /**
  3217. * The target node.
  3218. *
  3219. * @type {Node}
  3220. */
  3221. this.targetNode = targetNode;
  3222. /**
  3223. * The source node.
  3224. *
  3225. * @type {Node}
  3226. */
  3227. this.sourceNode = sourceNode;
  3228. /**
  3229. * This flag can be used for type testing.
  3230. *
  3231. * @type {boolean}
  3232. * @readonly
  3233. * @default true
  3234. */
  3235. this.isAssignNode = true;
  3236. }
  3237. /**
  3238. * Whether this node is used more than once in context of other nodes. This method
  3239. * is overwritten since it always returns `false` (assigns are unique).
  3240. *
  3241. * @return {boolean} A flag that indicates if there is more than one dependency to other nodes. Always `false`.
  3242. */
  3243. hasDependencies() {
  3244. return false;
  3245. }
  3246. getNodeType( builder, output ) {
  3247. return output !== 'void' ? this.targetNode.getNodeType( builder ) : 'void';
  3248. }
  3249. /**
  3250. * Whether a split is required when assigning source to target. This can happen when the component length of
  3251. * target and source data type does not match.
  3252. *
  3253. * @param {NodeBuilder} builder - The current node builder.
  3254. * @return {boolean} Whether a split is required when assigning source to target.
  3255. */
  3256. needsSplitAssign( builder ) {
  3257. const { targetNode } = this;
  3258. if ( builder.isAvailable( 'swizzleAssign' ) === false && targetNode.isSplitNode && targetNode.components.length > 1 ) {
  3259. const targetLength = builder.getTypeLength( targetNode.node.getNodeType( builder ) );
  3260. const assignDifferentVector = vectorComponents.join( '' ).slice( 0, targetLength ) !== targetNode.components;
  3261. return assignDifferentVector;
  3262. }
  3263. return false;
  3264. }
  3265. setup( builder ) {
  3266. const { targetNode, sourceNode } = this;
  3267. const properties = builder.getNodeProperties( this );
  3268. properties.sourceNode = sourceNode;
  3269. properties.targetNode = targetNode.context( { assign: true } );
  3270. }
  3271. generate( builder, output ) {
  3272. const { targetNode, sourceNode } = builder.getNodeProperties( this );
  3273. const needsSplitAssign = this.needsSplitAssign( builder );
  3274. const targetType = targetNode.getNodeType( builder );
  3275. const target = targetNode.build( builder );
  3276. const source = sourceNode.build( builder, targetType );
  3277. const sourceType = sourceNode.getNodeType( builder );
  3278. const nodeData = builder.getDataFromNode( this );
  3279. //
  3280. let snippet;
  3281. if ( nodeData.initialized === true ) {
  3282. if ( output !== 'void' ) {
  3283. snippet = target;
  3284. }
  3285. } else if ( needsSplitAssign ) {
  3286. const sourceVar = builder.getVarFromNode( this, null, targetType );
  3287. const sourceProperty = builder.getPropertyName( sourceVar );
  3288. builder.addLineFlowCode( `${ sourceProperty } = ${ source }`, this );
  3289. const splitNode = targetNode.node;
  3290. const splitTargetNode = splitNode.node.context( { assign: true } );
  3291. const targetRoot = splitTargetNode.build( builder );
  3292. for ( let i = 0; i < splitNode.components.length; i ++ ) {
  3293. const component = splitNode.components[ i ];
  3294. builder.addLineFlowCode( `${ targetRoot }.${ component } = ${ sourceProperty }[ ${ i } ]`, this );
  3295. }
  3296. if ( output !== 'void' ) {
  3297. snippet = target;
  3298. }
  3299. } else {
  3300. snippet = `${ target } = ${ source }`;
  3301. if ( output === 'void' || sourceType === 'void' ) {
  3302. builder.addLineFlowCode( snippet, this );
  3303. if ( output !== 'void' ) {
  3304. snippet = target;
  3305. }
  3306. }
  3307. }
  3308. nodeData.initialized = true;
  3309. return builder.format( snippet, targetType, output );
  3310. }
  3311. }
  3312. /**
  3313. * TSL function for creating an assign node.
  3314. *
  3315. * @tsl
  3316. * @function
  3317. * @param {Node} targetNode - The target node.
  3318. * @param {Node} sourceNode - The source type.
  3319. * @returns {AssignNode}
  3320. */
  3321. const assign = /*@__PURE__*/ nodeProxy( AssignNode ).setParameterLength( 2 );
  3322. addMethodChaining( 'assign', assign );
  3323. /**
  3324. * This module represents the call of a {@link FunctionNode}. Developers are usually not confronted
  3325. * with this module since they use the predefined TSL syntax `wgslFn` and `glslFn` which encapsulate
  3326. * this logic.
  3327. *
  3328. * @augments TempNode
  3329. */
  3330. class FunctionCallNode extends TempNode {
  3331. static get type() {
  3332. return 'FunctionCallNode';
  3333. }
  3334. /**
  3335. * Constructs a new function call node.
  3336. *
  3337. * @param {?FunctionNode} functionNode - The function node.
  3338. * @param {Object<string, Node>} [parameters={}] - The parameters for the function call.
  3339. */
  3340. constructor( functionNode = null, parameters = {} ) {
  3341. super();
  3342. /**
  3343. * The function node.
  3344. *
  3345. * @type {?FunctionNode}
  3346. * @default null
  3347. */
  3348. this.functionNode = functionNode;
  3349. /**
  3350. * The parameters of the function call.
  3351. *
  3352. * @type {Object<string, Node>}
  3353. * @default {}
  3354. */
  3355. this.parameters = parameters;
  3356. }
  3357. /**
  3358. * Sets the parameters of the function call node.
  3359. *
  3360. * @param {Object<string, Node>} parameters - The parameters to set.
  3361. * @return {FunctionCallNode} A reference to this node.
  3362. */
  3363. setParameters( parameters ) {
  3364. this.parameters = parameters;
  3365. return this;
  3366. }
  3367. /**
  3368. * Returns the parameters of the function call node.
  3369. *
  3370. * @return {Object<string, Node>} The parameters of this node.
  3371. */
  3372. getParameters() {
  3373. return this.parameters;
  3374. }
  3375. getNodeType( builder ) {
  3376. return this.functionNode.getNodeType( builder );
  3377. }
  3378. generate( builder ) {
  3379. const params = [];
  3380. const functionNode = this.functionNode;
  3381. const inputs = functionNode.getInputs( builder );
  3382. const parameters = this.parameters;
  3383. const generateInput = ( node, inputNode ) => {
  3384. const type = inputNode.type;
  3385. const pointer = type === 'pointer';
  3386. let output;
  3387. if ( pointer ) output = '&' + node.build( builder );
  3388. else output = node.build( builder, type );
  3389. return output;
  3390. };
  3391. if ( Array.isArray( parameters ) ) {
  3392. if ( parameters.length > inputs.length ) {
  3393. console.error( 'THREE.TSL: The number of provided parameters exceeds the expected number of inputs in \'Fn()\'.' );
  3394. parameters.length = inputs.length;
  3395. } else if ( parameters.length < inputs.length ) {
  3396. console.error( 'THREE.TSL: The number of provided parameters is less than the expected number of inputs in \'Fn()\'.' );
  3397. while ( parameters.length < inputs.length ) {
  3398. parameters.push( float( 0 ) );
  3399. }
  3400. }
  3401. for ( let i = 0; i < parameters.length; i ++ ) {
  3402. params.push( generateInput( parameters[ i ], inputs[ i ] ) );
  3403. }
  3404. } else {
  3405. for ( const inputNode of inputs ) {
  3406. const node = parameters[ inputNode.name ];
  3407. if ( node !== undefined ) {
  3408. params.push( generateInput( node, inputNode ) );
  3409. } else {
  3410. console.error( `THREE.TSL: Input '${ inputNode.name }' not found in \'Fn()\'.` );
  3411. params.push( generateInput( float( 0 ), inputNode ) );
  3412. }
  3413. }
  3414. }
  3415. const functionName = functionNode.build( builder, 'property' );
  3416. return `${ functionName }( ${ params.join( ', ' ) } )`;
  3417. }
  3418. }
  3419. const call = ( func, ...params ) => {
  3420. params = params.length > 1 || ( params[ 0 ] && params[ 0 ].isNode === true ) ? nodeArray( params ) : nodeObjects( params[ 0 ] );
  3421. return nodeObject( new FunctionCallNode( nodeObject( func ), params ) );
  3422. };
  3423. addMethodChaining( 'call', call );
  3424. const _vectorOperators = {
  3425. '==': 'equal',
  3426. '!=': 'notEqual',
  3427. '<': 'lessThan',
  3428. '>': 'greaterThan',
  3429. '<=': 'lessThanEqual',
  3430. '>=': 'greaterThanEqual',
  3431. '%': 'mod'
  3432. };
  3433. /**
  3434. * This node represents basic mathematical and logical operations like addition,
  3435. * subtraction or comparisons (e.g. `equal()`).
  3436. *
  3437. * @augments TempNode
  3438. */
  3439. class OperatorNode extends TempNode {
  3440. static get type() {
  3441. return 'OperatorNode';
  3442. }
  3443. /**
  3444. * Constructs a new operator node.
  3445. *
  3446. * @param {string} op - The operator.
  3447. * @param {Node} aNode - The first input.
  3448. * @param {Node} bNode - The second input.
  3449. * @param {...Node} params - Additional input parameters.
  3450. */
  3451. constructor( op, aNode, bNode, ...params ) {
  3452. super();
  3453. if ( params.length > 0 ) {
  3454. let finalOp = new OperatorNode( op, aNode, bNode );
  3455. for ( let i = 0; i < params.length - 1; i ++ ) {
  3456. finalOp = new OperatorNode( op, finalOp, params[ i ] );
  3457. }
  3458. aNode = finalOp;
  3459. bNode = params[ params.length - 1 ];
  3460. }
  3461. /**
  3462. * The operator.
  3463. *
  3464. * @type {string}
  3465. */
  3466. this.op = op;
  3467. /**
  3468. * The first input.
  3469. *
  3470. * @type {Node}
  3471. */
  3472. this.aNode = aNode;
  3473. /**
  3474. * The second input.
  3475. *
  3476. * @type {Node}
  3477. */
  3478. this.bNode = bNode;
  3479. /**
  3480. * This flag can be used for type testing.
  3481. *
  3482. * @type {boolean}
  3483. * @readonly
  3484. * @default true
  3485. */
  3486. this.isOperatorNode = true;
  3487. }
  3488. /**
  3489. * Returns the operator method name.
  3490. *
  3491. * @param {NodeBuilder} builder - The current node builder.
  3492. * @param {string} output - The output type.
  3493. * @returns {string} The operator method name.
  3494. */
  3495. getOperatorMethod( builder, output ) {
  3496. return builder.getMethod( _vectorOperators[ this.op ], output );
  3497. }
  3498. /**
  3499. * This method is overwritten since the node type is inferred from the operator
  3500. * and the input node types.
  3501. *
  3502. * @param {NodeBuilder} builder - The current node builder.
  3503. * @return {string} The node type.
  3504. */
  3505. getNodeType( builder ) {
  3506. const op = this.op;
  3507. const aNode = this.aNode;
  3508. const bNode = this.bNode;
  3509. const typeA = aNode.getNodeType( builder );
  3510. const typeB = bNode ? bNode.getNodeType( builder ) : null;
  3511. if ( typeA === 'void' || typeB === 'void' ) {
  3512. return 'void';
  3513. } else if ( op === '%' ) {
  3514. return typeA;
  3515. } else if ( op === '~' || op === '&' || op === '|' || op === '^' || op === '>>' || op === '<<' ) {
  3516. return builder.getIntegerType( typeA );
  3517. } else if ( op === '!' || op === '&&' || op === '||' || op === '^^' ) {
  3518. return 'bool';
  3519. } else if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3520. const typeLength = Math.max( builder.getTypeLength( typeA ), builder.getTypeLength( typeB ) );
  3521. return typeLength > 1 ? `bvec${ typeLength }` : 'bool';
  3522. } else {
  3523. // Handle matrix operations
  3524. if ( builder.isMatrix( typeA ) ) {
  3525. if ( typeB === 'float' ) {
  3526. return typeA; // matrix * scalar = matrix
  3527. } else if ( builder.isVector( typeB ) ) {
  3528. return builder.getVectorFromMatrix( typeA ); // matrix * vector
  3529. } else if ( builder.isMatrix( typeB ) ) {
  3530. return typeA; // matrix * matrix
  3531. }
  3532. } else if ( builder.isMatrix( typeB ) ) {
  3533. if ( typeA === 'float' ) {
  3534. return typeB; // scalar * matrix = matrix
  3535. } else if ( builder.isVector( typeA ) ) {
  3536. return builder.getVectorFromMatrix( typeB ); // vector * matrix
  3537. }
  3538. }
  3539. // Handle non-matrix cases
  3540. if ( builder.getTypeLength( typeB ) > builder.getTypeLength( typeA ) ) {
  3541. // anytype x anytype: use the greater length vector
  3542. return typeB;
  3543. }
  3544. return typeA;
  3545. }
  3546. }
  3547. generate( builder, output ) {
  3548. const op = this.op;
  3549. const { aNode, bNode } = this;
  3550. const type = this.getNodeType( builder );
  3551. let typeA = null;
  3552. let typeB = null;
  3553. if ( type !== 'void' ) {
  3554. typeA = aNode.getNodeType( builder );
  3555. typeB = bNode ? bNode.getNodeType( builder ) : null;
  3556. if ( op === '<' || op === '>' || op === '<=' || op === '>=' || op === '==' || op === '!=' ) {
  3557. if ( builder.isVector( typeA ) ) {
  3558. typeB = typeA;
  3559. } else if ( builder.isVector( typeB ) ) {
  3560. typeA = typeB;
  3561. } else if ( typeA !== typeB ) {
  3562. typeA = typeB = 'float';
  3563. }
  3564. } else if ( op === '>>' || op === '<<' ) {
  3565. typeA = type;
  3566. typeB = builder.changeComponentType( typeB, 'uint' );
  3567. } else if ( op === '%' ) {
  3568. typeA = type;
  3569. typeB = builder.isInteger( typeA ) && builder.isInteger( typeB ) ? typeB : typeA;
  3570. } else if ( builder.isMatrix( typeA ) ) {
  3571. if ( typeB === 'float' ) {
  3572. // Keep matrix type for typeA, but ensure typeB stays float
  3573. typeB = 'float';
  3574. } else if ( builder.isVector( typeB ) ) {
  3575. // matrix x vector
  3576. typeB = builder.getVectorFromMatrix( typeA );
  3577. } else if ( builder.isMatrix( typeB ) ) ; else {
  3578. typeA = typeB = type;
  3579. }
  3580. } else if ( builder.isMatrix( typeB ) ) {
  3581. if ( typeA === 'float' ) {
  3582. // Keep matrix type for typeB, but ensure typeA stays float
  3583. typeA = 'float';
  3584. } else if ( builder.isVector( typeA ) ) {
  3585. // vector x matrix
  3586. typeA = builder.getVectorFromMatrix( typeB );
  3587. } else {
  3588. typeA = typeB = type;
  3589. }
  3590. } else {
  3591. // anytype x anytype
  3592. typeA = typeB = type;
  3593. }
  3594. } else {
  3595. typeA = typeB = type;
  3596. }
  3597. const a = aNode.build( builder, typeA );
  3598. const b = bNode ? bNode.build( builder, typeB ) : null;
  3599. const fnOpSnippet = builder.getFunctionOperator( op );
  3600. if ( output !== 'void' ) {
  3601. const isGLSL = builder.renderer.coordinateSystem === WebGLCoordinateSystem;
  3602. if ( op === '==' || op === '!=' || op === '<' || op === '>' || op === '<=' || op === '>=' ) {
  3603. if ( isGLSL ) {
  3604. if ( builder.isVector( typeA ) ) {
  3605. return builder.format( `${ this.getOperatorMethod( builder, output ) }( ${ a }, ${ b } )`, type, output );
  3606. } else {
  3607. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3608. }
  3609. } else {
  3610. // WGSL
  3611. return builder.format( `( ${ a } ${ op } ${ b } )`, type, output );
  3612. }
  3613. } else if ( op === '%' ) {
  3614. if ( builder.isInteger( typeB ) ) {
  3615. return builder.format( `( ${ a } % ${ b } )`, type, output );
  3616. } else {
  3617. return builder.format( `${ this.getOperatorMethod( builder, type ) }( ${ a }, ${ b } )`, type, output );
  3618. }
  3619. } else if ( op === '!' || op === '~' ) {
  3620. return builder.format( `(${op}${a})`, typeA, output );
  3621. } else if ( fnOpSnippet ) {
  3622. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3623. } else {
  3624. // Handle matrix operations
  3625. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3626. return builder.format( `( ${ b } ${ op } ${ a } )`, type, output );
  3627. } else if ( typeA === 'float' && builder.isMatrix( typeB ) ) {
  3628. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3629. } else {
  3630. let snippet = `( ${ a } ${ op } ${ b } )`;
  3631. if ( ! isGLSL && type === 'bool' && builder.isVector( typeA ) && builder.isVector( typeB ) ) {
  3632. snippet = `all${ snippet }`;
  3633. }
  3634. return builder.format( snippet, type, output );
  3635. }
  3636. }
  3637. } else if ( typeA !== 'void' ) {
  3638. if ( fnOpSnippet ) {
  3639. return builder.format( `${ fnOpSnippet }( ${ a }, ${ b } )`, type, output );
  3640. } else {
  3641. if ( builder.isMatrix( typeA ) && typeB === 'float' ) {
  3642. return builder.format( `${ b } ${ op } ${ a }`, type, output );
  3643. } else {
  3644. return builder.format( `${ a } ${ op } ${ b }`, type, output );
  3645. }
  3646. }
  3647. }
  3648. }
  3649. serialize( data ) {
  3650. super.serialize( data );
  3651. data.op = this.op;
  3652. }
  3653. deserialize( data ) {
  3654. super.deserialize( data );
  3655. this.op = data.op;
  3656. }
  3657. }
  3658. /**
  3659. * Returns the addition of two or more value.
  3660. *
  3661. * @tsl
  3662. * @function
  3663. * @param {Node} a - The first input.
  3664. * @param {Node} b - The second input.
  3665. * @param {...Node} params - Additional input parameters.
  3666. * @returns {OperatorNode}
  3667. */
  3668. const add = /*@__PURE__*/ nodeProxy( OperatorNode, '+' ).setParameterLength( 2, Infinity ).setName( 'add' );
  3669. /**
  3670. * Returns the subtraction of two or more value.
  3671. *
  3672. * @tsl
  3673. * @function
  3674. * @param {Node} a - The first input.
  3675. * @param {Node} b - The second input.
  3676. * @param {...Node} params - Additional input parameters.
  3677. * @returns {OperatorNode}
  3678. */
  3679. const sub = /*@__PURE__*/ nodeProxy( OperatorNode, '-' ).setParameterLength( 2, Infinity ).setName( 'sub' );
  3680. /**
  3681. * Returns the multiplication of two or more value.
  3682. *
  3683. * @tsl
  3684. * @function
  3685. * @param {Node} a - The first input.
  3686. * @param {Node} b - The second input.
  3687. * @param {...Node} params - Additional input parameters.
  3688. * @returns {OperatorNode}
  3689. */
  3690. const mul = /*@__PURE__*/ nodeProxy( OperatorNode, '*' ).setParameterLength( 2, Infinity ).setName( 'mul' );
  3691. /**
  3692. * Returns the division of two or more value.
  3693. *
  3694. * @tsl
  3695. * @function
  3696. * @param {Node} a - The first input.
  3697. * @param {Node} b - The second input.
  3698. * @param {...Node} params - Additional input parameters.
  3699. * @returns {OperatorNode}
  3700. */
  3701. const div = /*@__PURE__*/ nodeProxy( OperatorNode, '/' ).setParameterLength( 2, Infinity ).setName( 'div' );
  3702. /**
  3703. * Computes the remainder of dividing the first node by the second one.
  3704. *
  3705. * @tsl
  3706. * @function
  3707. * @param {Node} a - The first input.
  3708. * @param {Node} b - The second input.
  3709. * @returns {OperatorNode}
  3710. */
  3711. const mod = /*@__PURE__*/ nodeProxy( OperatorNode, '%' ).setParameterLength( 2 ).setName( 'mod' );
  3712. /**
  3713. * Checks if two nodes are equal.
  3714. *
  3715. * @tsl
  3716. * @function
  3717. * @param {Node} a - The first input.
  3718. * @param {Node} b - The second input.
  3719. * @returns {OperatorNode}
  3720. */
  3721. const equal = /*@__PURE__*/ nodeProxy( OperatorNode, '==' ).setParameterLength( 2 ).setName( 'equal' );
  3722. /**
  3723. * Checks if two nodes are not equal.
  3724. *
  3725. * @tsl
  3726. * @function
  3727. * @param {Node} a - The first input.
  3728. * @param {Node} b - The second input.
  3729. * @returns {OperatorNode}
  3730. */
  3731. const notEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '!=' ).setParameterLength( 2 ).setName( 'notEqual' );
  3732. /**
  3733. * Checks if the first node is less than the second.
  3734. *
  3735. * @tsl
  3736. * @function
  3737. * @param {Node} a - The first input.
  3738. * @param {Node} b - The second input.
  3739. * @returns {OperatorNode}
  3740. */
  3741. const lessThan = /*@__PURE__*/ nodeProxy( OperatorNode, '<' ).setParameterLength( 2 ).setName( 'lessThan' );
  3742. /**
  3743. * Checks if the first node is greater than the second.
  3744. *
  3745. * @tsl
  3746. * @function
  3747. * @param {Node} a - The first input.
  3748. * @param {Node} b - The second input.
  3749. * @returns {OperatorNode}
  3750. */
  3751. const greaterThan = /*@__PURE__*/ nodeProxy( OperatorNode, '>' ).setParameterLength( 2 ).setName( 'greaterThan' );
  3752. /**
  3753. * Checks if the first node is less than or equal to the second.
  3754. *
  3755. * @tsl
  3756. * @function
  3757. * @param {Node} a - The first input.
  3758. * @param {Node} b - The second input.
  3759. * @returns {OperatorNode}
  3760. */
  3761. const lessThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '<=' ).setParameterLength( 2 ).setName( 'lessThanEqual' );
  3762. /**
  3763. * Checks if the first node is greater than or equal to the second.
  3764. *
  3765. * @tsl
  3766. * @function
  3767. * @param {Node} a - The first input.
  3768. * @param {Node} b - The second input.
  3769. * @returns {OperatorNode}
  3770. */
  3771. const greaterThanEqual = /*@__PURE__*/ nodeProxy( OperatorNode, '>=' ).setParameterLength( 2 ).setName( 'greaterThanEqual' );
  3772. /**
  3773. * Performs a logical AND operation on multiple nodes.
  3774. *
  3775. * @tsl
  3776. * @function
  3777. * @param {...Node} nodes - The input nodes to be combined using AND.
  3778. * @returns {OperatorNode}
  3779. */
  3780. const and = /*@__PURE__*/ nodeProxy( OperatorNode, '&&' ).setParameterLength( 2, Infinity ).setName( 'and' );
  3781. /**
  3782. * Performs a logical OR operation on multiple nodes.
  3783. *
  3784. * @tsl
  3785. * @function
  3786. * @param {...Node} nodes - The input nodes to be combined using OR.
  3787. * @returns {OperatorNode}
  3788. */
  3789. const or = /*@__PURE__*/ nodeProxy( OperatorNode, '||' ).setParameterLength( 2, Infinity ).setName( 'or' );
  3790. /**
  3791. * Performs logical NOT on a node.
  3792. *
  3793. * @tsl
  3794. * @function
  3795. * @param {Node} value - The value.
  3796. * @returns {OperatorNode}
  3797. */
  3798. const not = /*@__PURE__*/ nodeProxy( OperatorNode, '!' ).setParameterLength( 1 ).setName( 'not' );
  3799. /**
  3800. * Performs logical XOR on two nodes.
  3801. *
  3802. * @tsl
  3803. * @function
  3804. * @param {Node} a - The first input.
  3805. * @param {Node} b - The second input.
  3806. * @returns {OperatorNode}
  3807. */
  3808. const xor = /*@__PURE__*/ nodeProxy( OperatorNode, '^^' ).setParameterLength( 2 ).setName( 'xor' );
  3809. /**
  3810. * Performs bitwise AND on two nodes.
  3811. *
  3812. * @tsl
  3813. * @function
  3814. * @param {Node} a - The first input.
  3815. * @param {Node} b - The second input.
  3816. * @returns {OperatorNode}
  3817. */
  3818. const bitAnd = /*@__PURE__*/ nodeProxy( OperatorNode, '&' ).setParameterLength( 2 ).setName( 'bitAnd' );
  3819. /**
  3820. * Performs bitwise NOT on a node.
  3821. *
  3822. * @tsl
  3823. * @function
  3824. * @param {Node} a - The first input.
  3825. * @param {Node} b - The second input.
  3826. * @returns {OperatorNode}
  3827. */
  3828. const bitNot = /*@__PURE__*/ nodeProxy( OperatorNode, '~' ).setParameterLength( 2 ).setName( 'bitNot' );
  3829. /**
  3830. * Performs bitwise OR on two nodes.
  3831. *
  3832. * @tsl
  3833. * @function
  3834. * @param {Node} a - The first input.
  3835. * @param {Node} b - The second input.
  3836. * @returns {OperatorNode}
  3837. */
  3838. const bitOr = /*@__PURE__*/ nodeProxy( OperatorNode, '|' ).setParameterLength( 2 ).setName( 'bitOr' );
  3839. /**
  3840. * Performs bitwise XOR on two nodes.
  3841. *
  3842. * @tsl
  3843. * @function
  3844. * @param {Node} a - The first input.
  3845. * @param {Node} b - The second input.
  3846. * @returns {OperatorNode}
  3847. */
  3848. const bitXor = /*@__PURE__*/ nodeProxy( OperatorNode, '^' ).setParameterLength( 2 ).setName( 'bitXor' );
  3849. /**
  3850. * Shifts a node to the left.
  3851. *
  3852. * @tsl
  3853. * @function
  3854. * @param {Node} a - The node to shift.
  3855. * @param {Node} b - The value to shift.
  3856. * @returns {OperatorNode}
  3857. */
  3858. const shiftLeft = /*@__PURE__*/ nodeProxy( OperatorNode, '<<' ).setParameterLength( 2 ).setName( 'shiftLeft' );
  3859. /**
  3860. * Shifts a node to the right.
  3861. *
  3862. * @tsl
  3863. * @function
  3864. * @param {Node} a - The node to shift.
  3865. * @param {Node} b - The value to shift.
  3866. * @returns {OperatorNode}
  3867. */
  3868. const shiftRight = /*@__PURE__*/ nodeProxy( OperatorNode, '>>' ).setParameterLength( 2 ).setName( 'shiftRight' );
  3869. /**
  3870. * Increments a node by 1.
  3871. *
  3872. * @tsl
  3873. * @function
  3874. * @param {Node} a - The node to increment.
  3875. * @returns {OperatorNode}
  3876. */
  3877. const incrementBefore = Fn( ( [ a ] ) => {
  3878. a.addAssign( 1 );
  3879. return a;
  3880. } );
  3881. /**
  3882. * Decrements a node by 1.
  3883. *
  3884. * @tsl
  3885. * @function
  3886. * @param {Node} a - The node to decrement.
  3887. * @returns {OperatorNode}
  3888. */
  3889. const decrementBefore = Fn( ( [ a ] ) => {
  3890. a.subAssign( 1 );
  3891. return a;
  3892. } );
  3893. /**
  3894. * Increments a node by 1 and returns the previous value.
  3895. *
  3896. * @tsl
  3897. * @function
  3898. * @param {Node} a - The node to increment.
  3899. * @returns {OperatorNode}
  3900. */
  3901. const increment = /*@__PURE__*/ Fn( ( [ a ] ) => {
  3902. const temp = int( a ).toConst();
  3903. a.addAssign( 1 );
  3904. return temp;
  3905. } );
  3906. /**
  3907. * Decrements a node by 1 and returns the previous value.
  3908. *
  3909. * @tsl
  3910. * @function
  3911. * @param {Node} a - The node to decrement.
  3912. * @returns {OperatorNode}
  3913. */
  3914. const decrement = /*@__PURE__*/ Fn( ( [ a ] ) => {
  3915. const temp = int( a ).toConst();
  3916. a.subAssign( 1 );
  3917. return temp;
  3918. } );
  3919. addMethodChaining( 'add', add );
  3920. addMethodChaining( 'sub', sub );
  3921. addMethodChaining( 'mul', mul );
  3922. addMethodChaining( 'div', div );
  3923. addMethodChaining( 'mod', mod );
  3924. addMethodChaining( 'equal', equal );
  3925. addMethodChaining( 'notEqual', notEqual );
  3926. addMethodChaining( 'lessThan', lessThan );
  3927. addMethodChaining( 'greaterThan', greaterThan );
  3928. addMethodChaining( 'lessThanEqual', lessThanEqual );
  3929. addMethodChaining( 'greaterThanEqual', greaterThanEqual );
  3930. addMethodChaining( 'and', and );
  3931. addMethodChaining( 'or', or );
  3932. addMethodChaining( 'not', not );
  3933. addMethodChaining( 'xor', xor );
  3934. addMethodChaining( 'bitAnd', bitAnd );
  3935. addMethodChaining( 'bitNot', bitNot );
  3936. addMethodChaining( 'bitOr', bitOr );
  3937. addMethodChaining( 'bitXor', bitXor );
  3938. addMethodChaining( 'shiftLeft', shiftLeft );
  3939. addMethodChaining( 'shiftRight', shiftRight );
  3940. addMethodChaining( 'incrementBefore', incrementBefore );
  3941. addMethodChaining( 'decrementBefore', decrementBefore );
  3942. addMethodChaining( 'increment', increment );
  3943. addMethodChaining( 'decrement', decrement );
  3944. /**
  3945. * @tsl
  3946. * @function
  3947. * @deprecated since r168. Use {@link mod} instead.
  3948. *
  3949. * @param {Node} a - The first input.
  3950. * @param {Node} b - The second input.
  3951. * @returns {OperatorNode}
  3952. */
  3953. const remainder = ( a, b ) => { // @deprecated, r168
  3954. console.warn( 'THREE.TSL: "remainder()" is deprecated. Use "mod( int( ... ) )" instead.' );
  3955. return mod( a, b );
  3956. };
  3957. /**
  3958. * @tsl
  3959. * @function
  3960. * @deprecated since r175. Use {@link mod} instead.
  3961. *
  3962. * @param {Node} a - The first input.
  3963. * @param {Node} b - The second input.
  3964. * @returns {OperatorNode}
  3965. */
  3966. const modInt = ( a, b ) => { // @deprecated, r175
  3967. console.warn( 'THREE.TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.' );
  3968. return mod( int( a ), int( b ) );
  3969. };
  3970. addMethodChaining( 'remainder', remainder );
  3971. addMethodChaining( 'modInt', modInt );
  3972. /**
  3973. * This node represents a variety of mathematical methods available in shaders.
  3974. * They are divided into three categories:
  3975. *
  3976. * - Methods with one input like `sin`, `cos` or `normalize`.
  3977. * - Methods with two inputs like `dot`, `cross` or `pow`.
  3978. * - Methods with three inputs like `mix`, `clamp` or `smoothstep`.
  3979. *
  3980. * @augments TempNode
  3981. */
  3982. class MathNode extends TempNode {
  3983. static get type() {
  3984. return 'MathNode';
  3985. }
  3986. /**
  3987. * Constructs a new math node.
  3988. *
  3989. * @param {string} method - The method name.
  3990. * @param {Node} aNode - The first input.
  3991. * @param {?Node} [bNode=null] - The second input.
  3992. * @param {?Node} [cNode=null] - The third input.
  3993. */
  3994. constructor( method, aNode, bNode = null, cNode = null ) {
  3995. super();
  3996. // Allow the max() and min() functions to take an arbitrary number of arguments.
  3997. if ( ( method === MathNode.MAX || method === MathNode.MIN ) && arguments.length > 3 ) {
  3998. let finalOp = new MathNode( method, aNode, bNode );
  3999. for ( let i = 2; i < arguments.length - 1; i ++ ) {
  4000. finalOp = new MathNode( method, finalOp, arguments[ i ] );
  4001. }
  4002. aNode = finalOp;
  4003. bNode = arguments[ arguments.length - 1 ];
  4004. cNode = null;
  4005. }
  4006. /**
  4007. * The method name.
  4008. *
  4009. * @type {string}
  4010. */
  4011. this.method = method;
  4012. /**
  4013. * The first input.
  4014. *
  4015. * @type {Node}
  4016. */
  4017. this.aNode = aNode;
  4018. /**
  4019. * The second input.
  4020. *
  4021. * @type {?Node}
  4022. * @default null
  4023. */
  4024. this.bNode = bNode;
  4025. /**
  4026. * The third input.
  4027. *
  4028. * @type {?Node}
  4029. * @default null
  4030. */
  4031. this.cNode = cNode;
  4032. /**
  4033. * This flag can be used for type testing.
  4034. *
  4035. * @type {boolean}
  4036. * @readonly
  4037. * @default true
  4038. */
  4039. this.isMathNode = true;
  4040. }
  4041. /**
  4042. * The input type is inferred from the node types of the input nodes.
  4043. *
  4044. * @param {NodeBuilder} builder - The current node builder.
  4045. * @return {string} The input type.
  4046. */
  4047. getInputType( builder ) {
  4048. const aType = this.aNode.getNodeType( builder );
  4049. const bType = this.bNode ? this.bNode.getNodeType( builder ) : null;
  4050. const cType = this.cNode ? this.cNode.getNodeType( builder ) : null;
  4051. const aLen = builder.isMatrix( aType ) ? 0 : builder.getTypeLength( aType );
  4052. const bLen = builder.isMatrix( bType ) ? 0 : builder.getTypeLength( bType );
  4053. const cLen = builder.isMatrix( cType ) ? 0 : builder.getTypeLength( cType );
  4054. if ( aLen > bLen && aLen > cLen ) {
  4055. return aType;
  4056. } else if ( bLen > cLen ) {
  4057. return bType;
  4058. } else if ( cLen > aLen ) {
  4059. return cType;
  4060. }
  4061. return aType;
  4062. }
  4063. /**
  4064. * The selected method as well as the input type determine the node type of this node.
  4065. *
  4066. * @param {NodeBuilder} builder - The current node builder.
  4067. * @return {string} The node type.
  4068. */
  4069. getNodeType( builder ) {
  4070. const method = this.method;
  4071. if ( method === MathNode.LENGTH || method === MathNode.DISTANCE || method === MathNode.DOT ) {
  4072. return 'float';
  4073. } else if ( method === MathNode.CROSS ) {
  4074. return 'vec3';
  4075. } else if ( method === MathNode.ALL || method === MathNode.ANY ) {
  4076. return 'bool';
  4077. } else if ( method === MathNode.EQUALS ) {
  4078. return builder.changeComponentType( this.aNode.getNodeType( builder ), 'bool' );
  4079. } else {
  4080. return this.getInputType( builder );
  4081. }
  4082. }
  4083. setup( builder ) {
  4084. const { aNode, bNode, method } = this;
  4085. let outputNode = null;
  4086. if ( method === MathNode.ONE_MINUS ) {
  4087. outputNode = sub( 1.0, aNode );
  4088. } else if ( method === MathNode.RECIPROCAL ) {
  4089. outputNode = div( 1.0, aNode );
  4090. } else if ( method === MathNode.DIFFERENCE ) {
  4091. outputNode = abs( sub( aNode, bNode ) );
  4092. } else if ( method === MathNode.TRANSFORM_DIRECTION ) {
  4093. // dir can be either a direction vector or a normal vector
  4094. // upper-left 3x3 of matrix is assumed to be orthogonal
  4095. let tA = aNode;
  4096. let tB = bNode;
  4097. if ( builder.isMatrix( tA.getNodeType( builder ) ) ) {
  4098. tB = vec4( vec3( tB ), 0.0 );
  4099. } else {
  4100. tA = vec4( vec3( tA ), 0.0 );
  4101. }
  4102. const mulNode = mul( tA, tB ).xyz;
  4103. outputNode = normalize( mulNode );
  4104. }
  4105. if ( outputNode !== null ) {
  4106. return outputNode;
  4107. } else {
  4108. return super.setup( builder );
  4109. }
  4110. }
  4111. generate( builder, output ) {
  4112. const properties = builder.getNodeProperties( this );
  4113. if ( properties.outputNode ) {
  4114. return super.generate( builder, output );
  4115. }
  4116. let method = this.method;
  4117. const type = this.getNodeType( builder );
  4118. const inputType = this.getInputType( builder );
  4119. const a = this.aNode;
  4120. const b = this.bNode;
  4121. const c = this.cNode;
  4122. const coordinateSystem = builder.renderer.coordinateSystem;
  4123. if ( method === MathNode.NEGATE ) {
  4124. return builder.format( '( - ' + a.build( builder, inputType ) + ' )', type, output );
  4125. } else {
  4126. const params = [];
  4127. if ( method === MathNode.CROSS ) {
  4128. params.push(
  4129. a.build( builder, type ),
  4130. b.build( builder, type )
  4131. );
  4132. } else if ( coordinateSystem === WebGLCoordinateSystem && method === MathNode.STEP ) {
  4133. params.push(
  4134. a.build( builder, builder.getTypeLength( a.getNodeType( builder ) ) === 1 ? 'float' : inputType ),
  4135. b.build( builder, inputType )
  4136. );
  4137. } else if ( coordinateSystem === WebGLCoordinateSystem && ( method === MathNode.MIN || method === MathNode.MAX ) ) {
  4138. params.push(
  4139. a.build( builder, inputType ),
  4140. b.build( builder, builder.getTypeLength( b.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4141. );
  4142. } else if ( method === MathNode.REFRACT ) {
  4143. params.push(
  4144. a.build( builder, inputType ),
  4145. b.build( builder, inputType ),
  4146. c.build( builder, 'float' )
  4147. );
  4148. } else if ( method === MathNode.MIX ) {
  4149. params.push(
  4150. a.build( builder, inputType ),
  4151. b.build( builder, inputType ),
  4152. c.build( builder, builder.getTypeLength( c.getNodeType( builder ) ) === 1 ? 'float' : inputType )
  4153. );
  4154. } else {
  4155. if ( coordinateSystem === WebGPUCoordinateSystem && method === MathNode.ATAN && b !== null ) {
  4156. method = 'atan2';
  4157. }
  4158. if ( builder.shaderStage !== 'fragment' && ( method === MathNode.DFDX || method === MathNode.DFDY ) ) {
  4159. console.warn( `THREE.TSL: '${ method }' is not supported in the ${ builder.shaderStage } stage.` );
  4160. method = '/*' + method + '*/';
  4161. }
  4162. params.push( a.build( builder, inputType ) );
  4163. if ( b !== null ) params.push( b.build( builder, inputType ) );
  4164. if ( c !== null ) params.push( c.build( builder, inputType ) );
  4165. }
  4166. return builder.format( `${ builder.getMethod( method, type ) }( ${params.join( ', ' )} )`, type, output );
  4167. }
  4168. }
  4169. serialize( data ) {
  4170. super.serialize( data );
  4171. data.method = this.method;
  4172. }
  4173. deserialize( data ) {
  4174. super.deserialize( data );
  4175. this.method = data.method;
  4176. }
  4177. }
  4178. // 1 input
  4179. MathNode.ALL = 'all';
  4180. MathNode.ANY = 'any';
  4181. MathNode.RADIANS = 'radians';
  4182. MathNode.DEGREES = 'degrees';
  4183. MathNode.EXP = 'exp';
  4184. MathNode.EXP2 = 'exp2';
  4185. MathNode.LOG = 'log';
  4186. MathNode.LOG2 = 'log2';
  4187. MathNode.SQRT = 'sqrt';
  4188. MathNode.INVERSE_SQRT = 'inversesqrt';
  4189. MathNode.FLOOR = 'floor';
  4190. MathNode.CEIL = 'ceil';
  4191. MathNode.NORMALIZE = 'normalize';
  4192. MathNode.FRACT = 'fract';
  4193. MathNode.SIN = 'sin';
  4194. MathNode.COS = 'cos';
  4195. MathNode.TAN = 'tan';
  4196. MathNode.ASIN = 'asin';
  4197. MathNode.ACOS = 'acos';
  4198. MathNode.ATAN = 'atan';
  4199. MathNode.ABS = 'abs';
  4200. MathNode.SIGN = 'sign';
  4201. MathNode.LENGTH = 'length';
  4202. MathNode.NEGATE = 'negate';
  4203. MathNode.ONE_MINUS = 'oneMinus';
  4204. MathNode.DFDX = 'dFdx';
  4205. MathNode.DFDY = 'dFdy';
  4206. MathNode.ROUND = 'round';
  4207. MathNode.RECIPROCAL = 'reciprocal';
  4208. MathNode.TRUNC = 'trunc';
  4209. MathNode.FWIDTH = 'fwidth';
  4210. MathNode.TRANSPOSE = 'transpose';
  4211. // 2 inputs
  4212. MathNode.BITCAST = 'bitcast';
  4213. MathNode.EQUALS = 'equals';
  4214. MathNode.MIN = 'min';
  4215. MathNode.MAX = 'max';
  4216. MathNode.STEP = 'step';
  4217. MathNode.REFLECT = 'reflect';
  4218. MathNode.DISTANCE = 'distance';
  4219. MathNode.DIFFERENCE = 'difference';
  4220. MathNode.DOT = 'dot';
  4221. MathNode.CROSS = 'cross';
  4222. MathNode.POW = 'pow';
  4223. MathNode.TRANSFORM_DIRECTION = 'transformDirection';
  4224. // 3 inputs
  4225. MathNode.MIX = 'mix';
  4226. MathNode.CLAMP = 'clamp';
  4227. MathNode.REFRACT = 'refract';
  4228. MathNode.SMOOTHSTEP = 'smoothstep';
  4229. MathNode.FACEFORWARD = 'faceforward';
  4230. // 1 inputs
  4231. /**
  4232. * A small value used to handle floating-point precision errors.
  4233. *
  4234. * @tsl
  4235. * @type {Node<float>}
  4236. */
  4237. const EPSILON = /*@__PURE__*/ float( 1e-6 );
  4238. /**
  4239. * Represents infinity.
  4240. *
  4241. * @tsl
  4242. * @type {Node<float>}
  4243. */
  4244. const INFINITY = /*@__PURE__*/ float( 1e6 );
  4245. /**
  4246. * Represents PI.
  4247. *
  4248. * @tsl
  4249. * @type {Node<float>}
  4250. */
  4251. const PI = /*@__PURE__*/ float( Math.PI );
  4252. /**
  4253. * Represents PI * 2.
  4254. *
  4255. * @tsl
  4256. * @type {Node<float>}
  4257. */
  4258. const PI2 = /*@__PURE__*/ float( Math.PI * 2 );
  4259. /**
  4260. * Returns `true` if all components of `x` are `true`.
  4261. *
  4262. * @tsl
  4263. * @function
  4264. * @param {Node | number} x - The parameter.
  4265. * @returns {Node<bool>}
  4266. */
  4267. const all = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ALL ).setParameterLength( 1 );
  4268. /**
  4269. * Returns `true` if any components of `x` are `true`.
  4270. *
  4271. * @tsl
  4272. * @function
  4273. * @param {Node | number} x - The parameter.
  4274. * @returns {Node<bool>}
  4275. */
  4276. const any = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ANY ).setParameterLength( 1 );
  4277. /**
  4278. * Converts a quantity in degrees to radians.
  4279. *
  4280. * @tsl
  4281. * @function
  4282. * @param {Node | number} x - The input in degrees.
  4283. * @returns {Node}
  4284. */
  4285. const radians = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RADIANS ).setParameterLength( 1 );
  4286. /**
  4287. * Convert a quantity in radians to degrees.
  4288. *
  4289. * @tsl
  4290. * @function
  4291. * @param {Node | number} x - The input in radians.
  4292. * @returns {Node}
  4293. */
  4294. const degrees = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DEGREES ).setParameterLength( 1 );
  4295. /**
  4296. * Returns the natural exponentiation of the parameter.
  4297. *
  4298. * @tsl
  4299. * @function
  4300. * @param {Node | number} x - The parameter.
  4301. * @returns {Node}
  4302. */
  4303. const exp = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP ).setParameterLength( 1 );
  4304. /**
  4305. * Returns 2 raised to the power of the parameter.
  4306. *
  4307. * @tsl
  4308. * @function
  4309. * @param {Node | number} x - The parameter.
  4310. * @returns {Node}
  4311. */
  4312. const exp2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.EXP2 ).setParameterLength( 1 );
  4313. /**
  4314. * Returns the natural logarithm of the parameter.
  4315. *
  4316. * @tsl
  4317. * @function
  4318. * @param {Node | number} x - The parameter.
  4319. * @returns {Node}
  4320. */
  4321. const log = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG ).setParameterLength( 1 );
  4322. /**
  4323. * Returns the base 2 logarithm of the parameter.
  4324. *
  4325. * @tsl
  4326. * @function
  4327. * @param {Node | number} x - The parameter.
  4328. * @returns {Node}
  4329. */
  4330. const log2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LOG2 ).setParameterLength( 1 );
  4331. /**
  4332. * Returns the square root of the parameter.
  4333. *
  4334. * @tsl
  4335. * @function
  4336. * @param {Node | number} x - The parameter.
  4337. * @returns {Node}
  4338. */
  4339. const sqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SQRT ).setParameterLength( 1 );
  4340. /**
  4341. * Returns the inverse of the square root of the parameter.
  4342. *
  4343. * @tsl
  4344. * @function
  4345. * @param {Node | number} x - The parameter.
  4346. * @returns {Node}
  4347. */
  4348. const inverseSqrt = /*@__PURE__*/ nodeProxy( MathNode, MathNode.INVERSE_SQRT ).setParameterLength( 1 );
  4349. /**
  4350. * Finds the nearest integer less than or equal to the parameter.
  4351. *
  4352. * @tsl
  4353. * @function
  4354. * @param {Node | number} x - The parameter.
  4355. * @returns {Node}
  4356. */
  4357. const floor = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FLOOR ).setParameterLength( 1 );
  4358. /**
  4359. * Finds the nearest integer that is greater than or equal to the parameter.
  4360. *
  4361. * @tsl
  4362. * @function
  4363. * @param {Node | number} x - The parameter.
  4364. * @returns {Node}
  4365. */
  4366. const ceil = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CEIL ).setParameterLength( 1 );
  4367. /**
  4368. * Calculates the unit vector in the same direction as the original vector.
  4369. *
  4370. * @tsl
  4371. * @function
  4372. * @param {Node} x - The input vector.
  4373. * @returns {Node}
  4374. */
  4375. const normalize = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NORMALIZE ).setParameterLength( 1 );
  4376. /**
  4377. * Computes the fractional part of the parameter.
  4378. *
  4379. * @tsl
  4380. * @function
  4381. * @param {Node | number} x - The parameter.
  4382. * @returns {Node}
  4383. */
  4384. const fract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FRACT ).setParameterLength( 1 );
  4385. /**
  4386. * Returns the sine of the parameter.
  4387. *
  4388. * @tsl
  4389. * @function
  4390. * @param {Node | number} x - The parameter.
  4391. * @returns {Node}
  4392. */
  4393. const sin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIN ).setParameterLength( 1 );
  4394. /**
  4395. * Returns the cosine of the parameter.
  4396. *
  4397. * @tsl
  4398. * @function
  4399. * @param {Node | number} x - The parameter.
  4400. * @returns {Node}
  4401. */
  4402. const cos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.COS ).setParameterLength( 1 );
  4403. /**
  4404. * Returns the tangent of the parameter.
  4405. *
  4406. * @tsl
  4407. * @function
  4408. * @param {Node | number} x - The parameter.
  4409. * @returns {Node}
  4410. */
  4411. const tan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TAN ).setParameterLength( 1 );
  4412. /**
  4413. * Returns the arcsine of the parameter.
  4414. *
  4415. * @tsl
  4416. * @function
  4417. * @param {Node | number} x - The parameter.
  4418. * @returns {Node}
  4419. */
  4420. const asin = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ASIN ).setParameterLength( 1 );
  4421. /**
  4422. * Returns the arccosine of the parameter.
  4423. *
  4424. * @tsl
  4425. * @function
  4426. * @param {Node | number} x - The parameter.
  4427. * @returns {Node}
  4428. */
  4429. const acos = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ACOS ).setParameterLength( 1 );
  4430. /**
  4431. * Returns the arc-tangent of the parameter.
  4432. * If two parameters are provided, the result is `atan2(y/x)`.
  4433. *
  4434. * @tsl
  4435. * @function
  4436. * @param {Node | number} y - The y parameter.
  4437. * @param {?(Node | number)} x - The x parameter.
  4438. * @returns {Node}
  4439. */
  4440. const atan = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ATAN ).setParameterLength( 1, 2 );
  4441. /**
  4442. * Returns the absolute value of the parameter.
  4443. *
  4444. * @tsl
  4445. * @function
  4446. * @param {Node | number} x - The parameter.
  4447. * @returns {Node}
  4448. */
  4449. const abs = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ABS ).setParameterLength( 1 );
  4450. /**
  4451. * Extracts the sign of the parameter.
  4452. *
  4453. * @tsl
  4454. * @function
  4455. * @param {Node | number} x - The parameter.
  4456. * @returns {Node}
  4457. */
  4458. const sign = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SIGN ).setParameterLength( 1 );
  4459. /**
  4460. * Calculates the length of a vector.
  4461. *
  4462. * @tsl
  4463. * @function
  4464. * @param {Node} x - The parameter.
  4465. * @returns {Node<float>}
  4466. */
  4467. const length = /*@__PURE__*/ nodeProxy( MathNode, MathNode.LENGTH ).setParameterLength( 1 );
  4468. /**
  4469. * Negates the value of the parameter (-x).
  4470. *
  4471. * @tsl
  4472. * @function
  4473. * @param {Node | number} x - The parameter.
  4474. * @returns {Node}
  4475. */
  4476. const negate = /*@__PURE__*/ nodeProxy( MathNode, MathNode.NEGATE ).setParameterLength( 1 );
  4477. /**
  4478. * Return `1` minus the parameter.
  4479. *
  4480. * @tsl
  4481. * @function
  4482. * @param {Node | number} x - The parameter.
  4483. * @returns {Node}
  4484. */
  4485. const oneMinus = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ONE_MINUS ).setParameterLength( 1 );
  4486. /**
  4487. * Returns the partial derivative of the parameter with respect to x.
  4488. *
  4489. * @tsl
  4490. * @function
  4491. * @param {Node | number} x - The parameter.
  4492. * @returns {Node}
  4493. */
  4494. const dFdx = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDX ).setParameterLength( 1 );
  4495. /**
  4496. * Returns the partial derivative of the parameter with respect to y.
  4497. *
  4498. * @tsl
  4499. * @function
  4500. * @param {Node | number} x - The parameter.
  4501. * @returns {Node}
  4502. */
  4503. const dFdy = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DFDY ).setParameterLength( 1 );
  4504. /**
  4505. * Rounds the parameter to the nearest integer.
  4506. *
  4507. * @tsl
  4508. * @function
  4509. * @param {Node | number} x - The parameter.
  4510. * @returns {Node}
  4511. */
  4512. const round = /*@__PURE__*/ nodeProxy( MathNode, MathNode.ROUND ).setParameterLength( 1 );
  4513. /**
  4514. * Returns the reciprocal of the parameter `(1/x)`.
  4515. *
  4516. * @tsl
  4517. * @function
  4518. * @param {Node | number} x - The parameter.
  4519. * @returns {Node}
  4520. */
  4521. const reciprocal = /*@__PURE__*/ nodeProxy( MathNode, MathNode.RECIPROCAL ).setParameterLength( 1 );
  4522. /**
  4523. * Truncates the parameter, removing the fractional part.
  4524. *
  4525. * @tsl
  4526. * @function
  4527. * @param {Node | number} x - The parameter.
  4528. * @returns {Node}
  4529. */
  4530. const trunc = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRUNC ).setParameterLength( 1 );
  4531. /**
  4532. * Returns the sum of the absolute derivatives in x and y.
  4533. *
  4534. * @tsl
  4535. * @function
  4536. * @param {Node | number} x - The parameter.
  4537. * @returns {Node}
  4538. */
  4539. const fwidth = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FWIDTH ).setParameterLength( 1 );
  4540. /**
  4541. * Returns the transpose of a matrix.
  4542. *
  4543. * @tsl
  4544. * @function
  4545. * @param {Node<mat2|mat3|mat4>} x - The parameter.
  4546. * @returns {Node}
  4547. */
  4548. const transpose = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSPOSE ).setParameterLength( 1 );
  4549. // 2 inputs
  4550. /**
  4551. * Reinterpret the bit representation of a value in one type as a value in another type.
  4552. *
  4553. * @tsl
  4554. * @function
  4555. * @param {Node | number} x - The parameter.
  4556. * @param {string} y - The new type.
  4557. * @returns {Node}
  4558. */
  4559. const bitcast = /*@__PURE__*/ nodeProxy( MathNode, MathNode.BITCAST ).setParameterLength( 2 );
  4560. /**
  4561. * Returns `true` if `x` equals `y`.
  4562. *
  4563. * @tsl
  4564. * @function
  4565. * @param {Node | number} x - The first parameter.
  4566. * @param {Node | number} y - The second parameter.
  4567. * @deprecated since r175. Use {@link equal} instead.
  4568. * @returns {Node<bool>}
  4569. */
  4570. const equals = ( x, y ) => { // @deprecated, r172
  4571. console.warn( 'THREE.TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"' );
  4572. return equal( x, y );
  4573. };
  4574. /**
  4575. * Returns the least of the given values.
  4576. *
  4577. * @tsl
  4578. * @function
  4579. * @param {...(Node | number)} values - The values to compare.
  4580. * @returns {Node}
  4581. */
  4582. const min$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIN ).setParameterLength( 2, Infinity );
  4583. /**
  4584. * Returns the greatest of the given values.
  4585. *
  4586. * @tsl
  4587. * @function
  4588. * @param {...(Node | number)} values - The values to compare.
  4589. * @returns {Node}
  4590. */
  4591. const max$1 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MAX ).setParameterLength( 2, Infinity );
  4592. /**
  4593. * Generate a step function by comparing two values.
  4594. *
  4595. * @tsl
  4596. * @function
  4597. * @param {Node | number} x - The y parameter.
  4598. * @param {Node | number} y - The x parameter.
  4599. * @returns {Node}
  4600. */
  4601. const step = /*@__PURE__*/ nodeProxy( MathNode, MathNode.STEP ).setParameterLength( 2 );
  4602. /**
  4603. * Calculates the reflection direction for an incident vector.
  4604. *
  4605. * @tsl
  4606. * @function
  4607. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4608. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4609. * @returns {Node<vec2|vec3|vec4>}
  4610. */
  4611. const reflect = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFLECT ).setParameterLength( 2 );
  4612. /**
  4613. * Calculates the distance between two points.
  4614. *
  4615. * @tsl
  4616. * @function
  4617. * @param {Node<vec2|vec3|vec4>} x - The first point.
  4618. * @param {Node<vec2|vec3|vec4>} y - The second point.
  4619. * @returns {Node<float>}
  4620. */
  4621. const distance = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DISTANCE ).setParameterLength( 2 );
  4622. /**
  4623. * Calculates the absolute difference between two values.
  4624. *
  4625. * @tsl
  4626. * @function
  4627. * @param {Node | number} x - The first parameter.
  4628. * @param {Node | number} y - The second parameter.
  4629. * @returns {Node}
  4630. */
  4631. const difference = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DIFFERENCE ).setParameterLength( 2 );
  4632. /**
  4633. * Calculates the dot product of two vectors.
  4634. *
  4635. * @tsl
  4636. * @function
  4637. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4638. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4639. * @returns {Node<float>}
  4640. */
  4641. const dot = /*@__PURE__*/ nodeProxy( MathNode, MathNode.DOT ).setParameterLength( 2 );
  4642. /**
  4643. * Calculates the cross product of two vectors.
  4644. *
  4645. * @tsl
  4646. * @function
  4647. * @param {Node<vec2|vec3|vec4>} x - The first vector.
  4648. * @param {Node<vec2|vec3|vec4>} y - The second vector.
  4649. * @returns {Node<vec2|vec3|vec4>}
  4650. */
  4651. const cross = /*@__PURE__*/ nodeProxy( MathNode, MathNode.CROSS ).setParameterLength( 2 );
  4652. /**
  4653. * Return the value of the first parameter raised to the power of the second one.
  4654. *
  4655. * @tsl
  4656. * @function
  4657. * @param {Node | number} x - The first parameter.
  4658. * @param {Node | number} y - The second parameter.
  4659. * @returns {Node}
  4660. */
  4661. const pow = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW ).setParameterLength( 2 );
  4662. /**
  4663. * Returns the square of the parameter.
  4664. *
  4665. * @tsl
  4666. * @function
  4667. * @param {Node | number} x - The first parameter.
  4668. * @returns {Node}
  4669. */
  4670. const pow2 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 2 ).setParameterLength( 1 );
  4671. /**
  4672. * Returns the cube of the parameter.
  4673. *
  4674. * @tsl
  4675. * @function
  4676. * @param {Node | number} x - The first parameter.
  4677. * @returns {Node}
  4678. */
  4679. const pow3 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 3 ).setParameterLength( 1 );
  4680. /**
  4681. * Returns the fourth power of the parameter.
  4682. *
  4683. * @tsl
  4684. * @function
  4685. * @param {Node | number} x - The first parameter.
  4686. * @returns {Node}
  4687. */
  4688. const pow4 = /*@__PURE__*/ nodeProxy( MathNode, MathNode.POW, 4 ).setParameterLength( 1 );
  4689. /**
  4690. * Transforms the direction of a vector by a matrix and then normalizes the result.
  4691. *
  4692. * @tsl
  4693. * @function
  4694. * @param {Node<vec2|vec3|vec4>} direction - The direction vector.
  4695. * @param {Node<mat2|mat3|mat4>} matrix - The transformation matrix.
  4696. * @returns {Node}
  4697. */
  4698. const transformDirection = /*@__PURE__*/ nodeProxy( MathNode, MathNode.TRANSFORM_DIRECTION ).setParameterLength( 2 );
  4699. /**
  4700. * Returns the cube root of a number.
  4701. *
  4702. * @tsl
  4703. * @function
  4704. * @param {Node | number} a - The first parameter.
  4705. * @returns {Node}
  4706. */
  4707. const cbrt = ( a ) => mul( sign( a ), pow( abs( a ), 1.0 / 3.0 ) );
  4708. /**
  4709. * Calculate the squared length of a vector.
  4710. *
  4711. * @tsl
  4712. * @function
  4713. * @param {Node<vec2|vec3|vec4>} a - The vector.
  4714. * @returns {Node<float>}
  4715. */
  4716. const lengthSq = ( a ) => dot( a, a );
  4717. /**
  4718. * Linearly interpolates between two values.
  4719. *
  4720. * @tsl
  4721. * @function
  4722. * @param {Node | number} a - The first parameter.
  4723. * @param {Node | number} b - The second parameter.
  4724. * @param {Node | number} t - The interpolation value.
  4725. * @returns {Node}
  4726. */
  4727. const mix = /*@__PURE__*/ nodeProxy( MathNode, MathNode.MIX ).setParameterLength( 3 );
  4728. /**
  4729. * Constrains a value to lie between two further values.
  4730. *
  4731. * @tsl
  4732. * @function
  4733. * @param {Node | number} value - The value to constrain.
  4734. * @param {Node | number} [low=0] - The lower bound.
  4735. * @param {Node | number} [high=1] - The upper bound.
  4736. * @returns {Node}
  4737. */
  4738. const clamp = ( value, low = 0, high = 1 ) => nodeObject( new MathNode( MathNode.CLAMP, nodeObject( value ), nodeObject( low ), nodeObject( high ) ) );
  4739. /**
  4740. * Constrains a value between `0` and `1`.
  4741. *
  4742. * @tsl
  4743. * @function
  4744. * @param {Node | number} value - The value to constrain.
  4745. * @returns {Node}
  4746. */
  4747. const saturate = ( value ) => clamp( value );
  4748. /**
  4749. * Calculates the refraction direction for an incident vector.
  4750. *
  4751. * @tsl
  4752. * @function
  4753. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4754. * @param {Node<vec2|vec3|vec4>} N - The normal vector.
  4755. * @param {Node<float>} eta - The ratio of indices of refraction.
  4756. * @returns {Node<vec2|vec3|vec4>}
  4757. */
  4758. const refract = /*@__PURE__*/ nodeProxy( MathNode, MathNode.REFRACT ).setParameterLength( 3 );
  4759. /**
  4760. * Performs a Hermite interpolation between two values.
  4761. *
  4762. * @tsl
  4763. * @function
  4764. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4765. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4766. * @param {Node | number} x - The source value for interpolation.
  4767. * @returns {Node}
  4768. */
  4769. const smoothstep = /*@__PURE__*/ nodeProxy( MathNode, MathNode.SMOOTHSTEP ).setParameterLength( 3 );
  4770. /**
  4771. * Returns a vector pointing in the same direction as another.
  4772. *
  4773. * @tsl
  4774. * @function
  4775. * @param {Node<vec2|vec3|vec4>} N - The vector to orient.
  4776. * @param {Node<vec2|vec3|vec4>} I - The incident vector.
  4777. * @param {Node<vec2|vec3|vec4>} Nref - The reference vector.
  4778. * @returns {Node<vec2|vec3|vec4>}
  4779. */
  4780. const faceForward = /*@__PURE__*/ nodeProxy( MathNode, MathNode.FACEFORWARD ).setParameterLength( 3 );
  4781. /**
  4782. * Returns a random value for the given uv.
  4783. *
  4784. * @tsl
  4785. * @function
  4786. * @param {Node<vec2>} uv - The uv node.
  4787. * @returns {Node<float>}
  4788. */
  4789. const rand = /*@__PURE__*/ Fn( ( [ uv ] ) => {
  4790. const a = 12.9898, b = 78.233, c = 43758.5453;
  4791. const dt = dot( uv.xy, vec2( a, b ) ), sn = mod( dt, PI );
  4792. return fract( sin( sn ).mul( c ) );
  4793. } );
  4794. /**
  4795. * Alias for `mix()` with a different parameter order.
  4796. *
  4797. * @tsl
  4798. * @function
  4799. * @param {Node | number} t - The interpolation value.
  4800. * @param {Node | number} e1 - The first parameter.
  4801. * @param {Node | number} e2 - The second parameter.
  4802. * @returns {Node}
  4803. */
  4804. const mixElement = ( t, e1, e2 ) => mix( e1, e2, t );
  4805. /**
  4806. * Alias for `smoothstep()` with a different parameter order.
  4807. *
  4808. * @tsl
  4809. * @function
  4810. * @param {Node | number} x - The source value for interpolation.
  4811. * @param {Node | number} low - The value of the lower edge of the Hermite function.
  4812. * @param {Node | number} high - The value of the upper edge of the Hermite function.
  4813. * @returns {Node}
  4814. */
  4815. const smoothstepElement = ( x, low, high ) => smoothstep( low, high, x );
  4816. /**
  4817. * Returns the arc-tangent of the quotient of its parameters.
  4818. *
  4819. * @tsl
  4820. * @function
  4821. * @deprecated since r172. Use {@link atan} instead.
  4822. *
  4823. * @param {Node | number} y - The y parameter.
  4824. * @param {Node | number} x - The x parameter.
  4825. * @returns {Node}
  4826. */
  4827. const atan2 = ( y, x ) => { // @deprecated, r172
  4828. console.warn( 'THREE.TSL: "atan2" is overloaded. Use "atan" instead.' );
  4829. return atan( y, x );
  4830. };
  4831. // GLSL alias function
  4832. const faceforward = faceForward;
  4833. const inversesqrt = inverseSqrt;
  4834. // Method chaining
  4835. addMethodChaining( 'all', all );
  4836. addMethodChaining( 'any', any );
  4837. addMethodChaining( 'equals', equals );
  4838. addMethodChaining( 'radians', radians );
  4839. addMethodChaining( 'degrees', degrees );
  4840. addMethodChaining( 'exp', exp );
  4841. addMethodChaining( 'exp2', exp2 );
  4842. addMethodChaining( 'log', log );
  4843. addMethodChaining( 'log2', log2 );
  4844. addMethodChaining( 'sqrt', sqrt );
  4845. addMethodChaining( 'inverseSqrt', inverseSqrt );
  4846. addMethodChaining( 'floor', floor );
  4847. addMethodChaining( 'ceil', ceil );
  4848. addMethodChaining( 'normalize', normalize );
  4849. addMethodChaining( 'fract', fract );
  4850. addMethodChaining( 'sin', sin );
  4851. addMethodChaining( 'cos', cos );
  4852. addMethodChaining( 'tan', tan );
  4853. addMethodChaining( 'asin', asin );
  4854. addMethodChaining( 'acos', acos );
  4855. addMethodChaining( 'atan', atan );
  4856. addMethodChaining( 'abs', abs );
  4857. addMethodChaining( 'sign', sign );
  4858. addMethodChaining( 'length', length );
  4859. addMethodChaining( 'lengthSq', lengthSq );
  4860. addMethodChaining( 'negate', negate );
  4861. addMethodChaining( 'oneMinus', oneMinus );
  4862. addMethodChaining( 'dFdx', dFdx );
  4863. addMethodChaining( 'dFdy', dFdy );
  4864. addMethodChaining( 'round', round );
  4865. addMethodChaining( 'reciprocal', reciprocal );
  4866. addMethodChaining( 'trunc', trunc );
  4867. addMethodChaining( 'fwidth', fwidth );
  4868. addMethodChaining( 'atan2', atan2 );
  4869. addMethodChaining( 'min', min$1 );
  4870. addMethodChaining( 'max', max$1 );
  4871. addMethodChaining( 'step', step );
  4872. addMethodChaining( 'reflect', reflect );
  4873. addMethodChaining( 'distance', distance );
  4874. addMethodChaining( 'dot', dot );
  4875. addMethodChaining( 'cross', cross );
  4876. addMethodChaining( 'pow', pow );
  4877. addMethodChaining( 'pow2', pow2 );
  4878. addMethodChaining( 'pow3', pow3 );
  4879. addMethodChaining( 'pow4', pow4 );
  4880. addMethodChaining( 'transformDirection', transformDirection );
  4881. addMethodChaining( 'mix', mixElement );
  4882. addMethodChaining( 'clamp', clamp );
  4883. addMethodChaining( 'refract', refract );
  4884. addMethodChaining( 'smoothstep', smoothstepElement );
  4885. addMethodChaining( 'faceForward', faceForward );
  4886. addMethodChaining( 'difference', difference );
  4887. addMethodChaining( 'saturate', saturate );
  4888. addMethodChaining( 'cbrt', cbrt );
  4889. addMethodChaining( 'transpose', transpose );
  4890. addMethodChaining( 'rand', rand );
  4891. /**
  4892. * Represents a logical `if/else` statement. Can be used as an alternative
  4893. * to the `If()`/`Else()` syntax.
  4894. *
  4895. * The corresponding TSL `select()` looks like so:
  4896. * ```js
  4897. * velocity = position.greaterThanEqual( limit ).select( velocity.negate(), velocity );
  4898. * ```
  4899. * The `select()` method is called in a chaining fashion on a condition. The parameter nodes of `select()`
  4900. * determine the outcome of the entire statement.
  4901. *
  4902. * @augments Node
  4903. */
  4904. class ConditionalNode extends Node {
  4905. static get type() {
  4906. return 'ConditionalNode';
  4907. }
  4908. /**
  4909. * Constructs a new conditional node.
  4910. *
  4911. * @param {Node} condNode - The node that defines the condition.
  4912. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  4913. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  4914. */
  4915. constructor( condNode, ifNode, elseNode = null ) {
  4916. super();
  4917. /**
  4918. * The node that defines the condition.
  4919. *
  4920. * @type {Node}
  4921. */
  4922. this.condNode = condNode;
  4923. /**
  4924. * The node that is evaluate when the condition ends up `true`.
  4925. *
  4926. * @type {Node}
  4927. */
  4928. this.ifNode = ifNode;
  4929. /**
  4930. * The node that is evaluate when the condition ends up `false`.
  4931. *
  4932. * @type {?Node}
  4933. * @default null
  4934. */
  4935. this.elseNode = elseNode;
  4936. }
  4937. /**
  4938. * This method is overwritten since the node type is inferred from the if/else
  4939. * nodes.
  4940. *
  4941. * @param {NodeBuilder} builder - The current node builder.
  4942. * @return {string} The node type.
  4943. */
  4944. getNodeType( builder ) {
  4945. const { ifNode, elseNode } = builder.getNodeProperties( this );
  4946. if ( ifNode === undefined ) {
  4947. // fallback setup
  4948. this.setup( builder );
  4949. return this.getNodeType( builder );
  4950. }
  4951. const ifType = ifNode.getNodeType( builder );
  4952. if ( elseNode !== null ) {
  4953. const elseType = elseNode.getNodeType( builder );
  4954. if ( builder.getTypeLength( elseType ) > builder.getTypeLength( ifType ) ) {
  4955. return elseType;
  4956. }
  4957. }
  4958. return ifType;
  4959. }
  4960. setup( builder ) {
  4961. const condNode = this.condNode.cache();
  4962. const ifNode = this.ifNode.cache();
  4963. const elseNode = this.elseNode ? this.elseNode.cache() : null;
  4964. //
  4965. const currentNodeBlock = builder.context.nodeBlock;
  4966. builder.getDataFromNode( ifNode ).parentNodeBlock = currentNodeBlock;
  4967. if ( elseNode !== null ) builder.getDataFromNode( elseNode ).parentNodeBlock = currentNodeBlock;
  4968. //
  4969. const properties = builder.getNodeProperties( this );
  4970. properties.condNode = condNode;
  4971. properties.ifNode = ifNode.context( { nodeBlock: ifNode } );
  4972. properties.elseNode = elseNode ? elseNode.context( { nodeBlock: elseNode } ) : null;
  4973. }
  4974. generate( builder, output ) {
  4975. const type = this.getNodeType( builder );
  4976. const nodeData = builder.getDataFromNode( this );
  4977. if ( nodeData.nodeProperty !== undefined ) {
  4978. return nodeData.nodeProperty;
  4979. }
  4980. const { condNode, ifNode, elseNode } = builder.getNodeProperties( this );
  4981. const functionNode = builder.currentFunctionNode;
  4982. const needsOutput = output !== 'void';
  4983. const nodeProperty = needsOutput ? property( type ).build( builder ) : '';
  4984. nodeData.nodeProperty = nodeProperty;
  4985. const nodeSnippet = condNode.build( builder, 'bool' );
  4986. builder.addFlowCode( `\n${ builder.tab }if ( ${ nodeSnippet } ) {\n\n` ).addFlowTab();
  4987. let ifSnippet = ifNode.build( builder, type );
  4988. if ( ifSnippet ) {
  4989. if ( needsOutput ) {
  4990. ifSnippet = nodeProperty + ' = ' + ifSnippet + ';';
  4991. } else {
  4992. ifSnippet = 'return ' + ifSnippet + ';';
  4993. if ( functionNode === null ) {
  4994. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  4995. ifSnippet = '// ' + ifSnippet;
  4996. }
  4997. }
  4998. }
  4999. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + ifSnippet + '\n\n' + builder.tab + '}' );
  5000. if ( elseNode !== null ) {
  5001. builder.addFlowCode( ' else {\n\n' ).addFlowTab();
  5002. let elseSnippet = elseNode.build( builder, type );
  5003. if ( elseSnippet ) {
  5004. if ( needsOutput ) {
  5005. elseSnippet = nodeProperty + ' = ' + elseSnippet + ';';
  5006. } else {
  5007. elseSnippet = 'return ' + elseSnippet + ';';
  5008. if ( functionNode === null ) {
  5009. console.warn( 'THREE.TSL: Return statement used in an inline \'Fn()\'. Define a layout struct to allow return values.' );
  5010. elseSnippet = '// ' + elseSnippet;
  5011. }
  5012. }
  5013. }
  5014. builder.removeFlowTab().addFlowCode( builder.tab + '\t' + elseSnippet + '\n\n' + builder.tab + '}\n\n' );
  5015. } else {
  5016. builder.addFlowCode( '\n\n' );
  5017. }
  5018. return builder.format( nodeProperty, type, output );
  5019. }
  5020. }
  5021. /**
  5022. * TSL function for creating a conditional node.
  5023. *
  5024. * @tsl
  5025. * @function
  5026. * @param {Node} condNode - The node that defines the condition.
  5027. * @param {Node} ifNode - The node that is evaluate when the condition ends up `true`.
  5028. * @param {?Node} [elseNode=null] - The node that is evaluate when the condition ends up `false`.
  5029. * @returns {ConditionalNode}
  5030. */
  5031. const select = /*@__PURE__*/ nodeProxy( ConditionalNode ).setParameterLength( 2, 3 );
  5032. addMethodChaining( 'select', select );
  5033. // Deprecated
  5034. /**
  5035. * @tsl
  5036. * @function
  5037. * @deprecated since r168. Use {@link select} instead.
  5038. *
  5039. * @param {...any} params
  5040. * @returns {ConditionalNode}
  5041. */
  5042. const cond = ( ...params ) => { // @deprecated, r168
  5043. console.warn( 'THREE.TSL: cond() has been renamed to select().' );
  5044. return select( ...params );
  5045. };
  5046. addMethodChaining( 'cond', cond );
  5047. /**
  5048. * This node can be used as a context management component for another node.
  5049. * {@link NodeBuilder} performs its node building process in a specific context and
  5050. * this node allows the modify the context. A typical use case is to overwrite `getUV()` e.g.:
  5051. *
  5052. * ```js
  5053. *node.context( { getUV: () => customCoord } );
  5054. *```
  5055. * @augments Node
  5056. */
  5057. class ContextNode extends Node {
  5058. static get type() {
  5059. return 'ContextNode';
  5060. }
  5061. /**
  5062. * Constructs a new context node.
  5063. *
  5064. * @param {Node} node - The node whose context should be modified.
  5065. * @param {Object} [value={}] - The modified context data.
  5066. */
  5067. constructor( node, value = {} ) {
  5068. super();
  5069. /**
  5070. * This flag can be used for type testing.
  5071. *
  5072. * @type {boolean}
  5073. * @readonly
  5074. * @default true
  5075. */
  5076. this.isContextNode = true;
  5077. /**
  5078. * The node whose context should be modified.
  5079. *
  5080. * @type {Node}
  5081. */
  5082. this.node = node;
  5083. /**
  5084. * The modified context data.
  5085. *
  5086. * @type {Object}
  5087. * @default {}
  5088. */
  5089. this.value = value;
  5090. }
  5091. /**
  5092. * This method is overwritten to ensure it returns the reference to {@link ContextNode#node}.
  5093. *
  5094. * @return {Node} A reference to {@link ContextNode#node}.
  5095. */
  5096. getScope() {
  5097. return this.node.getScope();
  5098. }
  5099. /**
  5100. * This method is overwritten to ensure it returns the type of {@link ContextNode#node}.
  5101. *
  5102. * @param {NodeBuilder} builder - The current node builder.
  5103. * @return {string} The node type.
  5104. */
  5105. getNodeType( builder ) {
  5106. return this.node.getNodeType( builder );
  5107. }
  5108. analyze( builder ) {
  5109. const previousContext = builder.getContext();
  5110. builder.setContext( { ...builder.context, ...this.value } );
  5111. this.node.build( builder );
  5112. builder.setContext( previousContext );
  5113. }
  5114. setup( builder ) {
  5115. const previousContext = builder.getContext();
  5116. builder.setContext( { ...builder.context, ...this.value } );
  5117. this.node.build( builder );
  5118. builder.setContext( previousContext );
  5119. }
  5120. generate( builder, output ) {
  5121. const previousContext = builder.getContext();
  5122. builder.setContext( { ...builder.context, ...this.value } );
  5123. const snippet = this.node.build( builder, output );
  5124. builder.setContext( previousContext );
  5125. return snippet;
  5126. }
  5127. }
  5128. /**
  5129. * TSL function for creating a context node.
  5130. *
  5131. * @tsl
  5132. * @function
  5133. * @param {Node} node - The node whose context should be modified.
  5134. * @param {Object} [value={}] - The modified context data.
  5135. * @returns {ContextNode}
  5136. */
  5137. const context = /*@__PURE__*/ nodeProxy( ContextNode ).setParameterLength( 1, 2 );
  5138. /**
  5139. * TSL function for defining a label context value for a given node.
  5140. *
  5141. * @tsl
  5142. * @function
  5143. * @param {Node} node - The node whose context should be modified.
  5144. * @param {string} name - The name/label to set.
  5145. * @returns {ContextNode}
  5146. */
  5147. const label = ( node, name ) => context( node, { label: name } );
  5148. addMethodChaining( 'context', context );
  5149. addMethodChaining( 'label', label );
  5150. /**
  5151. * Class for representing shader variables as nodes. Variables are created from
  5152. * existing nodes like the following:
  5153. *
  5154. * ```js
  5155. * const depth = sampleDepth( uvNode ).toVar( 'depth' );
  5156. * ```
  5157. *
  5158. * @augments Node
  5159. */
  5160. class VarNode extends Node {
  5161. static get type() {
  5162. return 'VarNode';
  5163. }
  5164. /**
  5165. * Constructs a new variable node.
  5166. *
  5167. * @param {Node} node - The node for which a variable should be created.
  5168. * @param {?string} [name=null] - The name of the variable in the shader.
  5169. * @param {boolean} [readOnly=false] - The read-only flag.
  5170. */
  5171. constructor( node, name = null, readOnly = false ) {
  5172. super();
  5173. /**
  5174. * The node for which a variable should be created.
  5175. *
  5176. * @type {Node}
  5177. */
  5178. this.node = node;
  5179. /**
  5180. * The name of the variable in the shader. If no name is defined,
  5181. * the node system auto-generates one.
  5182. *
  5183. * @type {?string}
  5184. * @default null
  5185. */
  5186. this.name = name;
  5187. /**
  5188. * `VarNode` sets this property to `true` by default.
  5189. *
  5190. * @type {boolean}
  5191. * @default true
  5192. */
  5193. this.global = true;
  5194. /**
  5195. * This flag can be used for type testing.
  5196. *
  5197. * @type {boolean}
  5198. * @readonly
  5199. * @default true
  5200. */
  5201. this.isVarNode = true;
  5202. /**
  5203. *
  5204. * The read-only flag.
  5205. *
  5206. * @type {boolean}
  5207. * @default false
  5208. */
  5209. this.readOnly = readOnly;
  5210. /**
  5211. *
  5212. * Add this flag to the node system to indicate that this node require parents.
  5213. *
  5214. * @type {boolean}
  5215. * @default true
  5216. */
  5217. this.parents = true;
  5218. }
  5219. getMemberType( builder, name ) {
  5220. return this.node.getMemberType( builder, name );
  5221. }
  5222. getElementType( builder ) {
  5223. return this.node.getElementType( builder );
  5224. }
  5225. getNodeType( builder ) {
  5226. return this.node.getNodeType( builder );
  5227. }
  5228. generate( builder ) {
  5229. const { node, name, readOnly } = this;
  5230. const { renderer } = builder;
  5231. const isWebGPUBackend = renderer.backend.isWebGPUBackend === true;
  5232. let isDeterministic = false;
  5233. let shouldTreatAsReadOnly = false;
  5234. if ( readOnly ) {
  5235. isDeterministic = builder.isDeterministic( node );
  5236. shouldTreatAsReadOnly = isWebGPUBackend ? readOnly : isDeterministic;
  5237. }
  5238. const vectorType = builder.getVectorType( this.getNodeType( builder ) );
  5239. const snippet = node.build( builder, vectorType );
  5240. const nodeVar = builder.getVarFromNode( this, name, vectorType, undefined, shouldTreatAsReadOnly );
  5241. const propertyName = builder.getPropertyName( nodeVar );
  5242. let declarationPrefix = propertyName;
  5243. if ( shouldTreatAsReadOnly ) {
  5244. if ( isWebGPUBackend ) {
  5245. declarationPrefix = isDeterministic
  5246. ? `const ${ propertyName }`
  5247. : `let ${ propertyName }`;
  5248. } else {
  5249. const count = builder.getArrayCount( node );
  5250. declarationPrefix = `const ${ builder.getVar( nodeVar.type, propertyName, count ) }`;
  5251. }
  5252. }
  5253. builder.addLineFlowCode( `${ declarationPrefix } = ${ snippet }`, this );
  5254. return propertyName;
  5255. }
  5256. }
  5257. /**
  5258. * TSL function for creating a var node.
  5259. *
  5260. * @tsl
  5261. * @function
  5262. * @param {Node} node - The node for which a variable should be created.
  5263. * @param {?string} name - The name of the variable in the shader.
  5264. * @returns {VarNode}
  5265. */
  5266. const createVar = /*@__PURE__*/ nodeProxy( VarNode );
  5267. /**
  5268. * TSL function for creating a var node.
  5269. *
  5270. * @tsl
  5271. * @function
  5272. * @param {Node} node - The node for which a variable should be created.
  5273. * @param {?string} name - The name of the variable in the shader.
  5274. * @returns {VarNode}
  5275. */
  5276. const Var = ( node, name = null ) => createVar( node, name ).toStack();
  5277. /**
  5278. * TSL function for creating a const node.
  5279. *
  5280. * @tsl
  5281. * @function
  5282. * @param {Node} node - The node for which a constant should be created.
  5283. * @param {?string} name - The name of the constant in the shader.
  5284. * @returns {VarNode}
  5285. */
  5286. const Const = ( node, name = null ) => createVar( node, name, true ).toStack();
  5287. // Method chaining
  5288. addMethodChaining( 'toVar', Var );
  5289. addMethodChaining( 'toConst', Const );
  5290. // Deprecated
  5291. /**
  5292. * @tsl
  5293. * @function
  5294. * @deprecated since r170. Use `Var( node )` or `node.toVar()` instead.
  5295. *
  5296. * @param {any} node
  5297. * @returns {VarNode}
  5298. */
  5299. const temp = ( node ) => { // @deprecated, r170
  5300. console.warn( 'TSL: "temp( node )" is deprecated. Use "Var( node )" or "node.toVar()" instead.' );
  5301. return createVar( node );
  5302. };
  5303. addMethodChaining( 'temp', temp );
  5304. /**
  5305. * Class for representing shader varyings as nodes. Varyings are create from
  5306. * existing nodes like the following:
  5307. *
  5308. * ```js
  5309. * const positionLocal = positionGeometry.toVarying( 'vPositionLocal' );
  5310. * ```
  5311. *
  5312. * @augments Node
  5313. */
  5314. class VaryingNode extends Node {
  5315. static get type() {
  5316. return 'VaryingNode';
  5317. }
  5318. /**
  5319. * Constructs a new varying node.
  5320. *
  5321. * @param {Node} node - The node for which a varying should be created.
  5322. * @param {?string} name - The name of the varying in the shader.
  5323. */
  5324. constructor( node, name = null ) {
  5325. super();
  5326. /**
  5327. * The node for which a varying should be created.
  5328. *
  5329. * @type {Node}
  5330. */
  5331. this.node = node;
  5332. /**
  5333. * The name of the varying in the shader. If no name is defined,
  5334. * the node system auto-generates one.
  5335. *
  5336. * @type {?string}
  5337. * @default null
  5338. */
  5339. this.name = name;
  5340. /**
  5341. * This flag can be used for type testing.
  5342. *
  5343. * @type {boolean}
  5344. * @readonly
  5345. * @default true
  5346. */
  5347. this.isVaryingNode = true;
  5348. /**
  5349. * The interpolation type of the varying data.
  5350. *
  5351. * @type {?string}
  5352. * @default null
  5353. */
  5354. this.interpolationType = null;
  5355. /**
  5356. * The interpolation sampling type of varying data.
  5357. *
  5358. * @type {?string}
  5359. * @default null
  5360. */
  5361. this.interpolationSampling = null;
  5362. /**
  5363. * This flag is used for global cache.
  5364. *
  5365. * @type {boolean}
  5366. * @default true
  5367. */
  5368. this.global = true;
  5369. }
  5370. /**
  5371. * Defines the interpolation type of the varying.
  5372. *
  5373. * @param {string} type - The interpolation type.
  5374. * @param {?string} sampling - The interpolation sampling type
  5375. * @return {VaryingNode} A reference to this node.
  5376. */
  5377. setInterpolation( type, sampling = null ) {
  5378. this.interpolationType = type;
  5379. this.interpolationSampling = sampling;
  5380. return this;
  5381. }
  5382. getHash( builder ) {
  5383. return this.name || super.getHash( builder );
  5384. }
  5385. getNodeType( builder ) {
  5386. // VaryingNode is auto type
  5387. return this.node.getNodeType( builder );
  5388. }
  5389. /**
  5390. * This method performs the setup of a varying node with the current node builder.
  5391. *
  5392. * @param {NodeBuilder} builder - The current node builder.
  5393. * @return {NodeVarying} The node varying from the node builder.
  5394. */
  5395. setupVarying( builder ) {
  5396. const properties = builder.getNodeProperties( this );
  5397. let varying = properties.varying;
  5398. if ( varying === undefined ) {
  5399. const name = this.name;
  5400. const type = this.getNodeType( builder );
  5401. const interpolationType = this.interpolationType;
  5402. const interpolationSampling = this.interpolationSampling;
  5403. properties.varying = varying = builder.getVaryingFromNode( this, name, type, interpolationType, interpolationSampling );
  5404. properties.node = this.node;
  5405. }
  5406. // this property can be used to check if the varying can be optimized for a variable
  5407. varying.needsInterpolation || ( varying.needsInterpolation = ( builder.shaderStage === 'fragment' ) );
  5408. return varying;
  5409. }
  5410. setup( builder ) {
  5411. this.setupVarying( builder );
  5412. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5413. }
  5414. analyze( builder ) {
  5415. this.setupVarying( builder );
  5416. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node );
  5417. }
  5418. generate( builder ) {
  5419. const properties = builder.getNodeProperties( this );
  5420. const varying = this.setupVarying( builder );
  5421. if ( properties.propertyName === undefined ) {
  5422. const type = this.getNodeType( builder );
  5423. const propertyName = builder.getPropertyName( varying, NodeShaderStage.VERTEX );
  5424. // force node run in vertex stage
  5425. builder.flowNodeFromShaderStage( NodeShaderStage.VERTEX, this.node, type, propertyName );
  5426. properties.propertyName = propertyName;
  5427. }
  5428. return builder.getPropertyName( varying );
  5429. }
  5430. }
  5431. /**
  5432. * TSL function for creating a varying node.
  5433. *
  5434. * @tsl
  5435. * @function
  5436. * @param {Node} node - The node for which a varying should be created.
  5437. * @param {?string} name - The name of the varying in the shader.
  5438. * @returns {VaryingNode}
  5439. */
  5440. const varying = /*@__PURE__*/ nodeProxy( VaryingNode ).setParameterLength( 1, 2 );
  5441. /**
  5442. * Computes a node in the vertex stage.
  5443. *
  5444. * @tsl
  5445. * @function
  5446. * @param {Node} node - The node which should be executed in the vertex stage.
  5447. * @returns {VaryingNode}
  5448. */
  5449. const vertexStage = ( node ) => varying( node );
  5450. addMethodChaining( 'toVarying', varying );
  5451. addMethodChaining( 'toVertexStage', vertexStage );
  5452. // Deprecated
  5453. addMethodChaining( 'varying', ( ...params ) => { // @deprecated, r173
  5454. console.warn( 'THREE.TSL: .varying() has been renamed to .toVarying().' );
  5455. return varying( ...params );
  5456. } );
  5457. addMethodChaining( 'vertexStage', ( ...params ) => { // @deprecated, r173
  5458. console.warn( 'THREE.TSL: .vertexStage() has been renamed to .toVertexStage().' );
  5459. return varying( ...params );
  5460. } );
  5461. /**
  5462. * Converts the given color value from sRGB to linear-sRGB color space.
  5463. *
  5464. * @tsl
  5465. * @function
  5466. * @param {Node<vec3>} color - The sRGB color.
  5467. * @return {Node<vec3>} The linear-sRGB color.
  5468. */
  5469. const sRGBTransferEOTF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5470. const a = color.mul( 0.9478672986 ).add( 0.0521327014 ).pow( 2.4 );
  5471. const b = color.mul( 0.0773993808 );
  5472. const factor = color.lessThanEqual( 0.04045 );
  5473. const rgbResult = mix( a, b, factor );
  5474. return rgbResult;
  5475. } ).setLayout( {
  5476. name: 'sRGBTransferEOTF',
  5477. type: 'vec3',
  5478. inputs: [
  5479. { name: 'color', type: 'vec3' }
  5480. ]
  5481. } );
  5482. /**
  5483. * Converts the given color value from linear-sRGB to sRGB color space.
  5484. *
  5485. * @tsl
  5486. * @function
  5487. * @param {Node<vec3>} color - The linear-sRGB color.
  5488. * @return {Node<vec3>} The sRGB color.
  5489. */
  5490. const sRGBTransferOETF = /*@__PURE__*/ Fn( ( [ color ] ) => {
  5491. const a = color.pow( 0.41666 ).mul( 1.055 ).sub( 0.055 );
  5492. const b = color.mul( 12.92 );
  5493. const factor = color.lessThanEqual( 0.0031308 );
  5494. const rgbResult = mix( a, b, factor );
  5495. return rgbResult;
  5496. } ).setLayout( {
  5497. name: 'sRGBTransferOETF',
  5498. type: 'vec3',
  5499. inputs: [
  5500. { name: 'color', type: 'vec3' }
  5501. ]
  5502. } );
  5503. const WORKING_COLOR_SPACE = 'WorkingColorSpace';
  5504. const OUTPUT_COLOR_SPACE = 'OutputColorSpace';
  5505. /**
  5506. * This node represents a color space conversion. Meaning it converts
  5507. * a color value from a source to a target color space.
  5508. *
  5509. * @augments TempNode
  5510. */
  5511. class ColorSpaceNode extends TempNode {
  5512. static get type() {
  5513. return 'ColorSpaceNode';
  5514. }
  5515. /**
  5516. * Constructs a new color space node.
  5517. *
  5518. * @param {Node} colorNode - Represents the color to convert.
  5519. * @param {string} source - The source color space.
  5520. * @param {string} target - The target color space.
  5521. */
  5522. constructor( colorNode, source, target ) {
  5523. super( 'vec4' );
  5524. /**
  5525. * Represents the color to convert.
  5526. *
  5527. * @type {Node}
  5528. */
  5529. this.colorNode = colorNode;
  5530. /**
  5531. * The source color space.
  5532. *
  5533. * @type {string}
  5534. */
  5535. this.source = source;
  5536. /**
  5537. * The target color space.
  5538. *
  5539. * @type {string}
  5540. */
  5541. this.target = target;
  5542. }
  5543. /**
  5544. * This method resolves the constants `WORKING_COLOR_SPACE` and
  5545. * `OUTPUT_COLOR_SPACE` based on the current configuration of the
  5546. * color management and renderer.
  5547. *
  5548. * @param {NodeBuilder} builder - The current node builder.
  5549. * @param {string} colorSpace - The color space to resolve.
  5550. * @return {string} The resolved color space.
  5551. */
  5552. resolveColorSpace( builder, colorSpace ) {
  5553. if ( colorSpace === WORKING_COLOR_SPACE ) {
  5554. return ColorManagement.workingColorSpace;
  5555. } else if ( colorSpace === OUTPUT_COLOR_SPACE ) {
  5556. return builder.context.outputColorSpace || builder.renderer.outputColorSpace;
  5557. }
  5558. return colorSpace;
  5559. }
  5560. setup( builder ) {
  5561. const { colorNode } = this;
  5562. const source = this.resolveColorSpace( builder, this.source );
  5563. const target = this.resolveColorSpace( builder, this.target );
  5564. let outputNode = colorNode;
  5565. if ( ColorManagement.enabled === false || source === target || ! source || ! target ) {
  5566. return outputNode;
  5567. }
  5568. if ( ColorManagement.getTransfer( source ) === SRGBTransfer ) {
  5569. outputNode = vec4( sRGBTransferEOTF( outputNode.rgb ), outputNode.a );
  5570. }
  5571. if ( ColorManagement.getPrimaries( source ) !== ColorManagement.getPrimaries( target ) ) {
  5572. outputNode = vec4(
  5573. mat3( ColorManagement._getMatrix( new Matrix3(), source, target ) ).mul( outputNode.rgb ),
  5574. outputNode.a
  5575. );
  5576. }
  5577. if ( ColorManagement.getTransfer( target ) === SRGBTransfer ) {
  5578. outputNode = vec4( sRGBTransferOETF( outputNode.rgb ), outputNode.a );
  5579. }
  5580. return outputNode;
  5581. }
  5582. }
  5583. /**
  5584. * TSL function for converting a given color node from the current working color space to the given color space.
  5585. *
  5586. * @tsl
  5587. * @function
  5588. * @param {Node} node - Represents the node to convert.
  5589. * @param {string} targetColorSpace - The target color space.
  5590. * @returns {ColorSpaceNode}
  5591. */
  5592. const workingToColorSpace = ( node, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), WORKING_COLOR_SPACE, targetColorSpace ) );
  5593. /**
  5594. * TSL function for converting a given color node from the given color space to the current working color space.
  5595. *
  5596. * @tsl
  5597. * @function
  5598. * @param {Node} node - Represents the node to convert.
  5599. * @param {string} sourceColorSpace - The source color space.
  5600. * @returns {ColorSpaceNode}
  5601. */
  5602. const colorSpaceToWorking = ( node, sourceColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, WORKING_COLOR_SPACE ) );
  5603. /**
  5604. * TSL function for converting a given color node from one color space to another one.
  5605. *
  5606. * @tsl
  5607. * @function
  5608. * @param {Node} node - Represents the node to convert.
  5609. * @param {string} sourceColorSpace - The source color space.
  5610. * @param {string} targetColorSpace - The target color space.
  5611. * @returns {ColorSpaceNode}
  5612. */
  5613. const convertColorSpace = ( node, sourceColorSpace, targetColorSpace ) => nodeObject( new ColorSpaceNode( nodeObject( node ), sourceColorSpace, targetColorSpace ) );
  5614. addMethodChaining( 'workingToColorSpace', workingToColorSpace );
  5615. addMethodChaining( 'colorSpaceToWorking', colorSpaceToWorking );
  5616. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  5617. /**
  5618. * This class is only relevant if the referenced property is array-like.
  5619. * In this case, `ReferenceElementNode` allows to refer to a specific
  5620. * element inside the data structure via an index.
  5621. *
  5622. * @augments ArrayElementNode
  5623. */
  5624. let ReferenceElementNode$1 = class ReferenceElementNode extends ArrayElementNode {
  5625. static get type() {
  5626. return 'ReferenceElementNode';
  5627. }
  5628. /**
  5629. * Constructs a new reference element node.
  5630. *
  5631. * @param {ReferenceBaseNode} referenceNode - The reference node.
  5632. * @param {Node} indexNode - The index node that defines the element access.
  5633. */
  5634. constructor( referenceNode, indexNode ) {
  5635. super( referenceNode, indexNode );
  5636. /**
  5637. * Similar to {@link ReferenceBaseNode#reference}, an additional
  5638. * property references to the current node.
  5639. *
  5640. * @type {?ReferenceBaseNode}
  5641. * @default null
  5642. */
  5643. this.referenceNode = referenceNode;
  5644. /**
  5645. * This flag can be used for type testing.
  5646. *
  5647. * @type {boolean}
  5648. * @readonly
  5649. * @default true
  5650. */
  5651. this.isReferenceElementNode = true;
  5652. }
  5653. /**
  5654. * This method is overwritten since the node type is inferred from
  5655. * the uniform type of the reference node.
  5656. *
  5657. * @return {string} The node type.
  5658. */
  5659. getNodeType() {
  5660. return this.referenceNode.uniformType;
  5661. }
  5662. generate( builder ) {
  5663. const snippet = super.generate( builder );
  5664. const arrayType = this.referenceNode.getNodeType();
  5665. const elementType = this.getNodeType();
  5666. return builder.format( snippet, arrayType, elementType );
  5667. }
  5668. };
  5669. /**
  5670. * Base class for nodes which establishes a reference to a property of another object.
  5671. * In this way, the value of the node is automatically linked to the value of
  5672. * referenced object. Reference nodes internally represent the linked value
  5673. * as a uniform.
  5674. *
  5675. * @augments Node
  5676. */
  5677. class ReferenceBaseNode extends Node {
  5678. static get type() {
  5679. return 'ReferenceBaseNode';
  5680. }
  5681. /**
  5682. * Constructs a new reference base node.
  5683. *
  5684. * @param {string} property - The name of the property the node refers to.
  5685. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  5686. * @param {?Object} [object=null] - The object the property belongs to.
  5687. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  5688. */
  5689. constructor( property, uniformType, object = null, count = null ) {
  5690. super();
  5691. /**
  5692. * The name of the property the node refers to.
  5693. *
  5694. * @type {string}
  5695. */
  5696. this.property = property;
  5697. /**
  5698. * The uniform type that should be used to represent the property value.
  5699. *
  5700. * @type {string}
  5701. */
  5702. this.uniformType = uniformType;
  5703. /**
  5704. * The object the property belongs to.
  5705. *
  5706. * @type {?Object}
  5707. * @default null
  5708. */
  5709. this.object = object;
  5710. /**
  5711. * When the linked property is an array, this parameter defines its length.
  5712. *
  5713. * @type {?number}
  5714. * @default null
  5715. */
  5716. this.count = count;
  5717. /**
  5718. * The property name might have dots so nested properties can be referred.
  5719. * The hierarchy of the names is stored inside this array.
  5720. *
  5721. * @type {Array<string>}
  5722. */
  5723. this.properties = property.split( '.' );
  5724. /**
  5725. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  5726. * since the final reference might be updated from calling code.
  5727. *
  5728. * @type {?Object}
  5729. * @default null
  5730. */
  5731. this.reference = object;
  5732. /**
  5733. * The uniform node that holds the value of the reference node.
  5734. *
  5735. * @type {UniformNode}
  5736. * @default null
  5737. */
  5738. this.node = null;
  5739. /**
  5740. * The uniform group of the internal uniform.
  5741. *
  5742. * @type {UniformGroupNode}
  5743. * @default null
  5744. */
  5745. this.group = null;
  5746. /**
  5747. * Overwritten since reference nodes are updated per object.
  5748. *
  5749. * @type {string}
  5750. * @default 'object'
  5751. */
  5752. this.updateType = NodeUpdateType.OBJECT;
  5753. }
  5754. /**
  5755. * Sets the uniform group for this reference node.
  5756. *
  5757. * @param {UniformGroupNode} group - The uniform group to set.
  5758. * @return {ReferenceBaseNode} A reference to this node.
  5759. */
  5760. setGroup( group ) {
  5761. this.group = group;
  5762. return this;
  5763. }
  5764. /**
  5765. * When the referred property is array-like, this method can be used
  5766. * to access elements via an index node.
  5767. *
  5768. * @param {IndexNode} indexNode - indexNode.
  5769. * @return {ReferenceElementNode} A reference to an element.
  5770. */
  5771. element( indexNode ) {
  5772. return nodeObject( new ReferenceElementNode$1( this, nodeObject( indexNode ) ) );
  5773. }
  5774. /**
  5775. * Sets the node type which automatically defines the internal
  5776. * uniform type.
  5777. *
  5778. * @param {string} uniformType - The type to set.
  5779. */
  5780. setNodeType( uniformType ) {
  5781. const node = uniform( null, uniformType ).getSelf();
  5782. if ( this.group !== null ) {
  5783. node.setGroup( this.group );
  5784. }
  5785. this.node = node;
  5786. }
  5787. /**
  5788. * This method is overwritten since the node type is inferred from
  5789. * the type of the reference node.
  5790. *
  5791. * @param {NodeBuilder} builder - The current node builder.
  5792. * @return {string} The node type.
  5793. */
  5794. getNodeType( builder ) {
  5795. if ( this.node === null ) {
  5796. this.updateReference( builder );
  5797. this.updateValue();
  5798. }
  5799. return this.node.getNodeType( builder );
  5800. }
  5801. /**
  5802. * Returns the property value from the given referred object.
  5803. *
  5804. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  5805. * @return {any} The value.
  5806. */
  5807. getValueFromReference( object = this.reference ) {
  5808. const { properties } = this;
  5809. let value = object[ properties[ 0 ] ];
  5810. for ( let i = 1; i < properties.length; i ++ ) {
  5811. value = value[ properties[ i ] ];
  5812. }
  5813. return value;
  5814. }
  5815. /**
  5816. * Allows to update the reference based on the given state. The state is only
  5817. * evaluated {@link ReferenceBaseNode#object} is not set.
  5818. *
  5819. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5820. * @return {Object} The updated reference.
  5821. */
  5822. updateReference( state ) {
  5823. this.reference = this.object !== null ? this.object : state.object;
  5824. return this.reference;
  5825. }
  5826. /**
  5827. * The output of the reference node is the internal uniform node.
  5828. *
  5829. * @return {UniformNode} The output node.
  5830. */
  5831. setup() {
  5832. this.updateValue();
  5833. return this.node;
  5834. }
  5835. /**
  5836. * Overwritten to update the internal uniform value.
  5837. *
  5838. * @param {NodeFrame} frame - A reference to the current node frame.
  5839. */
  5840. update( /*frame*/ ) {
  5841. this.updateValue();
  5842. }
  5843. /**
  5844. * Retrieves the value from the referred object property and uses it
  5845. * to updated the internal uniform.
  5846. */
  5847. updateValue() {
  5848. if ( this.node === null ) this.setNodeType( this.uniformType );
  5849. const value = this.getValueFromReference();
  5850. if ( Array.isArray( value ) ) {
  5851. this.node.array = value;
  5852. } else {
  5853. this.node.value = value;
  5854. }
  5855. }
  5856. }
  5857. /**
  5858. * TSL function for creating a reference base node.
  5859. *
  5860. * @tsl
  5861. * @function
  5862. * @param {string} name - The name of the property the node refers to.
  5863. * @param {string} type - The uniform type that should be used to represent the property value.
  5864. * @param {Object} object - The object the property belongs to.
  5865. * @returns {ReferenceBaseNode}
  5866. */
  5867. const reference$1 = ( name, type, object ) => nodeObject( new ReferenceBaseNode( name, type, object ) );
  5868. /**
  5869. * This node is a special type of reference node which is intended
  5870. * for linking renderer properties with node values.
  5871. * ```js
  5872. * const exposureNode = rendererReference( 'toneMappingExposure', 'float', renderer );
  5873. * ```
  5874. * When changing `renderer.toneMappingExposure`, the node value of `exposureNode` will
  5875. * automatically be updated.
  5876. *
  5877. * @augments ReferenceBaseNode
  5878. */
  5879. class RendererReferenceNode extends ReferenceBaseNode {
  5880. static get type() {
  5881. return 'RendererReferenceNode';
  5882. }
  5883. /**
  5884. * Constructs a new renderer reference node.
  5885. *
  5886. * @param {string} property - The name of the property the node refers to.
  5887. * @param {string} inputType - The uniform type that should be used to represent the property value.
  5888. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5889. * the node refers to the renderer of the current state.
  5890. */
  5891. constructor( property, inputType, renderer = null ) {
  5892. super( property, inputType, renderer );
  5893. /**
  5894. * The renderer the property belongs to. When no renderer is set,
  5895. * the node refers to the renderer of the current state.
  5896. *
  5897. * @type {?Renderer}
  5898. * @default null
  5899. */
  5900. this.renderer = renderer;
  5901. this.setGroup( renderGroup );
  5902. }
  5903. /**
  5904. * Updates the reference based on the given state. The state is only evaluated
  5905. * {@link RendererReferenceNode#renderer} is not set.
  5906. *
  5907. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  5908. * @return {Object} The updated reference.
  5909. */
  5910. updateReference( state ) {
  5911. this.reference = this.renderer !== null ? this.renderer : state.renderer;
  5912. return this.reference;
  5913. }
  5914. }
  5915. /**
  5916. * TSL function for creating a renderer reference node.
  5917. *
  5918. * @tsl
  5919. * @function
  5920. * @param {string} name - The name of the property the node refers to.
  5921. * @param {string} type - The uniform type that should be used to represent the property value.
  5922. * @param {?Renderer} [renderer=null] - The renderer the property belongs to. When no renderer is set,
  5923. * the node refers to the renderer of the current state.
  5924. * @returns {RendererReferenceNode}
  5925. */
  5926. const rendererReference = ( name, type, renderer = null ) => nodeObject( new RendererReferenceNode( name, type, renderer ) );
  5927. /**
  5928. * This node represents a tone mapping operation.
  5929. *
  5930. * @augments TempNode
  5931. */
  5932. class ToneMappingNode extends TempNode {
  5933. static get type() {
  5934. return 'ToneMappingNode';
  5935. }
  5936. /**
  5937. * Constructs a new tone mapping node.
  5938. *
  5939. * @param {number} toneMapping - The tone mapping type.
  5940. * @param {Node} exposureNode - The tone mapping exposure.
  5941. * @param {Node} [colorNode=null] - The color node to process.
  5942. */
  5943. constructor( toneMapping, exposureNode = toneMappingExposure, colorNode = null ) {
  5944. super( 'vec3' );
  5945. /**
  5946. * The tone mapping type.
  5947. *
  5948. * @type {number}
  5949. */
  5950. this.toneMapping = toneMapping;
  5951. /**
  5952. * The tone mapping exposure.
  5953. *
  5954. * @type {Node}
  5955. * @default null
  5956. */
  5957. this.exposureNode = exposureNode;
  5958. /**
  5959. * Represents the color to process.
  5960. *
  5961. * @type {?Node}
  5962. * @default null
  5963. */
  5964. this.colorNode = colorNode;
  5965. }
  5966. /**
  5967. * Overwrites the default `customCacheKey()` implementation by including the tone
  5968. * mapping type into the cache key.
  5969. *
  5970. * @return {number} The hash.
  5971. */
  5972. customCacheKey() {
  5973. return hash$1( this.toneMapping );
  5974. }
  5975. setup( builder ) {
  5976. const colorNode = this.colorNode || builder.context.color;
  5977. const toneMapping = this.toneMapping;
  5978. if ( toneMapping === NoToneMapping ) return colorNode;
  5979. let outputNode = null;
  5980. const toneMappingFn = builder.renderer.library.getToneMappingFunction( toneMapping );
  5981. if ( toneMappingFn !== null ) {
  5982. outputNode = vec4( toneMappingFn( colorNode.rgb, this.exposureNode ), colorNode.a );
  5983. } else {
  5984. console.error( 'ToneMappingNode: Unsupported Tone Mapping configuration.', toneMapping );
  5985. outputNode = colorNode;
  5986. }
  5987. return outputNode;
  5988. }
  5989. }
  5990. /**
  5991. * TSL function for creating a tone mapping node.
  5992. *
  5993. * @tsl
  5994. * @function
  5995. * @param {number} mapping - The tone mapping type.
  5996. * @param {Node<float> | number} exposure - The tone mapping exposure.
  5997. * @param {Node<vec3> | Color} color - The color node to process.
  5998. * @returns {ToneMappingNode<vec3>}
  5999. */
  6000. const toneMapping = ( mapping, exposure, color ) => nodeObject( new ToneMappingNode( mapping, nodeObject( exposure ), nodeObject( color ) ) );
  6001. /**
  6002. * TSL object that represents the global tone mapping exposure of the renderer.
  6003. *
  6004. * @tsl
  6005. * @type {RendererReferenceNode<vec3>}
  6006. */
  6007. const toneMappingExposure = /*@__PURE__*/ rendererReference( 'toneMappingExposure', 'float' );
  6008. addMethodChaining( 'toneMapping', ( color, mapping, exposure ) => toneMapping( mapping, exposure, color ) );
  6009. /**
  6010. * In earlier `three.js` versions it was only possible to define attribute data
  6011. * on geometry level. With `BufferAttributeNode`, it is also possible to do this
  6012. * on the node level.
  6013. * ```js
  6014. * const geometry = new THREE.PlaneGeometry();
  6015. * const positionAttribute = geometry.getAttribute( 'position' );
  6016. *
  6017. * const colors = [];
  6018. * for ( let i = 0; i < position.count; i ++ ) {
  6019. * colors.push( 1, 0, 0 );
  6020. * }
  6021. *
  6022. * material.colorNode = bufferAttribute( new THREE.Float32BufferAttribute( colors, 3 ) );
  6023. * ```
  6024. * This new approach is especially interesting when geometry data are generated via
  6025. * compute shaders. The below line converts a storage buffer into an attribute node.
  6026. * ```js
  6027. * material.positionNode = positionBuffer.toAttribute();
  6028. * ```
  6029. * @augments InputNode
  6030. */
  6031. class BufferAttributeNode extends InputNode {
  6032. static get type() {
  6033. return 'BufferAttributeNode';
  6034. }
  6035. /**
  6036. * Constructs a new buffer attribute node.
  6037. *
  6038. * @param {BufferAttribute|InterleavedBuffer|TypedArray} value - The attribute data.
  6039. * @param {?string} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  6040. * @param {number} [bufferStride=0] - The buffer stride.
  6041. * @param {number} [bufferOffset=0] - The buffer offset.
  6042. */
  6043. constructor( value, bufferType = null, bufferStride = 0, bufferOffset = 0 ) {
  6044. super( value, bufferType );
  6045. /**
  6046. * This flag can be used for type testing.
  6047. *
  6048. * @type {boolean}
  6049. * @readonly
  6050. * @default true
  6051. */
  6052. this.isBufferNode = true;
  6053. /**
  6054. * The buffer type (e.g. `'vec3'`).
  6055. *
  6056. * @type {?string}
  6057. * @default null
  6058. */
  6059. this.bufferType = bufferType;
  6060. /**
  6061. * The buffer stride.
  6062. *
  6063. * @type {number}
  6064. * @default 0
  6065. */
  6066. this.bufferStride = bufferStride;
  6067. /**
  6068. * The buffer offset.
  6069. *
  6070. * @type {number}
  6071. * @default 0
  6072. */
  6073. this.bufferOffset = bufferOffset;
  6074. /**
  6075. * The usage property. Set this to `THREE.DynamicDrawUsage` via `.setUsage()`,
  6076. * if you are planning to update the attribute data per frame.
  6077. *
  6078. * @type {number}
  6079. * @default StaticDrawUsage
  6080. */
  6081. this.usage = StaticDrawUsage;
  6082. /**
  6083. * Whether the attribute is instanced or not.
  6084. *
  6085. * @type {boolean}
  6086. * @default false
  6087. */
  6088. this.instanced = false;
  6089. /**
  6090. * A reference to the buffer attribute.
  6091. *
  6092. * @type {?BufferAttribute}
  6093. * @default null
  6094. */
  6095. this.attribute = null;
  6096. /**
  6097. * `BufferAttributeNode` sets this property to `true` by default.
  6098. *
  6099. * @type {boolean}
  6100. * @default true
  6101. */
  6102. this.global = true;
  6103. if ( value && value.isBufferAttribute === true ) {
  6104. this.attribute = value;
  6105. this.usage = value.usage;
  6106. this.instanced = value.isInstancedBufferAttribute;
  6107. }
  6108. }
  6109. /**
  6110. * This method is overwritten since the attribute data might be shared
  6111. * and thus the hash should be shared as well.
  6112. *
  6113. * @param {NodeBuilder} builder - The current node builder.
  6114. * @return {string} The hash.
  6115. */
  6116. getHash( builder ) {
  6117. if ( this.bufferStride === 0 && this.bufferOffset === 0 ) {
  6118. let bufferData = builder.globalCache.getData( this.value );
  6119. if ( bufferData === undefined ) {
  6120. bufferData = {
  6121. node: this
  6122. };
  6123. builder.globalCache.setData( this.value, bufferData );
  6124. }
  6125. return bufferData.node.uuid;
  6126. }
  6127. return this.uuid;
  6128. }
  6129. /**
  6130. * This method is overwritten since the node type is inferred from
  6131. * the buffer attribute.
  6132. *
  6133. * @param {NodeBuilder} builder - The current node builder.
  6134. * @return {string} The node type.
  6135. */
  6136. getNodeType( builder ) {
  6137. if ( this.bufferType === null ) {
  6138. this.bufferType = builder.getTypeFromAttribute( this.attribute );
  6139. }
  6140. return this.bufferType;
  6141. }
  6142. /**
  6143. * Depending on which value was passed to the node, `setup()` behaves
  6144. * differently. If no instance of `BufferAttribute` was passed, the method
  6145. * creates an internal attribute and configures it respectively.
  6146. *
  6147. * @param {NodeBuilder} builder - The current node builder.
  6148. */
  6149. setup( builder ) {
  6150. if ( this.attribute !== null ) return;
  6151. const type = this.getNodeType( builder );
  6152. const array = this.value;
  6153. const itemSize = builder.getTypeLength( type );
  6154. const stride = this.bufferStride || itemSize;
  6155. const offset = this.bufferOffset;
  6156. const buffer = array.isInterleavedBuffer === true ? array : new InterleavedBuffer( array, stride );
  6157. const bufferAttribute = new InterleavedBufferAttribute( buffer, itemSize, offset );
  6158. buffer.setUsage( this.usage );
  6159. this.attribute = bufferAttribute;
  6160. this.attribute.isInstancedBufferAttribute = this.instanced; // @TODO: Add a possible: InstancedInterleavedBufferAttribute
  6161. }
  6162. /**
  6163. * Generates the code snippet of the buffer attribute node.
  6164. *
  6165. * @param {NodeBuilder} builder - The current node builder.
  6166. * @return {string} The generated code snippet.
  6167. */
  6168. generate( builder ) {
  6169. const nodeType = this.getNodeType( builder );
  6170. const nodeAttribute = builder.getBufferAttributeFromNode( this, nodeType );
  6171. const propertyName = builder.getPropertyName( nodeAttribute );
  6172. let output = null;
  6173. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  6174. this.name = propertyName;
  6175. output = propertyName;
  6176. } else {
  6177. const nodeVarying = varying( this );
  6178. output = nodeVarying.build( builder, nodeType );
  6179. }
  6180. return output;
  6181. }
  6182. /**
  6183. * Overwrites the default implementation to return a fixed value `'bufferAttribute'`.
  6184. *
  6185. * @param {NodeBuilder} builder - The current node builder.
  6186. * @return {string} The input type.
  6187. */
  6188. getInputType( /*builder*/ ) {
  6189. return 'bufferAttribute';
  6190. }
  6191. /**
  6192. * Sets the `usage` property to the given value.
  6193. *
  6194. * @param {number} value - The usage to set.
  6195. * @return {BufferAttributeNode} A reference to this node.
  6196. */
  6197. setUsage( value ) {
  6198. this.usage = value;
  6199. if ( this.attribute && this.attribute.isBufferAttribute === true ) {
  6200. this.attribute.usage = value;
  6201. }
  6202. return this;
  6203. }
  6204. /**
  6205. * Sets the `instanced` property to the given value.
  6206. *
  6207. * @param {boolean} value - The value to set.
  6208. * @return {BufferAttributeNode} A reference to this node.
  6209. */
  6210. setInstanced( value ) {
  6211. this.instanced = value;
  6212. return this;
  6213. }
  6214. }
  6215. /**
  6216. * TSL function for creating a buffer attribute node.
  6217. *
  6218. * @tsl
  6219. * @function
  6220. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6221. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6222. * @param {number} [stride=0] - The buffer stride.
  6223. * @param {number} [offset=0] - The buffer offset.
  6224. * @returns {BufferAttributeNode}
  6225. */
  6226. const bufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => nodeObject( new BufferAttributeNode( array, type, stride, offset ) );
  6227. /**
  6228. * TSL function for creating a buffer attribute node but with dynamic draw usage.
  6229. * Use this function if attribute data are updated per frame.
  6230. *
  6231. * @tsl
  6232. * @function
  6233. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6234. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6235. * @param {number} [stride=0] - The buffer stride.
  6236. * @param {number} [offset=0] - The buffer offset.
  6237. * @returns {BufferAttributeNode}
  6238. */
  6239. const dynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setUsage( DynamicDrawUsage );
  6240. /**
  6241. * TSL function for creating a buffer attribute node but with enabled instancing
  6242. *
  6243. * @tsl
  6244. * @function
  6245. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6246. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6247. * @param {number} [stride=0] - The buffer stride.
  6248. * @param {number} [offset=0] - The buffer offset.
  6249. * @returns {BufferAttributeNode}
  6250. */
  6251. const instancedBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => bufferAttribute( array, type, stride, offset ).setInstanced( true );
  6252. /**
  6253. * TSL function for creating a buffer attribute node but with dynamic draw usage and enabled instancing
  6254. *
  6255. * @tsl
  6256. * @function
  6257. * @param {BufferAttribute|InterleavedBuffer|TypedArray} array - The attribute data.
  6258. * @param {?string} [type=null] - The buffer type (e.g. `'vec3'`).
  6259. * @param {number} [stride=0] - The buffer stride.
  6260. * @param {number} [offset=0] - The buffer offset.
  6261. * @returns {BufferAttributeNode}
  6262. */
  6263. const instancedDynamicBufferAttribute = ( array, type = null, stride = 0, offset = 0 ) => dynamicBufferAttribute( array, type, stride, offset ).setInstanced( true );
  6264. addMethodChaining( 'toAttribute', ( bufferNode ) => bufferAttribute( bufferNode.value ) );
  6265. /**
  6266. * TODO
  6267. *
  6268. * @augments Node
  6269. */
  6270. class ComputeNode extends Node {
  6271. static get type() {
  6272. return 'ComputeNode';
  6273. }
  6274. /**
  6275. * Constructs a new compute node.
  6276. *
  6277. * @param {Node} computeNode - TODO
  6278. * @param {number} count - TODO.
  6279. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6280. */
  6281. constructor( computeNode, count, workgroupSize = [ 64 ] ) {
  6282. super( 'void' );
  6283. /**
  6284. * This flag can be used for type testing.
  6285. *
  6286. * @type {boolean}
  6287. * @readonly
  6288. * @default true
  6289. */
  6290. this.isComputeNode = true;
  6291. /**
  6292. * TODO
  6293. *
  6294. * @type {Node}
  6295. */
  6296. this.computeNode = computeNode;
  6297. /**
  6298. * TODO
  6299. *
  6300. * @type {number}
  6301. */
  6302. this.count = count;
  6303. /**
  6304. * TODO
  6305. *
  6306. * @type {Array<number>}
  6307. * @default [64]
  6308. */
  6309. this.workgroupSize = workgroupSize;
  6310. /**
  6311. * TODO
  6312. *
  6313. * @type {number}
  6314. */
  6315. this.dispatchCount = 0;
  6316. /**
  6317. * TODO
  6318. *
  6319. * @type {number}
  6320. */
  6321. this.version = 1;
  6322. /**
  6323. * The name or label of the uniform.
  6324. *
  6325. * @type {string}
  6326. * @default ''
  6327. */
  6328. this.name = '';
  6329. /**
  6330. * The `updateBeforeType` is set to `NodeUpdateType.OBJECT` since {@link ComputeNode#updateBefore}
  6331. * is executed once per object by default.
  6332. *
  6333. * @type {string}
  6334. * @default 'object'
  6335. */
  6336. this.updateBeforeType = NodeUpdateType.OBJECT;
  6337. /**
  6338. * TODO
  6339. *
  6340. * @type {?Function}
  6341. */
  6342. this.onInitFunction = null;
  6343. this.updateDispatchCount();
  6344. }
  6345. /**
  6346. * Executes the `dispose` event for this node.
  6347. */
  6348. dispose() {
  6349. this.dispatchEvent( { type: 'dispose' } );
  6350. }
  6351. /**
  6352. * Sets the {@link ComputeNode#name} property.
  6353. *
  6354. * @param {string} name - The name of the uniform.
  6355. * @return {ComputeNode} A reference to this node.
  6356. */
  6357. label( name ) {
  6358. this.name = name;
  6359. return this;
  6360. }
  6361. /**
  6362. * TODO
  6363. */
  6364. updateDispatchCount() {
  6365. const { count, workgroupSize } = this;
  6366. let size = workgroupSize[ 0 ];
  6367. for ( let i = 1; i < workgroupSize.length; i ++ )
  6368. size *= workgroupSize[ i ];
  6369. this.dispatchCount = Math.ceil( count / size );
  6370. }
  6371. /**
  6372. * TODO
  6373. *
  6374. * @param {Function} callback - TODO.
  6375. * @return {ComputeNode} A reference to this node.
  6376. */
  6377. onInit( callback ) {
  6378. this.onInitFunction = callback;
  6379. return this;
  6380. }
  6381. /**
  6382. * The method execute the compute for this node.
  6383. *
  6384. * @param {NodeFrame} frame - A reference to the current node frame.
  6385. */
  6386. updateBefore( { renderer } ) {
  6387. renderer.compute( this );
  6388. }
  6389. setup( builder ) {
  6390. const result = this.computeNode.build( builder );
  6391. if ( result ) {
  6392. const properties = builder.getNodeProperties( this );
  6393. properties.outputComputeNode = result.outputNode;
  6394. result.outputNode = null;
  6395. }
  6396. return result;
  6397. }
  6398. generate( builder, output ) {
  6399. const { shaderStage } = builder;
  6400. if ( shaderStage === 'compute' ) {
  6401. const snippet = this.computeNode.build( builder, 'void' );
  6402. if ( snippet !== '' ) {
  6403. builder.addLineFlowCode( snippet, this );
  6404. }
  6405. } else {
  6406. const properties = builder.getNodeProperties( this );
  6407. const outputComputeNode = properties.outputComputeNode;
  6408. if ( outputComputeNode ) {
  6409. return outputComputeNode.build( builder, output );
  6410. }
  6411. }
  6412. }
  6413. }
  6414. /**
  6415. * TSL function for creating a compute node.
  6416. *
  6417. * @tsl
  6418. * @function
  6419. * @param {Node} node - TODO
  6420. * @param {number} count - TODO.
  6421. * @param {Array<number>} [workgroupSize=[64]] - TODO.
  6422. * @returns {AtomicFunctionNode}
  6423. */
  6424. const compute = ( node, count, workgroupSize ) => nodeObject( new ComputeNode( nodeObject( node ), count, workgroupSize ) );
  6425. addMethodChaining( 'compute', compute );
  6426. /**
  6427. * This node can be used as a cache management component for another node.
  6428. * Caching is in general used by default in {@link NodeBuilder} but this node
  6429. * allows the usage of a shared parent cache during the build process.
  6430. *
  6431. * @augments Node
  6432. */
  6433. class CacheNode extends Node {
  6434. static get type() {
  6435. return 'CacheNode';
  6436. }
  6437. /**
  6438. * Constructs a new cache node.
  6439. *
  6440. * @param {Node} node - The node that should be cached.
  6441. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  6442. */
  6443. constructor( node, parent = true ) {
  6444. super();
  6445. /**
  6446. * The node that should be cached.
  6447. *
  6448. * @type {Node}
  6449. */
  6450. this.node = node;
  6451. /**
  6452. * Whether this node refers to a shared parent cache or not.
  6453. *
  6454. * @type {boolean}
  6455. * @default true
  6456. */
  6457. this.parent = parent;
  6458. /**
  6459. * This flag can be used for type testing.
  6460. *
  6461. * @type {boolean}
  6462. * @readonly
  6463. * @default true
  6464. */
  6465. this.isCacheNode = true;
  6466. }
  6467. getNodeType( builder ) {
  6468. const previousCache = builder.getCache();
  6469. const cache = builder.getCacheFromNode( this, this.parent );
  6470. builder.setCache( cache );
  6471. const nodeType = this.node.getNodeType( builder );
  6472. builder.setCache( previousCache );
  6473. return nodeType;
  6474. }
  6475. build( builder, ...params ) {
  6476. const previousCache = builder.getCache();
  6477. const cache = builder.getCacheFromNode( this, this.parent );
  6478. builder.setCache( cache );
  6479. const data = this.node.build( builder, ...params );
  6480. builder.setCache( previousCache );
  6481. return data;
  6482. }
  6483. }
  6484. /**
  6485. * TSL function for creating a cache node.
  6486. *
  6487. * @tsl
  6488. * @function
  6489. * @param {Node} node - The node that should be cached.
  6490. * @param {boolean} [parent] - Whether this node refers to a shared parent cache or not.
  6491. * @returns {CacheNode}
  6492. */
  6493. const cache = ( node, parent ) => nodeObject( new CacheNode( nodeObject( node ), parent ) );
  6494. /**
  6495. * Assigns a namespace to the given node by updating its context.
  6496. *
  6497. * Important for TSL functions that use `.once( namespace )` to ensure that the namespace will run twice,
  6498. * once when the node is build in the specific namespace and once when the node is built in the others namespace.
  6499. *
  6500. * This is useful for nodes like `positionWorld` that need to be re-updated if used in `material.positionNode` and outside of it in the same material.
  6501. *
  6502. * @param {Object} node - The node to which the namespace will be assigned.
  6503. * @param {string} namespace - The namespace to be assigned to the node.
  6504. * @returns {Object} The updated node with the new namespace in its context.
  6505. */
  6506. const namespace = ( node, namespace ) => node.context( { namespace } );
  6507. addMethodChaining( 'cache', cache );
  6508. /**
  6509. * The class generates the code of a given node but returns another node in the output.
  6510. * This can be used to call a method or node that does not return a value, i.e.
  6511. * type `void` on an input where returning a value is required. Example:
  6512. *
  6513. * ```js
  6514. * material.colorNode = myColor.bypass( runVoidFn() )
  6515. *```
  6516. *
  6517. * @augments Node
  6518. */
  6519. class BypassNode extends Node {
  6520. static get type() {
  6521. return 'BypassNode';
  6522. }
  6523. /**
  6524. * Constructs a new bypass node.
  6525. *
  6526. * @param {Node} outputNode - The output node.
  6527. * @param {Node} callNode - The call node.
  6528. */
  6529. constructor( outputNode, callNode ) {
  6530. super();
  6531. /**
  6532. * This flag can be used for type testing.
  6533. *
  6534. * @type {boolean}
  6535. * @readonly
  6536. * @default true
  6537. */
  6538. this.isBypassNode = true;
  6539. /**
  6540. * The output node.
  6541. *
  6542. * @type {Node}
  6543. */
  6544. this.outputNode = outputNode;
  6545. /**
  6546. * The call node.
  6547. *
  6548. * @type {Node}
  6549. */
  6550. this.callNode = callNode;
  6551. }
  6552. getNodeType( builder ) {
  6553. return this.outputNode.getNodeType( builder );
  6554. }
  6555. generate( builder ) {
  6556. const snippet = this.callNode.build( builder, 'void' );
  6557. if ( snippet !== '' ) {
  6558. builder.addLineFlowCode( snippet, this );
  6559. }
  6560. return this.outputNode.build( builder );
  6561. }
  6562. }
  6563. /**
  6564. * TSL function for creating a bypass node.
  6565. *
  6566. * @tsl
  6567. * @function
  6568. * @param {Node} outputNode - The output node.
  6569. * @param {Node} callNode - The call node.
  6570. * @returns {BypassNode}
  6571. */
  6572. const bypass = /*@__PURE__*/ nodeProxy( BypassNode ).setParameterLength( 2 );
  6573. addMethodChaining( 'bypass', bypass );
  6574. /**
  6575. * This node allows to remap a node value from one range into another. E.g a value of
  6576. * `0.4` in the range `[ 0.3, 0.5 ]` should be remapped into the normalized range `[ 0, 1 ]`.
  6577. * `RemapNode` takes care of that and converts the original value of `0.4` to `0.5`.
  6578. *
  6579. * @augments Node
  6580. */
  6581. class RemapNode extends Node {
  6582. static get type() {
  6583. return 'RemapNode';
  6584. }
  6585. /**
  6586. * Constructs a new remap node.
  6587. *
  6588. * @param {Node} node - The node that should be remapped.
  6589. * @param {Node} inLowNode - The source or current lower bound of the range.
  6590. * @param {Node} inHighNode - The source or current upper bound of the range.
  6591. * @param {Node} [outLowNode=float(0)] - The target lower bound of the range.
  6592. * @param {Node} [outHighNode=float(1)] - The target upper bound of the range.
  6593. */
  6594. constructor( node, inLowNode, inHighNode, outLowNode = float( 0 ), outHighNode = float( 1 ) ) {
  6595. super();
  6596. /**
  6597. * The node that should be remapped.
  6598. *
  6599. * @type {Node}
  6600. */
  6601. this.node = node;
  6602. /**
  6603. * The source or current lower bound of the range.
  6604. *
  6605. * @type {Node}
  6606. */
  6607. this.inLowNode = inLowNode;
  6608. /**
  6609. * The source or current upper bound of the range.
  6610. *
  6611. * @type {Node}
  6612. */
  6613. this.inHighNode = inHighNode;
  6614. /**
  6615. * The target lower bound of the range.
  6616. *
  6617. * @type {Node}
  6618. * @default float(0)
  6619. */
  6620. this.outLowNode = outLowNode;
  6621. /**
  6622. * The target upper bound of the range.
  6623. *
  6624. * @type {Node}
  6625. * @default float(1)
  6626. */
  6627. this.outHighNode = outHighNode;
  6628. /**
  6629. * Whether the node value should be clamped before
  6630. * remapping it to the target range.
  6631. *
  6632. * @type {boolean}
  6633. * @default true
  6634. */
  6635. this.doClamp = true;
  6636. }
  6637. setup() {
  6638. const { node, inLowNode, inHighNode, outLowNode, outHighNode, doClamp } = this;
  6639. let t = node.sub( inLowNode ).div( inHighNode.sub( inLowNode ) );
  6640. if ( doClamp === true ) t = t.clamp();
  6641. return t.mul( outHighNode.sub( outLowNode ) ).add( outLowNode );
  6642. }
  6643. }
  6644. /**
  6645. * TSL function for creating a remap node.
  6646. *
  6647. * @tsl
  6648. * @function
  6649. * @param {Node} node - The node that should be remapped.
  6650. * @param {Node} inLowNode - The source or current lower bound of the range.
  6651. * @param {Node} inHighNode - The source or current upper bound of the range.
  6652. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  6653. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  6654. * @returns {RemapNode}
  6655. */
  6656. const remap = /*@__PURE__*/ nodeProxy( RemapNode, null, null, { doClamp: false } ).setParameterLength( 3, 5 );
  6657. /**
  6658. * TSL function for creating a remap node, but with enabled clamping.
  6659. *
  6660. * @tsl
  6661. * @function
  6662. * @param {Node} node - The node that should be remapped.
  6663. * @param {Node} inLowNode - The source or current lower bound of the range.
  6664. * @param {Node} inHighNode - The source or current upper bound of the range.
  6665. * @param {?Node} [outLowNode=float(0)] - The target lower bound of the range.
  6666. * @param {?Node} [outHighNode=float(1)] - The target upper bound of the range.
  6667. * @returns {RemapNode}
  6668. */
  6669. const remapClamp = /*@__PURE__*/ nodeProxy( RemapNode ).setParameterLength( 3, 5 );
  6670. addMethodChaining( 'remap', remap );
  6671. addMethodChaining( 'remapClamp', remapClamp );
  6672. /**
  6673. * This class can be used to implement basic expressions in shader code.
  6674. * Basic examples for that are `return`, `continue` or `discard` statements.
  6675. *
  6676. * @augments Node
  6677. */
  6678. class ExpressionNode extends Node {
  6679. static get type() {
  6680. return 'ExpressionNode';
  6681. }
  6682. /**
  6683. * Constructs a new expression node.
  6684. *
  6685. * @param {string} [snippet=''] - The native code snippet.
  6686. * @param {string} [nodeType='void'] - The node type.
  6687. */
  6688. constructor( snippet = '', nodeType = 'void' ) {
  6689. super( nodeType );
  6690. /**
  6691. * The native code snippet.
  6692. *
  6693. * @type {string}
  6694. * @default ''
  6695. */
  6696. this.snippet = snippet;
  6697. }
  6698. generate( builder, output ) {
  6699. const type = this.getNodeType( builder );
  6700. const snippet = this.snippet;
  6701. if ( type === 'void' ) {
  6702. builder.addLineFlowCode( snippet, this );
  6703. } else {
  6704. return builder.format( snippet, type, output );
  6705. }
  6706. }
  6707. }
  6708. /**
  6709. * TSL function for creating an expression node.
  6710. *
  6711. * @tsl
  6712. * @function
  6713. * @param {string} [snippet] - The native code snippet.
  6714. * @param {?string} [nodeType='void'] - The node type.
  6715. * @returns {ExpressionNode}
  6716. */
  6717. const expression = /*@__PURE__*/ nodeProxy( ExpressionNode ).setParameterLength( 1, 2 );
  6718. /**
  6719. * Represents a `discard` shader operation in TSL.
  6720. *
  6721. * @tsl
  6722. * @function
  6723. * @param {?ConditionalNode} conditional - An optional conditional node. It allows to decide whether the discard should be executed or not.
  6724. * @return {Node} The `discard` expression.
  6725. */
  6726. const Discard = ( conditional ) => ( conditional ? select( conditional, expression( 'discard' ) ) : expression( 'discard' ) ).toStack();
  6727. /**
  6728. * Represents a `return` shader operation in TSL.
  6729. *
  6730. * @tsl
  6731. * @function
  6732. * @return {ExpressionNode} The `return` expression.
  6733. */
  6734. const Return = () => expression( 'return' ).toStack();
  6735. addMethodChaining( 'discard', Discard );
  6736. /**
  6737. * Normally, tone mapping and color conversion happens automatically
  6738. * before outputting pixel too the default (screen) framebuffer. In certain
  6739. * post processing setups this happens to late because certain effects
  6740. * require e.g. sRGB input. For such scenarios, `RenderOutputNode` can be used
  6741. * to apply tone mapping and color space conversion at an arbitrary point
  6742. * in the effect chain.
  6743. *
  6744. * When applying tone mapping and color space conversion manually with this node,
  6745. * you have to set {@link PostProcessing#outputColorTransform} to `false`.
  6746. *
  6747. * ```js
  6748. * const postProcessing = new PostProcessing( renderer );
  6749. * postProcessing.outputColorTransform = false;
  6750. *
  6751. * const scenePass = pass( scene, camera );
  6752. * const outputPass = renderOutput( scenePass );
  6753. *
  6754. * postProcessing.outputNode = outputPass;
  6755. * ```
  6756. *
  6757. * @augments TempNode
  6758. */
  6759. class RenderOutputNode extends TempNode {
  6760. static get type() {
  6761. return 'RenderOutputNode';
  6762. }
  6763. /**
  6764. * Constructs a new render output node.
  6765. *
  6766. * @param {Node} colorNode - The color node to process.
  6767. * @param {?number} toneMapping - The tone mapping type.
  6768. * @param {?string} outputColorSpace - The output color space.
  6769. */
  6770. constructor( colorNode, toneMapping, outputColorSpace ) {
  6771. super( 'vec4' );
  6772. /**
  6773. * The color node to process.
  6774. *
  6775. * @type {Node}
  6776. */
  6777. this.colorNode = colorNode;
  6778. /**
  6779. * The tone mapping type.
  6780. *
  6781. * @type {?number}
  6782. */
  6783. this.toneMapping = toneMapping;
  6784. /**
  6785. * The output color space.
  6786. *
  6787. * @type {?string}
  6788. */
  6789. this.outputColorSpace = outputColorSpace;
  6790. /**
  6791. * This flag can be used for type testing.
  6792. *
  6793. * @type {boolean}
  6794. * @readonly
  6795. * @default true
  6796. */
  6797. this.isRenderOutputNode = true;
  6798. }
  6799. setup( { context } ) {
  6800. let outputNode = this.colorNode || context.color;
  6801. // tone mapping
  6802. const toneMapping = ( this.toneMapping !== null ? this.toneMapping : context.toneMapping ) || NoToneMapping;
  6803. const outputColorSpace = ( this.outputColorSpace !== null ? this.outputColorSpace : context.outputColorSpace ) || NoColorSpace;
  6804. if ( toneMapping !== NoToneMapping ) {
  6805. outputNode = outputNode.toneMapping( toneMapping );
  6806. }
  6807. // working to output color space
  6808. if ( outputColorSpace !== NoColorSpace && outputColorSpace !== ColorManagement.workingColorSpace ) {
  6809. outputNode = outputNode.workingToColorSpace( outputColorSpace );
  6810. }
  6811. return outputNode;
  6812. }
  6813. }
  6814. /**
  6815. * TSL function for creating a posterize node.
  6816. *
  6817. * @tsl
  6818. * @function
  6819. * @param {Node} color - The color node to process.
  6820. * @param {?number} [toneMapping=null] - The tone mapping type.
  6821. * @param {?string} [outputColorSpace=null] - The output color space.
  6822. * @returns {RenderOutputNode}
  6823. */
  6824. const renderOutput = ( color, toneMapping = null, outputColorSpace = null ) => nodeObject( new RenderOutputNode( nodeObject( color ), toneMapping, outputColorSpace ) );
  6825. addMethodChaining( 'renderOutput', renderOutput );
  6826. class DebugNode extends TempNode {
  6827. static get type() {
  6828. return 'DebugNode';
  6829. }
  6830. constructor( node, callback = null ) {
  6831. super();
  6832. this.node = node;
  6833. this.callback = callback;
  6834. }
  6835. getNodeType( builder ) {
  6836. return this.node.getNodeType( builder );
  6837. }
  6838. setup( builder ) {
  6839. return this.node.build( builder );
  6840. }
  6841. analyze( builder ) {
  6842. return this.node.build( builder );
  6843. }
  6844. generate( builder ) {
  6845. const callback = this.callback;
  6846. const snippet = this.node.build( builder );
  6847. const title = '--- TSL debug - ' + builder.shaderStage + ' shader ---';
  6848. const border = '-'.repeat( title.length );
  6849. let code = '';
  6850. code += '// #' + title + '#\n';
  6851. code += builder.flow.code.replace( /^\t/mg, '' ) + '\n';
  6852. code += '/* ... */ ' + snippet + ' /* ... */\n';
  6853. code += '// #' + border + '#\n';
  6854. if ( callback !== null ) {
  6855. callback( builder, code );
  6856. } else {
  6857. console.log( code );
  6858. }
  6859. return snippet;
  6860. }
  6861. }
  6862. /**
  6863. * TSL function for creating a debug node.
  6864. *
  6865. * @tsl
  6866. * @function
  6867. * @param {Node} node - The node to debug.
  6868. * @param {?Function} [callback=null] - Optional callback function to handle the debug output.
  6869. * @returns {DebugNode}
  6870. */
  6871. const debug = ( node, callback = null ) => nodeObject( new DebugNode( nodeObject( node ), callback ) );
  6872. addMethodChaining( 'debug', debug );
  6873. // Non-PURE exports list, side-effects are required here.
  6874. // TSL Base Syntax
  6875. function addNodeElement( name/*, nodeElement*/ ) {
  6876. console.warn( 'THREE.TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add', name );
  6877. }
  6878. /**
  6879. * Base class for representing shader attributes as nodes.
  6880. *
  6881. * @augments Node
  6882. */
  6883. class AttributeNode extends Node {
  6884. static get type() {
  6885. return 'AttributeNode';
  6886. }
  6887. /**
  6888. * Constructs a new attribute node.
  6889. *
  6890. * @param {string} attributeName - The name of the attribute.
  6891. * @param {?string} nodeType - The node type.
  6892. */
  6893. constructor( attributeName, nodeType = null ) {
  6894. super( nodeType );
  6895. /**
  6896. * `AttributeNode` sets this property to `true` by default.
  6897. *
  6898. * @type {boolean}
  6899. * @default true
  6900. */
  6901. this.global = true;
  6902. this._attributeName = attributeName;
  6903. }
  6904. getHash( builder ) {
  6905. return this.getAttributeName( builder );
  6906. }
  6907. getNodeType( builder ) {
  6908. let nodeType = this.nodeType;
  6909. if ( nodeType === null ) {
  6910. const attributeName = this.getAttributeName( builder );
  6911. if ( builder.hasGeometryAttribute( attributeName ) ) {
  6912. const attribute = builder.geometry.getAttribute( attributeName );
  6913. nodeType = builder.getTypeFromAttribute( attribute );
  6914. } else {
  6915. nodeType = 'float';
  6916. }
  6917. }
  6918. return nodeType;
  6919. }
  6920. /**
  6921. * Sets the attribute name to the given value. The method can be
  6922. * overwritten in derived classes if the final name must be computed
  6923. * analytically.
  6924. *
  6925. * @param {string} attributeName - The name of the attribute.
  6926. * @return {AttributeNode} A reference to this node.
  6927. */
  6928. setAttributeName( attributeName ) {
  6929. this._attributeName = attributeName;
  6930. return this;
  6931. }
  6932. /**
  6933. * Returns the attribute name of this node. The method can be
  6934. * overwritten in derived classes if the final name must be computed
  6935. * analytically.
  6936. *
  6937. * @param {NodeBuilder} builder - The current node builder.
  6938. * @return {string} The attribute name.
  6939. */
  6940. getAttributeName( /*builder*/ ) {
  6941. return this._attributeName;
  6942. }
  6943. generate( builder ) {
  6944. const attributeName = this.getAttributeName( builder );
  6945. const nodeType = this.getNodeType( builder );
  6946. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  6947. if ( geometryAttribute === true ) {
  6948. const attribute = builder.geometry.getAttribute( attributeName );
  6949. const attributeType = builder.getTypeFromAttribute( attribute );
  6950. const nodeAttribute = builder.getAttribute( attributeName, attributeType );
  6951. if ( builder.shaderStage === 'vertex' ) {
  6952. return builder.format( nodeAttribute.name, attributeType, nodeType );
  6953. } else {
  6954. const nodeVarying = varying( this );
  6955. return nodeVarying.build( builder, nodeType );
  6956. }
  6957. } else {
  6958. console.warn( `AttributeNode: Vertex attribute "${ attributeName }" not found on geometry.` );
  6959. return builder.generateConst( nodeType );
  6960. }
  6961. }
  6962. serialize( data ) {
  6963. super.serialize( data );
  6964. data.global = this.global;
  6965. data._attributeName = this._attributeName;
  6966. }
  6967. deserialize( data ) {
  6968. super.deserialize( data );
  6969. this.global = data.global;
  6970. this._attributeName = data._attributeName;
  6971. }
  6972. }
  6973. /**
  6974. * TSL function for creating an attribute node.
  6975. *
  6976. * @tsl
  6977. * @function
  6978. * @param {string} name - The name of the attribute.
  6979. * @param {?string} [nodeType=null] - The node type.
  6980. * @returns {AttributeNode}
  6981. */
  6982. const attribute = ( name, nodeType = null ) => nodeObject( new AttributeNode( name, nodeType ) );
  6983. /**
  6984. * TSL function for creating an uv attribute node with the given index.
  6985. *
  6986. * @tsl
  6987. * @function
  6988. * @param {number} [index=0] - The uv index.
  6989. * @return {AttributeNode<vec2>} The uv attribute node.
  6990. */
  6991. const uv = ( index = 0 ) => attribute( 'uv' + ( index > 0 ? index : '' ), 'vec2' );
  6992. /**
  6993. * A node that represents the dimensions of a texture. The texture size is
  6994. * retrieved in the shader via built-in shader functions like `textureDimensions()`
  6995. * or `textureSize()`.
  6996. *
  6997. * @augments Node
  6998. */
  6999. class TextureSizeNode extends Node {
  7000. static get type() {
  7001. return 'TextureSizeNode';
  7002. }
  7003. /**
  7004. * Constructs a new texture size node.
  7005. *
  7006. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7007. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7008. */
  7009. constructor( textureNode, levelNode = null ) {
  7010. super( 'uvec2' );
  7011. /**
  7012. * This flag can be used for type testing.
  7013. *
  7014. * @type {boolean}
  7015. * @readonly
  7016. * @default true
  7017. */
  7018. this.isTextureSizeNode = true;
  7019. /**
  7020. * A texture node which size should be retrieved.
  7021. *
  7022. * @type {TextureNode}
  7023. */
  7024. this.textureNode = textureNode;
  7025. /**
  7026. * A level node which defines the requested mip.
  7027. *
  7028. * @type {Node<int>}
  7029. * @default null
  7030. */
  7031. this.levelNode = levelNode;
  7032. }
  7033. generate( builder, output ) {
  7034. const textureProperty = this.textureNode.build( builder, 'property' );
  7035. const level = this.levelNode === null ? '0' : this.levelNode.build( builder, 'int' );
  7036. return builder.format( `${ builder.getMethod( 'textureDimensions' ) }( ${ textureProperty }, ${ level } )`, this.getNodeType( builder ), output );
  7037. }
  7038. }
  7039. /**
  7040. * TSL function for creating a texture size node.
  7041. *
  7042. * @tsl
  7043. * @function
  7044. * @param {TextureNode} textureNode - A texture node which size should be retrieved.
  7045. * @param {?Node<int>} [levelNode=null] - A level node which defines the requested mip.
  7046. * @returns {TextureSizeNode}
  7047. */
  7048. const textureSize = /*@__PURE__*/ nodeProxy( TextureSizeNode ).setParameterLength( 1, 2 );
  7049. /**
  7050. * A special type of uniform node that computes the
  7051. * maximum mipmap level for a given texture node.
  7052. *
  7053. * ```js
  7054. * const level = maxMipLevel( textureNode );
  7055. * ```
  7056. *
  7057. * @augments UniformNode
  7058. */
  7059. class MaxMipLevelNode extends UniformNode {
  7060. static get type() {
  7061. return 'MaxMipLevelNode';
  7062. }
  7063. /**
  7064. * Constructs a new max mip level node.
  7065. *
  7066. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7067. */
  7068. constructor( textureNode ) {
  7069. super( 0 );
  7070. /**
  7071. * The texture node to compute the max mip level for.
  7072. *
  7073. * @private
  7074. * @type {TextureNode}
  7075. */
  7076. this._textureNode = textureNode;
  7077. /**
  7078. * The `updateType` is set to `NodeUpdateType.FRAME` since the node updates
  7079. * the texture once per frame in its {@link MaxMipLevelNode#update} method.
  7080. *
  7081. * @type {string}
  7082. * @default 'frame'
  7083. */
  7084. this.updateType = NodeUpdateType.FRAME;
  7085. }
  7086. /**
  7087. * The texture node to compute the max mip level for.
  7088. *
  7089. * @readonly
  7090. * @type {TextureNode}
  7091. */
  7092. get textureNode() {
  7093. return this._textureNode;
  7094. }
  7095. /**
  7096. * The texture.
  7097. *
  7098. * @readonly
  7099. * @type {Texture}
  7100. */
  7101. get texture() {
  7102. return this._textureNode.value;
  7103. }
  7104. update() {
  7105. const texture = this.texture;
  7106. const images = texture.images;
  7107. const image = ( images && images.length > 0 ) ? ( ( images[ 0 ] && images[ 0 ].image ) || images[ 0 ] ) : texture.image;
  7108. if ( image && image.width !== undefined ) {
  7109. const { width, height } = image;
  7110. this.value = Math.log2( Math.max( width, height ) );
  7111. }
  7112. }
  7113. }
  7114. /**
  7115. * TSL function for creating a max mip level node.
  7116. *
  7117. * @tsl
  7118. * @function
  7119. * @param {TextureNode} textureNode - The texture node to compute the max mip level for.
  7120. * @returns {MaxMipLevelNode}
  7121. */
  7122. const maxMipLevel = /*@__PURE__*/ nodeProxy( MaxMipLevelNode ).setParameterLength( 1 );
  7123. const EmptyTexture$1 = /*@__PURE__*/ new Texture();
  7124. /**
  7125. * This type of uniform node represents a 2D texture.
  7126. *
  7127. * @augments UniformNode
  7128. */
  7129. class TextureNode extends UniformNode {
  7130. static get type() {
  7131. return 'TextureNode';
  7132. }
  7133. /**
  7134. * Constructs a new texture node.
  7135. *
  7136. * @param {Texture} [value=EmptyTexture] - The texture.
  7137. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7138. * @param {?Node<int>} [levelNode=null] - The level node.
  7139. * @param {?Node<float>} [biasNode=null] - The bias node.
  7140. */
  7141. constructor( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) {
  7142. super( value );
  7143. /**
  7144. * This flag can be used for type testing.
  7145. *
  7146. * @type {boolean}
  7147. * @readonly
  7148. * @default true
  7149. */
  7150. this.isTextureNode = true;
  7151. /**
  7152. * Represents the texture coordinates.
  7153. *
  7154. * @type {?Node<vec2|vec3>}
  7155. * @default null
  7156. */
  7157. this.uvNode = uvNode;
  7158. /**
  7159. * Represents the mip level that should be selected.
  7160. *
  7161. * @type {?Node<int>}
  7162. * @default null
  7163. */
  7164. this.levelNode = levelNode;
  7165. /**
  7166. * Represents the bias to be applied during level-of-detail computation.
  7167. *
  7168. * @type {?Node<float>}
  7169. * @default null
  7170. */
  7171. this.biasNode = biasNode;
  7172. /**
  7173. * Represents a reference value a texture sample is compared to.
  7174. *
  7175. * @type {?Node<float>}
  7176. * @default null
  7177. */
  7178. this.compareNode = null;
  7179. /**
  7180. * When using texture arrays, the depth node defines the layer to select.
  7181. *
  7182. * @type {?Node<int>}
  7183. * @default null
  7184. */
  7185. this.depthNode = null;
  7186. /**
  7187. * When defined, a texture is sampled using explicit gradients.
  7188. *
  7189. * @type {?Array<Node<vec2>>}
  7190. * @default null
  7191. */
  7192. this.gradNode = null;
  7193. /**
  7194. * Whether texture values should be sampled or fetched.
  7195. *
  7196. * @type {boolean}
  7197. * @default true
  7198. */
  7199. this.sampler = true;
  7200. /**
  7201. * Whether the uv transformation matrix should be
  7202. * automatically updated or not. Use `setUpdateMatrix()`
  7203. * if you want to change the value of the property.
  7204. *
  7205. * @type {boolean}
  7206. * @default false
  7207. */
  7208. this.updateMatrix = false;
  7209. /**
  7210. * By default the `update()` method is not executed. `setUpdateMatrix()`
  7211. * sets the value to `frame` when the uv transformation matrix should
  7212. * automatically be updated.
  7213. *
  7214. * @type {string}
  7215. * @default 'none'
  7216. */
  7217. this.updateType = NodeUpdateType.NONE;
  7218. /**
  7219. * The reference node.
  7220. *
  7221. * @type {?Node}
  7222. * @default null
  7223. */
  7224. this.referenceNode = null;
  7225. /**
  7226. * The texture value is stored in a private property.
  7227. *
  7228. * @private
  7229. * @type {Texture}
  7230. */
  7231. this._value = value;
  7232. /**
  7233. * The uniform node that represents the uv transformation matrix.
  7234. *
  7235. * @private
  7236. * @type {?UniformNode<mat3>}
  7237. */
  7238. this._matrixUniform = null;
  7239. this.setUpdateMatrix( uvNode === null );
  7240. }
  7241. set value( value ) {
  7242. if ( this.referenceNode ) {
  7243. this.referenceNode.value = value;
  7244. } else {
  7245. this._value = value;
  7246. }
  7247. }
  7248. /**
  7249. * The texture value.
  7250. *
  7251. * @type {Texture}
  7252. */
  7253. get value() {
  7254. return this.referenceNode ? this.referenceNode.value : this._value;
  7255. }
  7256. /**
  7257. * Overwritten since the uniform hash is defined by the texture's UUID.
  7258. *
  7259. * @param {NodeBuilder} builder - The current node builder.
  7260. * @return {string} The uniform hash.
  7261. */
  7262. getUniformHash( /*builder*/ ) {
  7263. return this.value.uuid;
  7264. }
  7265. /**
  7266. * Overwritten since the node type is inferred from the texture type.
  7267. *
  7268. * @param {NodeBuilder} builder - The current node builder.
  7269. * @return {string} The node type.
  7270. */
  7271. getNodeType( /*builder*/ ) {
  7272. if ( this.value.isDepthTexture === true ) return 'float';
  7273. if ( this.value.type === UnsignedIntType ) {
  7274. return 'uvec4';
  7275. } else if ( this.value.type === IntType ) {
  7276. return 'ivec4';
  7277. }
  7278. return 'vec4';
  7279. }
  7280. /**
  7281. * Overwrites the default implementation to return a fixed value `'texture'`.
  7282. *
  7283. * @param {NodeBuilder} builder - The current node builder.
  7284. * @return {string} The input type.
  7285. */
  7286. getInputType( /*builder*/ ) {
  7287. return 'texture';
  7288. }
  7289. /**
  7290. * Returns a default uvs based on the current texture's channel.
  7291. *
  7292. * @return {AttributeNode<vec2>} The default uvs.
  7293. */
  7294. getDefaultUV() {
  7295. return uv( this.value.channel );
  7296. }
  7297. /**
  7298. * Overwritten to always return the texture reference of the node.
  7299. *
  7300. * @param {any} state - This method can be invocated in different contexts so `state` can refer to any object type.
  7301. * @return {Texture} The texture reference.
  7302. */
  7303. updateReference( /*state*/ ) {
  7304. return this.value;
  7305. }
  7306. /**
  7307. * Transforms the given uv node with the texture transformation matrix.
  7308. *
  7309. * @param {Node} uvNode - The uv node to transform.
  7310. * @return {Node} The transformed uv node.
  7311. */
  7312. getTransformedUV( uvNode ) {
  7313. if ( this._matrixUniform === null ) this._matrixUniform = uniform( this.value.matrix );
  7314. return this._matrixUniform.mul( vec3( uvNode, 1 ) ).xy;
  7315. }
  7316. /**
  7317. * Defines whether the uv transformation matrix should automatically be updated or not.
  7318. *
  7319. * @param {boolean} value - The update toggle.
  7320. * @return {TextureNode} A reference to this node.
  7321. */
  7322. setUpdateMatrix( value ) {
  7323. this.updateMatrix = value;
  7324. this.updateType = value ? NodeUpdateType.OBJECT : NodeUpdateType.NONE;
  7325. return this;
  7326. }
  7327. /**
  7328. * Setups the uv node. Depending on the backend as well as texture's image and type, it might be necessary
  7329. * to modify the uv node for correct sampling.
  7330. *
  7331. * @param {NodeBuilder} builder - The current node builder.
  7332. * @param {Node} uvNode - The uv node to setup.
  7333. * @return {Node} The updated uv node.
  7334. */
  7335. setupUV( builder, uvNode ) {
  7336. const texture = this.value;
  7337. if ( builder.isFlipY() && ( ( texture.image instanceof ImageBitmap && texture.flipY === true ) || texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true || texture.isDepthTexture === true ) ) {
  7338. if ( this.sampler ) {
  7339. uvNode = uvNode.flipY();
  7340. } else {
  7341. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  7342. }
  7343. }
  7344. return uvNode;
  7345. }
  7346. /**
  7347. * Setups texture node by preparing the internal nodes for code generation.
  7348. *
  7349. * @param {NodeBuilder} builder - The current node builder.
  7350. */
  7351. setup( builder ) {
  7352. const properties = builder.getNodeProperties( this );
  7353. properties.referenceNode = this.referenceNode;
  7354. //
  7355. const texture = this.value;
  7356. if ( ! texture || texture.isTexture !== true ) {
  7357. throw new Error( 'THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().' );
  7358. }
  7359. //
  7360. let uvNode = this.uvNode;
  7361. if ( ( uvNode === null || builder.context.forceUVContext === true ) && builder.context.getUV ) {
  7362. uvNode = builder.context.getUV( this, builder );
  7363. }
  7364. if ( ! uvNode ) uvNode = this.getDefaultUV();
  7365. if ( this.updateMatrix === true ) {
  7366. uvNode = this.getTransformedUV( uvNode );
  7367. }
  7368. uvNode = this.setupUV( builder, uvNode );
  7369. //
  7370. let levelNode = this.levelNode;
  7371. if ( levelNode === null && builder.context.getTextureLevel ) {
  7372. levelNode = builder.context.getTextureLevel( this );
  7373. }
  7374. //
  7375. properties.uvNode = uvNode;
  7376. properties.levelNode = levelNode;
  7377. properties.biasNode = this.biasNode;
  7378. properties.compareNode = this.compareNode;
  7379. properties.gradNode = this.gradNode;
  7380. properties.depthNode = this.depthNode;
  7381. }
  7382. /**
  7383. * Generates the uv code snippet.
  7384. *
  7385. * @param {NodeBuilder} builder - The current node builder.
  7386. * @param {Node} uvNode - The uv node to generate code for.
  7387. * @return {string} The generated code snippet.
  7388. */
  7389. generateUV( builder, uvNode ) {
  7390. return uvNode.build( builder, this.sampler === true ? 'vec2' : 'ivec2' );
  7391. }
  7392. /**
  7393. * Generates the snippet for the texture sampling.
  7394. *
  7395. * @param {NodeBuilder} builder - The current node builder.
  7396. * @param {string} textureProperty - The texture property.
  7397. * @param {string} uvSnippet - The uv snippet.
  7398. * @param {?string} levelSnippet - The level snippet.
  7399. * @param {?string} biasSnippet - The bias snippet.
  7400. * @param {?string} depthSnippet - The depth snippet.
  7401. * @param {?string} compareSnippet - The compare snippet.
  7402. * @param {?Array<string>} gradSnippet - The grad snippet.
  7403. * @return {string} The generated code snippet.
  7404. */
  7405. generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet ) {
  7406. const texture = this.value;
  7407. let snippet;
  7408. if ( levelSnippet ) {
  7409. snippet = builder.generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  7410. } else if ( biasSnippet ) {
  7411. snippet = builder.generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet );
  7412. } else if ( gradSnippet ) {
  7413. snippet = builder.generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet );
  7414. } else if ( compareSnippet ) {
  7415. snippet = builder.generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet );
  7416. } else if ( this.sampler === false ) {
  7417. snippet = builder.generateTextureLoad( texture, textureProperty, uvSnippet, depthSnippet );
  7418. } else {
  7419. snippet = builder.generateTexture( texture, textureProperty, uvSnippet, depthSnippet );
  7420. }
  7421. return snippet;
  7422. }
  7423. /**
  7424. * Generates the code snippet of the texture node.
  7425. *
  7426. * @param {NodeBuilder} builder - The current node builder.
  7427. * @param {string} output - The current output.
  7428. * @return {string} The generated code snippet.
  7429. */
  7430. generate( builder, output ) {
  7431. const texture = this.value;
  7432. const properties = builder.getNodeProperties( this );
  7433. const textureProperty = super.generate( builder, 'property' );
  7434. if ( /^sampler/.test( output ) ) {
  7435. return textureProperty + '_sampler';
  7436. } else if ( builder.isReference( output ) ) {
  7437. return textureProperty;
  7438. } else {
  7439. const nodeData = builder.getDataFromNode( this );
  7440. let propertyName = nodeData.propertyName;
  7441. if ( propertyName === undefined ) {
  7442. const { uvNode, levelNode, biasNode, compareNode, depthNode, gradNode } = properties;
  7443. const uvSnippet = this.generateUV( builder, uvNode );
  7444. const levelSnippet = levelNode ? levelNode.build( builder, 'float' ) : null;
  7445. const biasSnippet = biasNode ? biasNode.build( builder, 'float' ) : null;
  7446. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  7447. const compareSnippet = compareNode ? compareNode.build( builder, 'float' ) : null;
  7448. const gradSnippet = gradNode ? [ gradNode[ 0 ].build( builder, 'vec2' ), gradNode[ 1 ].build( builder, 'vec2' ) ] : null;
  7449. const nodeVar = builder.getVarFromNode( this );
  7450. propertyName = builder.getPropertyName( nodeVar );
  7451. const snippet = this.generateSnippet( builder, textureProperty, uvSnippet, levelSnippet, biasSnippet, depthSnippet, compareSnippet, gradSnippet );
  7452. builder.addLineFlowCode( `${propertyName} = ${snippet}`, this );
  7453. nodeData.snippet = snippet;
  7454. nodeData.propertyName = propertyName;
  7455. }
  7456. let snippet = propertyName;
  7457. const nodeType = this.getNodeType( builder );
  7458. if ( builder.needsToWorkingColorSpace( texture ) ) {
  7459. snippet = colorSpaceToWorking( expression( snippet, nodeType ), texture.colorSpace ).setup( builder ).build( builder, nodeType );
  7460. }
  7461. return builder.format( snippet, nodeType, output );
  7462. }
  7463. }
  7464. /**
  7465. * Sets the sampler value.
  7466. *
  7467. * @param {boolean} value - The sampler value to set.
  7468. * @return {TextureNode} A reference to this texture node.
  7469. */
  7470. setSampler( value ) {
  7471. this.sampler = value;
  7472. return this;
  7473. }
  7474. /**
  7475. * Returns the sampler value.
  7476. *
  7477. * @return {boolean} The sampler value.
  7478. */
  7479. getSampler() {
  7480. return this.sampler;
  7481. }
  7482. // @TODO: Move to TSL
  7483. /**
  7484. * @function
  7485. * @deprecated since r172. Use {@link TextureNode#sample} instead.
  7486. *
  7487. * @param {Node} uvNode - The uv node.
  7488. * @return {TextureNode} A texture node representing the texture sample.
  7489. */
  7490. uv( uvNode ) { // @deprecated, r172
  7491. console.warn( 'THREE.TextureNode: .uv() has been renamed. Use .sample() instead.' );
  7492. return this.sample( uvNode );
  7493. }
  7494. /**
  7495. * Samples the texture with the given uv node.
  7496. *
  7497. * @param {Node} uvNode - The uv node.
  7498. * @return {TextureNode} A texture node representing the texture sample.
  7499. */
  7500. sample( uvNode ) {
  7501. const textureNode = this.clone();
  7502. textureNode.uvNode = nodeObject( uvNode );
  7503. textureNode.referenceNode = this.getSelf();
  7504. return nodeObject( textureNode );
  7505. }
  7506. /**
  7507. * Samples a blurred version of the texture by defining an internal bias.
  7508. *
  7509. * @param {Node<float>} amountNode - How blurred the texture should be.
  7510. * @return {TextureNode} A texture node representing the texture sample.
  7511. */
  7512. blur( amountNode ) {
  7513. const textureNode = this.clone();
  7514. textureNode.biasNode = nodeObject( amountNode ).mul( maxMipLevel( textureNode ) );
  7515. textureNode.referenceNode = this.getSelf();
  7516. const map = textureNode.value;
  7517. if ( textureNode.generateMipmaps === false && ( map && map.generateMipmaps === false || map.minFilter === NearestFilter || map.magFilter === NearestFilter ) ) {
  7518. console.warn( 'THREE.TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture.' );
  7519. textureNode.biasNode = null;
  7520. }
  7521. return nodeObject( textureNode );
  7522. }
  7523. /**
  7524. * Samples a specific mip of the texture.
  7525. *
  7526. * @param {Node<int>} levelNode - The mip level to sample.
  7527. * @return {TextureNode} A texture node representing the texture sample.
  7528. */
  7529. level( levelNode ) {
  7530. const textureNode = this.clone();
  7531. textureNode.levelNode = nodeObject( levelNode );
  7532. textureNode.referenceNode = this.getSelf();
  7533. return nodeObject( textureNode );
  7534. }
  7535. /**
  7536. * Returns the texture size of the requested level.
  7537. *
  7538. * @param {Node<int>} levelNode - The level to compute the size for.
  7539. * @return {TextureSizeNode} The texture size.
  7540. */
  7541. size( levelNode ) {
  7542. return textureSize( this, levelNode );
  7543. }
  7544. /**
  7545. * Samples the texture with the given bias.
  7546. *
  7547. * @param {Node<float>} biasNode - The bias node.
  7548. * @return {TextureNode} A texture node representing the texture sample.
  7549. */
  7550. bias( biasNode ) {
  7551. const textureNode = this.clone();
  7552. textureNode.biasNode = nodeObject( biasNode );
  7553. textureNode.referenceNode = this.getSelf();
  7554. return nodeObject( textureNode );
  7555. }
  7556. /**
  7557. * Samples the texture by executing a compare operation.
  7558. *
  7559. * @param {Node<float>} compareNode - The node that defines the compare value.
  7560. * @return {TextureNode} A texture node representing the texture sample.
  7561. */
  7562. compare( compareNode ) {
  7563. const textureNode = this.clone();
  7564. textureNode.compareNode = nodeObject( compareNode );
  7565. textureNode.referenceNode = this.getSelf();
  7566. return nodeObject( textureNode );
  7567. }
  7568. /**
  7569. * Samples the texture using an explicit gradient.
  7570. *
  7571. * @param {Node<vec2>} gradNodeX - The gradX node.
  7572. * @param {Node<vec2>} gradNodeY - The gradY node.
  7573. * @return {TextureNode} A texture node representing the texture sample.
  7574. */
  7575. grad( gradNodeX, gradNodeY ) {
  7576. const textureNode = this.clone();
  7577. textureNode.gradNode = [ nodeObject( gradNodeX ), nodeObject( gradNodeY ) ];
  7578. textureNode.referenceNode = this.getSelf();
  7579. return nodeObject( textureNode );
  7580. }
  7581. /**
  7582. * Samples the texture by defining a depth node.
  7583. *
  7584. * @param {Node<int>} depthNode - The depth node.
  7585. * @return {TextureNode} A texture node representing the texture sample.
  7586. */
  7587. depth( depthNode ) {
  7588. const textureNode = this.clone();
  7589. textureNode.depthNode = nodeObject( depthNode );
  7590. textureNode.referenceNode = this.getSelf();
  7591. return nodeObject( textureNode );
  7592. }
  7593. // --
  7594. serialize( data ) {
  7595. super.serialize( data );
  7596. data.value = this.value.toJSON( data.meta ).uuid;
  7597. data.sampler = this.sampler;
  7598. data.updateMatrix = this.updateMatrix;
  7599. data.updateType = this.updateType;
  7600. }
  7601. deserialize( data ) {
  7602. super.deserialize( data );
  7603. this.value = data.meta.textures[ data.value ];
  7604. this.sampler = data.sampler;
  7605. this.updateMatrix = data.updateMatrix;
  7606. this.updateType = data.updateType;
  7607. }
  7608. /**
  7609. * The update is used to implement the update of the uv transformation matrix.
  7610. */
  7611. update() {
  7612. const texture = this.value;
  7613. const matrixUniform = this._matrixUniform;
  7614. if ( matrixUniform !== null ) matrixUniform.value = texture.matrix;
  7615. if ( texture.matrixAutoUpdate === true ) {
  7616. texture.updateMatrix();
  7617. }
  7618. }
  7619. /**
  7620. * Clones the texture node.
  7621. *
  7622. * @return {TextureNode} The cloned texture node.
  7623. */
  7624. clone() {
  7625. const newNode = new this.constructor( this.value, this.uvNode, this.levelNode, this.biasNode );
  7626. newNode.sampler = this.sampler;
  7627. newNode.depthNode = this.depthNode;
  7628. newNode.compareNode = this.compareNode;
  7629. newNode.gradNode = this.gradNode;
  7630. return newNode;
  7631. }
  7632. }
  7633. /**
  7634. * TSL function for creating a texture node.
  7635. *
  7636. * @tsl
  7637. * @function
  7638. * @param {?Texture} value - The texture.
  7639. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7640. * @param {?Node<int>} [levelNode=null] - The level node.
  7641. * @param {?Node<float>} [biasNode=null] - The bias node.
  7642. * @returns {TextureNode}
  7643. */
  7644. const textureBase = /*@__PURE__*/ nodeProxy( TextureNode ).setParameterLength( 1, 4 ).setName( 'texture' );
  7645. /**
  7646. * TSL function for creating a texture node or sample a texture node already existing.
  7647. *
  7648. * @tsl
  7649. * @function
  7650. * @param {?Texture|TextureNode} [value=EmptyTexture] - The texture.
  7651. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7652. * @param {?Node<int>} [levelNode=null] - The level node.
  7653. * @param {?Node<float>} [biasNode=null] - The bias node.
  7654. * @returns {TextureNode}
  7655. */
  7656. const texture = ( value = EmptyTexture$1, uvNode = null, levelNode = null, biasNode = null ) => {
  7657. let textureNode;
  7658. if ( value && value.isTextureNode === true ) {
  7659. textureNode = nodeObject( value.clone() );
  7660. textureNode.referenceNode = value.getSelf(); // Ensure the reference is set to the original node
  7661. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  7662. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  7663. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  7664. } else {
  7665. textureNode = textureBase( value, uvNode, levelNode, biasNode );
  7666. }
  7667. return textureNode;
  7668. };
  7669. /**
  7670. * TSL function for creating a uniform texture node.
  7671. *
  7672. * @tsl
  7673. * @function
  7674. * @param {?Texture} value - The texture.
  7675. * @returns {TextureNode}
  7676. */
  7677. const uniformTexture = ( value = EmptyTexture$1 ) => texture( value );
  7678. /**
  7679. * TSL function for creating a texture node that fetches/loads texels without interpolation.
  7680. *
  7681. * @tsl
  7682. * @function
  7683. * @param {?Texture|TextureNode} [value=EmptyTexture] - The texture.
  7684. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  7685. * @param {?Node<int>} [levelNode=null] - The level node.
  7686. * @param {?Node<float>} [biasNode=null] - The bias node.
  7687. * @returns {TextureNode}
  7688. */
  7689. const textureLoad = ( ...params ) => texture( ...params ).setSampler( false );
  7690. //export const textureLevel = ( value, uv, level ) => texture( value, uv ).level( level );
  7691. /**
  7692. * Converts a texture or texture node to a sampler.
  7693. *
  7694. * @tsl
  7695. * @function
  7696. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7697. * @returns {Node}
  7698. */
  7699. const sampler = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'sampler' );
  7700. /**
  7701. * Converts a texture or texture node to a sampler comparison.
  7702. *
  7703. * @tsl
  7704. * @function
  7705. * @param {TextureNode|Texture} value - The texture or texture node to convert.
  7706. * @returns {Node}
  7707. */
  7708. const samplerComparison = ( value ) => ( value.isNode === true ? value : texture( value ) ).convert( 'samplerComparison' );
  7709. /**
  7710. * A special type of uniform node which represents array-like data
  7711. * as uniform buffers. The access usually happens via `element()`
  7712. * which returns an instance of {@link ArrayElementNode}. For example:
  7713. *
  7714. * ```js
  7715. * const bufferNode = buffer( array, 'mat4', count );
  7716. * const matrixNode = bufferNode.element( index ); // access a matrix from the buffer
  7717. * ```
  7718. * In general, it is recommended to use the more managed {@link UniformArrayNode}
  7719. * since it handles more input types and automatically cares about buffer paddings.
  7720. *
  7721. * @augments UniformNode
  7722. */
  7723. class BufferNode extends UniformNode {
  7724. static get type() {
  7725. return 'BufferNode';
  7726. }
  7727. /**
  7728. * Constructs a new buffer node.
  7729. *
  7730. * @param {Array<number>} value - Array-like buffer data.
  7731. * @param {string} bufferType - The data type of the buffer.
  7732. * @param {number} [bufferCount=0] - The count of buffer elements.
  7733. */
  7734. constructor( value, bufferType, bufferCount = 0 ) {
  7735. super( value, bufferType );
  7736. /**
  7737. * This flag can be used for type testing.
  7738. *
  7739. * @type {boolean}
  7740. * @readonly
  7741. * @default true
  7742. */
  7743. this.isBufferNode = true;
  7744. /**
  7745. * The data type of the buffer.
  7746. *
  7747. * @type {string}
  7748. */
  7749. this.bufferType = bufferType;
  7750. /**
  7751. * The uniform node that holds the value of the reference node.
  7752. *
  7753. * @type {number}
  7754. * @default 0
  7755. */
  7756. this.bufferCount = bufferCount;
  7757. }
  7758. /**
  7759. * The data type of the buffer elements.
  7760. *
  7761. * @param {NodeBuilder} builder - The current node builder.
  7762. * @return {string} The element type.
  7763. */
  7764. getElementType( builder ) {
  7765. return this.getNodeType( builder );
  7766. }
  7767. /**
  7768. * Overwrites the default implementation to return a fixed value `'buffer'`.
  7769. *
  7770. * @param {NodeBuilder} builder - The current node builder.
  7771. * @return {string} The input type.
  7772. */
  7773. getInputType( /*builder*/ ) {
  7774. return 'buffer';
  7775. }
  7776. }
  7777. /**
  7778. * TSL function for creating a buffer node.
  7779. *
  7780. * @tsl
  7781. * @function
  7782. * @param {Array} value - Array-like buffer data.
  7783. * @param {string} type - The data type of a buffer element.
  7784. * @param {number} count - The count of buffer elements.
  7785. * @returns {BufferNode}
  7786. */
  7787. const buffer = ( value, type, count ) => nodeObject( new BufferNode( value, type, count ) );
  7788. /**
  7789. * Represents the element access on uniform array nodes.
  7790. *
  7791. * @augments ArrayElementNode
  7792. */
  7793. class UniformArrayElementNode extends ArrayElementNode {
  7794. static get type() {
  7795. return 'UniformArrayElementNode';
  7796. }
  7797. /**
  7798. * Constructs a new buffer node.
  7799. *
  7800. * @param {UniformArrayNode} uniformArrayNode - The uniform array node to access.
  7801. * @param {IndexNode} indexNode - The index data that define the position of the accessed element in the array.
  7802. */
  7803. constructor( uniformArrayNode, indexNode ) {
  7804. super( uniformArrayNode, indexNode );
  7805. /**
  7806. * This flag can be used for type testing.
  7807. *
  7808. * @type {boolean}
  7809. * @readonly
  7810. * @default true
  7811. */
  7812. this.isArrayBufferElementNode = true;
  7813. }
  7814. generate( builder ) {
  7815. const snippet = super.generate( builder );
  7816. const type = this.getNodeType();
  7817. const paddedType = this.node.getPaddedType();
  7818. return builder.format( snippet, paddedType, type );
  7819. }
  7820. }
  7821. /**
  7822. * Similar to {@link BufferNode} this module represents array-like data as
  7823. * uniform buffers. Unlike {@link BufferNode}, it can handle more common
  7824. * data types in the array (e.g `three.js` primitives) and automatically
  7825. * manage buffer padding. It should be the first choice when working with
  7826. * uniforms buffers.
  7827. * ```js
  7828. * const tintColors = uniformArray( [
  7829. * new Color( 1, 0, 0 ),
  7830. * new Color( 0, 1, 0 ),
  7831. * new Color( 0, 0, 1 )
  7832. * ], 'color' );
  7833. *
  7834. * const redColor = tintColors.element( 0 );
  7835. *
  7836. * @augments BufferNode
  7837. */
  7838. class UniformArrayNode extends BufferNode {
  7839. static get type() {
  7840. return 'UniformArrayNode';
  7841. }
  7842. /**
  7843. * Constructs a new uniform array node.
  7844. *
  7845. * @param {Array<any>} value - Array holding the buffer data.
  7846. * @param {?string} [elementType=null] - The data type of a buffer element.
  7847. */
  7848. constructor( value, elementType = null ) {
  7849. super( null );
  7850. /**
  7851. * Array holding the buffer data. Unlike {@link BufferNode}, the array can
  7852. * hold number primitives as well as three.js objects like vectors, matrices
  7853. * or colors.
  7854. *
  7855. * @type {Array<any>}
  7856. */
  7857. this.array = value;
  7858. /**
  7859. * The data type of an array element.
  7860. *
  7861. * @type {string}
  7862. */
  7863. this.elementType = elementType === null ? getValueType( value[ 0 ] ) : elementType;
  7864. /**
  7865. * The padded type. Uniform buffers must conform to a certain buffer layout
  7866. * so a separate type is computed to ensure correct buffer size.
  7867. *
  7868. * @type {string}
  7869. */
  7870. this.paddedType = this.getPaddedType();
  7871. /**
  7872. * Overwritten since uniform array nodes are updated per render.
  7873. *
  7874. * @type {string}
  7875. * @default 'render'
  7876. */
  7877. this.updateType = NodeUpdateType.RENDER;
  7878. /**
  7879. * This flag can be used for type testing.
  7880. *
  7881. * @type {boolean}
  7882. * @readonly
  7883. * @default true
  7884. */
  7885. this.isArrayBufferNode = true;
  7886. }
  7887. /**
  7888. * This method is overwritten since the node type is inferred from the
  7889. * {@link UniformArrayNode#paddedType}.
  7890. *
  7891. * @param {NodeBuilder} builder - The current node builder.
  7892. * @return {string} The node type.
  7893. */
  7894. getNodeType( /*builder*/ ) {
  7895. return this.paddedType;
  7896. }
  7897. /**
  7898. * The data type of the array elements.
  7899. *
  7900. * @param {NodeBuilder} builder - The current node builder.
  7901. * @return {string} The element type.
  7902. */
  7903. getElementType() {
  7904. return this.elementType;
  7905. }
  7906. /**
  7907. * Returns the padded type based on the element type.
  7908. *
  7909. * @return {string} The padded type.
  7910. */
  7911. getPaddedType() {
  7912. const elementType = this.elementType;
  7913. let paddedType = 'vec4';
  7914. if ( elementType === 'mat2' ) {
  7915. paddedType = 'mat2';
  7916. } else if ( /mat/.test( elementType ) === true ) {
  7917. paddedType = 'mat4';
  7918. } else if ( elementType.charAt( 0 ) === 'i' ) {
  7919. paddedType = 'ivec4';
  7920. } else if ( elementType.charAt( 0 ) === 'u' ) {
  7921. paddedType = 'uvec4';
  7922. }
  7923. return paddedType;
  7924. }
  7925. /**
  7926. * The update makes sure to correctly transfer the data from the (complex) objects
  7927. * in the array to the internal, correctly padded value buffer.
  7928. *
  7929. * @param {NodeFrame} frame - A reference to the current node frame.
  7930. */
  7931. update( /*frame*/ ) {
  7932. const { array, value } = this;
  7933. const elementType = this.elementType;
  7934. if ( elementType === 'float' || elementType === 'int' || elementType === 'uint' ) {
  7935. for ( let i = 0; i < array.length; i ++ ) {
  7936. const index = i * 4;
  7937. value[ index ] = array[ i ];
  7938. }
  7939. } else if ( elementType === 'color' ) {
  7940. for ( let i = 0; i < array.length; i ++ ) {
  7941. const index = i * 4;
  7942. const vector = array[ i ];
  7943. value[ index ] = vector.r;
  7944. value[ index + 1 ] = vector.g;
  7945. value[ index + 2 ] = vector.b || 0;
  7946. //value[ index + 3 ] = vector.a || 0;
  7947. }
  7948. } else if ( elementType === 'mat2' ) {
  7949. for ( let i = 0; i < array.length; i ++ ) {
  7950. const index = i * 4;
  7951. const matrix = array[ i ];
  7952. value[ index ] = matrix.elements[ 0 ];
  7953. value[ index + 1 ] = matrix.elements[ 1 ];
  7954. value[ index + 2 ] = matrix.elements[ 2 ];
  7955. value[ index + 3 ] = matrix.elements[ 3 ];
  7956. }
  7957. } else if ( elementType === 'mat3' ) {
  7958. for ( let i = 0; i < array.length; i ++ ) {
  7959. const index = i * 16;
  7960. const matrix = array[ i ];
  7961. value[ index ] = matrix.elements[ 0 ];
  7962. value[ index + 1 ] = matrix.elements[ 1 ];
  7963. value[ index + 2 ] = matrix.elements[ 2 ];
  7964. value[ index + 4 ] = matrix.elements[ 3 ];
  7965. value[ index + 5 ] = matrix.elements[ 4 ];
  7966. value[ index + 6 ] = matrix.elements[ 5 ];
  7967. value[ index + 8 ] = matrix.elements[ 6 ];
  7968. value[ index + 9 ] = matrix.elements[ 7 ];
  7969. value[ index + 10 ] = matrix.elements[ 8 ];
  7970. value[ index + 15 ] = 1;
  7971. }
  7972. } else if ( elementType === 'mat4' ) {
  7973. for ( let i = 0; i < array.length; i ++ ) {
  7974. const index = i * 16;
  7975. const matrix = array[ i ];
  7976. for ( let i = 0; i < matrix.elements.length; i ++ ) {
  7977. value[ index + i ] = matrix.elements[ i ];
  7978. }
  7979. }
  7980. } else {
  7981. for ( let i = 0; i < array.length; i ++ ) {
  7982. const index = i * 4;
  7983. const vector = array[ i ];
  7984. value[ index ] = vector.x;
  7985. value[ index + 1 ] = vector.y;
  7986. value[ index + 2 ] = vector.z || 0;
  7987. value[ index + 3 ] = vector.w || 0;
  7988. }
  7989. }
  7990. }
  7991. /**
  7992. * Implement the value buffer creation based on the array data.
  7993. *
  7994. * @param {NodeBuilder} builder - A reference to the current node builder.
  7995. * @return {null}
  7996. */
  7997. setup( builder ) {
  7998. const length = this.array.length;
  7999. const elementType = this.elementType;
  8000. let arrayType = Float32Array;
  8001. const paddedType = this.paddedType;
  8002. const paddedElementLength = builder.getTypeLength( paddedType );
  8003. if ( elementType.charAt( 0 ) === 'i' ) arrayType = Int32Array;
  8004. if ( elementType.charAt( 0 ) === 'u' ) arrayType = Uint32Array;
  8005. this.value = new arrayType( length * paddedElementLength );
  8006. this.bufferCount = length;
  8007. this.bufferType = paddedType;
  8008. return super.setup( builder );
  8009. }
  8010. /**
  8011. * Overwrites the default `element()` method to provide element access
  8012. * based on {@link UniformArrayNode}.
  8013. *
  8014. * @param {IndexNode} indexNode - The index node.
  8015. * @return {UniformArrayElementNode}
  8016. */
  8017. element( indexNode ) {
  8018. return nodeObject( new UniformArrayElementNode( this, nodeObject( indexNode ) ) );
  8019. }
  8020. }
  8021. /**
  8022. * TSL function for creating an uniform array node.
  8023. *
  8024. * @tsl
  8025. * @function
  8026. * @param {Array<any>} values - Array-like data.
  8027. * @param {?string} [nodeType] - The data type of the array elements.
  8028. * @returns {UniformArrayNode}
  8029. */
  8030. const uniformArray = ( values, nodeType ) => nodeObject( new UniformArrayNode( values, nodeType ) );
  8031. /**
  8032. * @tsl
  8033. * @function
  8034. * @deprecated since r168. Use {@link uniformArray} instead.
  8035. *
  8036. * @param {Array<any>} values - Array-like data.
  8037. * @param {string} nodeType - The data type of the array elements.
  8038. * @returns {UniformArrayNode}
  8039. */
  8040. const uniforms = ( values, nodeType ) => { // @deprecated, r168
  8041. console.warn( 'THREE.TSL: uniforms() has been renamed to uniformArray().' );
  8042. return nodeObject( new UniformArrayNode( values, nodeType ) );
  8043. };
  8044. /**
  8045. * The node allows to set values for built-in shader variables. That is
  8046. * required for features like hardware-accelerated vertex clipping.
  8047. *
  8048. * @augments Node
  8049. */
  8050. class BuiltinNode extends Node {
  8051. /**
  8052. * Constructs a new builtin node.
  8053. *
  8054. * @param {string} name - The name of the built-in shader variable.
  8055. */
  8056. constructor( name ) {
  8057. super( 'float' );
  8058. /**
  8059. * The name of the built-in shader variable.
  8060. *
  8061. * @type {string}
  8062. */
  8063. this.name = name;
  8064. /**
  8065. * This flag can be used for type testing.
  8066. *
  8067. * @type {boolean}
  8068. * @readonly
  8069. * @default true
  8070. */
  8071. this.isBuiltinNode = true;
  8072. }
  8073. /**
  8074. * Generates the code snippet of the builtin node.
  8075. *
  8076. * @param {NodeBuilder} builder - The current node builder.
  8077. * @return {string} The generated code snippet.
  8078. */
  8079. generate( /* builder */ ) {
  8080. return this.name;
  8081. }
  8082. }
  8083. /**
  8084. * TSL function for creating a builtin node.
  8085. *
  8086. * @tsl
  8087. * @function
  8088. * @param {string} name - The name of the built-in shader variable.
  8089. * @returns {BuiltinNode}
  8090. */
  8091. const builtin = nodeProxy( BuiltinNode ).setParameterLength( 1 );
  8092. /**
  8093. * TSL object that represents the current `index` value of the camera if used ArrayCamera.
  8094. *
  8095. * @tsl
  8096. * @type {UniformNode<uint>}
  8097. */
  8098. const cameraIndex = /*@__PURE__*/ uniform( 0, 'uint' ).label( 'u_cameraIndex' ).setGroup( sharedUniformGroup( 'cameraIndex' ) ).toVarying( 'v_cameraIndex' );
  8099. /**
  8100. * TSL object that represents the `near` value of the camera used for the current render.
  8101. *
  8102. * @tsl
  8103. * @type {UniformNode<float>}
  8104. */
  8105. const cameraNear = /*@__PURE__*/ uniform( 'float' ).label( 'cameraNear' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.near );
  8106. /**
  8107. * TSL object that represents the `far` value of the camera used for the current render.
  8108. *
  8109. * @tsl
  8110. * @type {UniformNode<float>}
  8111. */
  8112. const cameraFar = /*@__PURE__*/ uniform( 'float' ).label( 'cameraFar' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.far );
  8113. /**
  8114. * TSL object that represents the projection matrix of the camera used for the current render.
  8115. *
  8116. * @tsl
  8117. * @type {UniformNode<mat4>}
  8118. */
  8119. const cameraProjectionMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8120. let cameraProjectionMatrix;
  8121. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8122. const matrices = [];
  8123. for ( const subCamera of camera.cameras ) {
  8124. matrices.push( subCamera.projectionMatrix );
  8125. }
  8126. const cameraProjectionMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatrices' );
  8127. cameraProjectionMatrix = cameraProjectionMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraProjectionMatrix' );
  8128. } else {
  8129. cameraProjectionMatrix = uniform( 'mat4' ).label( 'cameraProjectionMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrix );
  8130. }
  8131. return cameraProjectionMatrix;
  8132. } ).once() )();
  8133. /**
  8134. * TSL object that represents the inverse projection matrix of the camera used for the current render.
  8135. *
  8136. * @tsl
  8137. * @type {UniformNode<mat4>}
  8138. */
  8139. const cameraProjectionMatrixInverse = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8140. let cameraProjectionMatrixInverse;
  8141. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8142. const matrices = [];
  8143. for ( const subCamera of camera.cameras ) {
  8144. matrices.push( subCamera.projectionMatrixInverse );
  8145. }
  8146. const cameraProjectionMatricesInverse = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraProjectionMatricesInverse' );
  8147. cameraProjectionMatrixInverse = cameraProjectionMatricesInverse.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraProjectionMatrixInverse' );
  8148. } else {
  8149. cameraProjectionMatrixInverse = uniform( 'mat4' ).label( 'cameraProjectionMatrixInverse' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.projectionMatrixInverse );
  8150. }
  8151. return cameraProjectionMatrixInverse;
  8152. } ).once() )();
  8153. /**
  8154. * TSL object that represents the view matrix of the camera used for the current render.
  8155. *
  8156. * @tsl
  8157. * @type {UniformNode<mat4>}
  8158. */
  8159. const cameraViewMatrix = /*@__PURE__*/ ( Fn( ( { camera } ) => {
  8160. let cameraViewMatrix;
  8161. if ( camera.isArrayCamera && camera.cameras.length > 0 ) {
  8162. const matrices = [];
  8163. for ( const subCamera of camera.cameras ) {
  8164. matrices.push( subCamera.matrixWorldInverse );
  8165. }
  8166. const cameraViewMatrices = uniformArray( matrices ).setGroup( renderGroup ).label( 'cameraViewMatrices' );
  8167. cameraViewMatrix = cameraViewMatrices.element( camera.isMultiViewCamera ? builtin( 'gl_ViewID_OVR' ) : cameraIndex ).toVar( 'cameraViewMatrix' );
  8168. } else {
  8169. cameraViewMatrix = uniform( 'mat4' ).label( 'cameraViewMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorldInverse );
  8170. }
  8171. return cameraViewMatrix;
  8172. } ).once() )();
  8173. /**
  8174. * TSL object that represents the world matrix of the camera used for the current render.
  8175. *
  8176. * @tsl
  8177. * @type {UniformNode<mat4>}
  8178. */
  8179. const cameraWorldMatrix = /*@__PURE__*/ uniform( 'mat4' ).label( 'cameraWorldMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.matrixWorld );
  8180. /**
  8181. * TSL object that represents the normal matrix of the camera used for the current render.
  8182. *
  8183. * @tsl
  8184. * @type {UniformNode<mat3>}
  8185. */
  8186. const cameraNormalMatrix = /*@__PURE__*/ uniform( 'mat3' ).label( 'cameraNormalMatrix' ).setGroup( renderGroup ).onRenderUpdate( ( { camera } ) => camera.normalMatrix );
  8187. /**
  8188. * TSL object that represents the position in world space of the camera used for the current render.
  8189. *
  8190. * @tsl
  8191. * @type {UniformNode<vec3>}
  8192. */
  8193. const cameraPosition = /*@__PURE__*/ uniform( new Vector3() ).label( 'cameraPosition' ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => self.value.setFromMatrixPosition( camera.matrixWorld ) );
  8194. const _sphere = /*@__PURE__*/ new Sphere();
  8195. /**
  8196. * This node can be used to access transformation related metrics of 3D objects.
  8197. * Depending on the selected scope, a different metric is represented as a uniform
  8198. * in the shader. The following scopes are supported:
  8199. *
  8200. * - `POSITION`: The object's position in world space.
  8201. * - `VIEW_POSITION`: The object's position in view/camera space.
  8202. * - `DIRECTION`: The object's direction in world space.
  8203. * - `SCALE`: The object's scale in world space.
  8204. * - `WORLD_MATRIX`: The object's matrix in world space.
  8205. *
  8206. * @augments Node
  8207. */
  8208. class Object3DNode extends Node {
  8209. static get type() {
  8210. return 'Object3DNode';
  8211. }
  8212. /**
  8213. * Constructs a new object 3D node.
  8214. *
  8215. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8216. * @param {?Object3D} [object3d=null] - The 3D object.
  8217. */
  8218. constructor( scope, object3d = null ) {
  8219. super();
  8220. /**
  8221. * The node reports a different type of transformation depending on the scope.
  8222. *
  8223. * @type {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')}
  8224. */
  8225. this.scope = scope;
  8226. /**
  8227. * The 3D object.
  8228. *
  8229. * @type {?Object3D}
  8230. * @default null
  8231. */
  8232. this.object3d = object3d;
  8233. /**
  8234. * Overwritten since this type of node is updated per object.
  8235. *
  8236. * @type {string}
  8237. * @default 'object'
  8238. */
  8239. this.updateType = NodeUpdateType.OBJECT;
  8240. /**
  8241. * Holds the value of the node as a uniform.
  8242. *
  8243. * @type {UniformNode}
  8244. */
  8245. this.uniformNode = new UniformNode( null );
  8246. }
  8247. /**
  8248. * Overwritten since the node type is inferred from the scope.
  8249. *
  8250. * @return {string} The node type.
  8251. */
  8252. getNodeType() {
  8253. const scope = this.scope;
  8254. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8255. return 'mat4';
  8256. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8257. return 'vec3';
  8258. } else if ( scope === Object3DNode.RADIUS ) {
  8259. return 'float';
  8260. }
  8261. }
  8262. /**
  8263. * Updates the uniform value depending on the scope.
  8264. *
  8265. * @param {NodeFrame} frame - The current node frame.
  8266. */
  8267. update( frame ) {
  8268. const object = this.object3d;
  8269. const uniformNode = this.uniformNode;
  8270. const scope = this.scope;
  8271. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8272. uniformNode.value = object.matrixWorld;
  8273. } else if ( scope === Object3DNode.POSITION ) {
  8274. uniformNode.value = uniformNode.value || new Vector3();
  8275. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8276. } else if ( scope === Object3DNode.SCALE ) {
  8277. uniformNode.value = uniformNode.value || new Vector3();
  8278. uniformNode.value.setFromMatrixScale( object.matrixWorld );
  8279. } else if ( scope === Object3DNode.DIRECTION ) {
  8280. uniformNode.value = uniformNode.value || new Vector3();
  8281. object.getWorldDirection( uniformNode.value );
  8282. } else if ( scope === Object3DNode.VIEW_POSITION ) {
  8283. const camera = frame.camera;
  8284. uniformNode.value = uniformNode.value || new Vector3();
  8285. uniformNode.value.setFromMatrixPosition( object.matrixWorld );
  8286. uniformNode.value.applyMatrix4( camera.matrixWorldInverse );
  8287. } else if ( scope === Object3DNode.RADIUS ) {
  8288. const geometry = frame.object.geometry;
  8289. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  8290. _sphere.copy( geometry.boundingSphere ).applyMatrix4( object.matrixWorld );
  8291. uniformNode.value = _sphere.radius;
  8292. }
  8293. }
  8294. /**
  8295. * Generates the code snippet of the uniform node. The node type of the uniform
  8296. * node also depends on the selected scope.
  8297. *
  8298. * @param {NodeBuilder} builder - The current node builder.
  8299. * @return {string} The generated code snippet.
  8300. */
  8301. generate( builder ) {
  8302. const scope = this.scope;
  8303. if ( scope === Object3DNode.WORLD_MATRIX ) {
  8304. this.uniformNode.nodeType = 'mat4';
  8305. } else if ( scope === Object3DNode.POSITION || scope === Object3DNode.VIEW_POSITION || scope === Object3DNode.DIRECTION || scope === Object3DNode.SCALE ) {
  8306. this.uniformNode.nodeType = 'vec3';
  8307. } else if ( scope === Object3DNode.RADIUS ) {
  8308. this.uniformNode.nodeType = 'float';
  8309. }
  8310. return this.uniformNode.build( builder );
  8311. }
  8312. serialize( data ) {
  8313. super.serialize( data );
  8314. data.scope = this.scope;
  8315. }
  8316. deserialize( data ) {
  8317. super.deserialize( data );
  8318. this.scope = data.scope;
  8319. }
  8320. }
  8321. Object3DNode.WORLD_MATRIX = 'worldMatrix';
  8322. Object3DNode.POSITION = 'position';
  8323. Object3DNode.SCALE = 'scale';
  8324. Object3DNode.VIEW_POSITION = 'viewPosition';
  8325. Object3DNode.DIRECTION = 'direction';
  8326. Object3DNode.RADIUS = 'radius';
  8327. /**
  8328. * TSL function for creating an object 3D node that represents the object's direction in world space.
  8329. *
  8330. * @tsl
  8331. * @function
  8332. * @param {?Object3D} [object3d] - The 3D object.
  8333. * @returns {Object3DNode<vec3>}
  8334. */
  8335. const objectDirection = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.DIRECTION ).setParameterLength( 1 );
  8336. /**
  8337. * TSL function for creating an object 3D node that represents the object's world matrix.
  8338. *
  8339. * @tsl
  8340. * @function
  8341. * @param {?Object3D} [object3d] - The 3D object.
  8342. * @returns {Object3DNode<mat4>}
  8343. */
  8344. const objectWorldMatrix = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.WORLD_MATRIX ).setParameterLength( 1 );
  8345. /**
  8346. * TSL function for creating an object 3D node that represents the object's position in world space.
  8347. *
  8348. * @tsl
  8349. * @function
  8350. * @param {?Object3D} [object3d] - The 3D object.
  8351. * @returns {Object3DNode<vec3>}
  8352. */
  8353. const objectPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.POSITION ).setParameterLength( 1 );
  8354. /**
  8355. * TSL function for creating an object 3D node that represents the object's scale in world space.
  8356. *
  8357. * @tsl
  8358. * @function
  8359. * @param {?Object3D} [object3d] - The 3D object.
  8360. * @returns {Object3DNode<vec3>}
  8361. */
  8362. const objectScale = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.SCALE ).setParameterLength( 1 );
  8363. /**
  8364. * TSL function for creating an object 3D node that represents the object's position in view/camera space.
  8365. *
  8366. * @tsl
  8367. * @function
  8368. * @param {?Object3D} [object3d] - The 3D object.
  8369. * @returns {Object3DNode<vec3>}
  8370. */
  8371. const objectViewPosition = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.VIEW_POSITION ).setParameterLength( 1 );
  8372. /**
  8373. * TSL function for creating an object 3D node that represents the object's radius.
  8374. *
  8375. * @tsl
  8376. * @function
  8377. * @param {?Object3D} [object3d] - The 3D object.
  8378. * @returns {Object3DNode<float>}
  8379. */
  8380. const objectRadius = /*@__PURE__*/ nodeProxy( Object3DNode, Object3DNode.RADIUS ).setParameterLength( 1 );
  8381. /**
  8382. * This type of node is a specialized version of `Object3DNode`
  8383. * with larger set of model related metrics. Unlike `Object3DNode`,
  8384. * `ModelNode` extracts the reference to the 3D object from the
  8385. * current node frame state.
  8386. *
  8387. * @augments Object3DNode
  8388. */
  8389. class ModelNode extends Object3DNode {
  8390. static get type() {
  8391. return 'ModelNode';
  8392. }
  8393. /**
  8394. * Constructs a new object model node.
  8395. *
  8396. * @param {('position'|'viewPosition'|'direction'|'scale'|'worldMatrix')} scope - The node represents a different type of transformation depending on the scope.
  8397. */
  8398. constructor( scope ) {
  8399. super( scope );
  8400. }
  8401. /**
  8402. * Extracts the model reference from the frame state and then
  8403. * updates the uniform value depending on the scope.
  8404. *
  8405. * @param {NodeFrame} frame - The current node frame.
  8406. */
  8407. update( frame ) {
  8408. this.object3d = frame.object;
  8409. super.update( frame );
  8410. }
  8411. }
  8412. /**
  8413. * TSL object that represents the object's direction in world space.
  8414. *
  8415. * @tsl
  8416. * @type {ModelNode<vec3>}
  8417. */
  8418. const modelDirection = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.DIRECTION );
  8419. /**
  8420. * TSL object that represents the object's world matrix.
  8421. *
  8422. * @tsl
  8423. * @type {ModelNode<mat4>}
  8424. */
  8425. const modelWorldMatrix = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.WORLD_MATRIX );
  8426. /**
  8427. * TSL object that represents the object's position in world space.
  8428. *
  8429. * @tsl
  8430. * @type {ModelNode<vec3>}
  8431. */
  8432. const modelPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.POSITION );
  8433. /**
  8434. * TSL object that represents the object's scale in world space.
  8435. *
  8436. * @tsl
  8437. * @type {ModelNode<vec3>}
  8438. */
  8439. const modelScale = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.SCALE );
  8440. /**
  8441. * TSL object that represents the object's position in view/camera space.
  8442. *
  8443. * @tsl
  8444. * @type {ModelNode<vec3>}
  8445. */
  8446. const modelViewPosition = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.VIEW_POSITION );
  8447. /**
  8448. * TSL object that represents the object's radius.
  8449. *
  8450. * @tsl
  8451. * @type {ModelNode<float>}
  8452. */
  8453. const modelRadius = /*@__PURE__*/ nodeImmutable( ModelNode, ModelNode.RADIUS );
  8454. /**
  8455. * TSL object that represents the object's normal matrix.
  8456. *
  8457. * @tsl
  8458. * @type {UniformNode<mat3>}
  8459. */
  8460. const modelNormalMatrix = /*@__PURE__*/ uniform( new Matrix3() ).onObjectUpdate( ( { object }, self ) => self.value.getNormalMatrix( object.matrixWorld ) );
  8461. /**
  8462. * TSL object that represents the object's inverse world matrix.
  8463. *
  8464. * @tsl
  8465. * @type {UniformNode<mat4>}
  8466. */
  8467. const modelWorldMatrixInverse = /*@__PURE__*/ uniform( new Matrix4() ).onObjectUpdate( ( { object }, self ) => self.value.copy( object.matrixWorld ).invert() );
  8468. /**
  8469. * TSL object that represents the object's model view matrix.
  8470. *
  8471. * @tsl
  8472. * @type {Node<mat4>}
  8473. */
  8474. const modelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8475. return builder.renderer.overrideNodes.modelViewMatrix || mediumpModelViewMatrix;
  8476. } ).once() )().toVar( 'modelViewMatrix' );
  8477. // GPU Precision
  8478. /**
  8479. * TSL object that represents the object's model view in `mediump` precision.
  8480. *
  8481. * @tsl
  8482. * @type {Node<mat4>}
  8483. */
  8484. const mediumpModelViewMatrix = /*@__PURE__*/ cameraViewMatrix.mul( modelWorldMatrix );
  8485. // CPU Precision
  8486. /**
  8487. * TSL object that represents the object's model view in `highp` precision
  8488. * which is achieved by computing the matrix in JS and not in the shader.
  8489. *
  8490. * @tsl
  8491. * @type {Node<mat4>}
  8492. */
  8493. const highpModelViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8494. builder.context.isHighPrecisionModelViewMatrix = true;
  8495. return uniform( 'mat4' ).onObjectUpdate( ( { object, camera } ) => {
  8496. return object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  8497. } );
  8498. } ).once() )().toVar( 'highpModelViewMatrix' );
  8499. /**
  8500. * TSL object that represents the object's model normal view in `highp` precision
  8501. * which is achieved by computing the matrix in JS and not in the shader.
  8502. *
  8503. * @tsl
  8504. * @type {Node<mat3>}
  8505. */
  8506. const highpModelNormalViewMatrix = /*@__PURE__*/ ( Fn( ( builder ) => {
  8507. const isHighPrecisionModelViewMatrix = builder.context.isHighPrecisionModelViewMatrix;
  8508. return uniform( 'mat3' ).onObjectUpdate( ( { object, camera } ) => {
  8509. if ( isHighPrecisionModelViewMatrix !== true ) {
  8510. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  8511. }
  8512. return object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  8513. } );
  8514. } ).once() )().toVar( 'highpModelNormalViewMatrix' );
  8515. /**
  8516. * TSL object that represents the position attribute of the current rendered object.
  8517. *
  8518. * @tsl
  8519. * @type {AttributeNode<vec3>}
  8520. */
  8521. const positionGeometry = /*@__PURE__*/ attribute( 'position', 'vec3' );
  8522. /**
  8523. * TSL object that represents the vertex position in local space of the current rendered object.
  8524. *
  8525. * @tsl
  8526. * @type {AttributeNode<vec3>}
  8527. */
  8528. const positionLocal = /*@__PURE__*/ positionGeometry.toVarying( 'positionLocal' );
  8529. /**
  8530. * TSL object that represents the previous vertex position in local space of the current rendered object.
  8531. * Used in context of {@link VelocityNode} for rendering motion vectors.
  8532. *
  8533. * @tsl
  8534. * @type {AttributeNode<vec3>}
  8535. */
  8536. const positionPrevious = /*@__PURE__*/ positionGeometry.toVarying( 'positionPrevious' );
  8537. /**
  8538. * TSL object that represents the vertex position in world space of the current rendered object.
  8539. *
  8540. * @tsl
  8541. * @type {VaryingNode<vec3>}
  8542. */
  8543. const positionWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  8544. return modelWorldMatrix.mul( positionLocal ).xyz.toVarying( builder.getNamespace( 'v_positionWorld' ) );
  8545. }, 'vec3' ).once( 'POSITION' ) )();
  8546. /**
  8547. * TSL object that represents the position world direction of the current rendered object.
  8548. *
  8549. * @tsl
  8550. * @type {Node<vec3>}
  8551. */
  8552. const positionWorldDirection = /*@__PURE__*/ ( Fn( ( builder ) => {
  8553. const vertexPWD = positionLocal.transformDirection( modelWorldMatrix ).toVarying( builder.getNamespace( 'v_positionWorldDirection' ) );
  8554. return vertexPWD.normalize().toVar( 'positionWorldDirection' );
  8555. }, 'vec3' ).once( 'POSITION' ) )();
  8556. /**
  8557. * TSL object that represents the vertex position in view space of the current rendered object.
  8558. *
  8559. * @tsl
  8560. * @type {VaryingNode<vec3>}
  8561. */
  8562. const positionView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8563. return builder.context.setupPositionView().toVarying( builder.getNamespace( 'v_positionView' ) );
  8564. }, 'vec3' ).once( 'POSITION' ) )();
  8565. /**
  8566. * TSL object that represents the position view direction of the current rendered object.
  8567. *
  8568. * @tsl
  8569. * @type {VaryingNode<vec3>}
  8570. */
  8571. const positionViewDirection = /*@__PURE__*/ positionView.negate().toVarying( 'v_positionViewDirection' ).normalize().toVar( 'positionViewDirection' );
  8572. /**
  8573. * This node can be used to evaluate whether a primitive is front or back facing.
  8574. *
  8575. * @augments Node
  8576. */
  8577. class FrontFacingNode extends Node {
  8578. static get type() {
  8579. return 'FrontFacingNode';
  8580. }
  8581. /**
  8582. * Constructs a new front facing node.
  8583. */
  8584. constructor() {
  8585. super( 'bool' );
  8586. /**
  8587. * This flag can be used for type testing.
  8588. *
  8589. * @type {boolean}
  8590. * @readonly
  8591. * @default true
  8592. */
  8593. this.isFrontFacingNode = true;
  8594. }
  8595. generate( builder ) {
  8596. const { renderer, material } = builder;
  8597. if ( renderer.coordinateSystem === WebGLCoordinateSystem ) {
  8598. if ( material.side === BackSide ) {
  8599. return 'false';
  8600. }
  8601. }
  8602. return builder.getFrontFacing();
  8603. }
  8604. }
  8605. /**
  8606. * TSL object that represents whether a primitive is front or back facing
  8607. *
  8608. * @tsl
  8609. * @type {FrontFacingNode<bool>}
  8610. */
  8611. const frontFacing = /*@__PURE__*/ nodeImmutable( FrontFacingNode );
  8612. /**
  8613. * TSL object that represents the front facing status as a number instead of a bool.
  8614. * `1` means front facing, `-1` means back facing.
  8615. *
  8616. * @tsl
  8617. * @type {Node<float>}
  8618. */
  8619. const faceDirection = /*@__PURE__*/ float( frontFacing ).mul( 2.0 ).sub( 1.0 );
  8620. /**
  8621. * TSL object that represents the normal attribute of the current rendered object.
  8622. *
  8623. * @tsl
  8624. * @type {Node<vec3>}
  8625. */
  8626. const normalGeometry = /*@__PURE__*/ attribute( 'normal', 'vec3' );
  8627. /**
  8628. * TSL object that represents the vertex normal in local space of the current rendered object.
  8629. *
  8630. * @tsl
  8631. * @type {Node<vec3>}
  8632. */
  8633. const normalLocal = /*@__PURE__*/ ( Fn( ( builder ) => {
  8634. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  8635. console.warn( 'THREE.TSL: Vertex attribute "normal" not found on geometry.' );
  8636. return vec3( 0, 1, 0 );
  8637. }
  8638. return normalGeometry;
  8639. }, 'vec3' ).once() )().toVar( 'normalLocal' );
  8640. /**
  8641. * TSL object that represents the flat vertex normal in view space of the current rendered object.
  8642. *
  8643. * @tsl
  8644. * @type {Node<vec3>}
  8645. */
  8646. const normalFlat = /*@__PURE__*/ positionView.dFdx().cross( positionView.dFdy() ).normalize().toVar( 'normalFlat' );
  8647. /**
  8648. * TSL object that represents the vertex normal in view space of the current rendered object.
  8649. *
  8650. * @tsl
  8651. * @type {Node<vec3>}
  8652. */
  8653. const normalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8654. let node;
  8655. if ( builder.material.flatShading === true ) {
  8656. node = normalFlat;
  8657. } else {
  8658. node = varying( transformNormalToView( normalLocal ), 'v_normalView' ).normalize();
  8659. }
  8660. return node;
  8661. }, 'vec3' ).once() )().toVar( 'normalView' );
  8662. /**
  8663. * TSL object that represents the vertex normal in world space of the current rendered object.
  8664. *
  8665. * @tsl
  8666. * @type {Node<vec3>}
  8667. */
  8668. const normalWorld = /*@__PURE__*/ ( Fn( ( builder ) => {
  8669. let normal = normalView.transformDirection( cameraViewMatrix );
  8670. if ( builder.material.flatShading !== true ) {
  8671. normal = varying( normal, 'v_normalWorld' );
  8672. }
  8673. return normal;
  8674. }, 'vec3' ).once() )().normalize().toVar( 'normalWorld' );
  8675. /**
  8676. * TSL object that represents the transformed vertex normal in view space of the current rendered object.
  8677. *
  8678. * @tsl
  8679. * @type {Node<vec3>}
  8680. */
  8681. const transformedNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8682. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8683. let node = builder.context.setupNormal().context( { getUV: null } );
  8684. if ( builder.material.flatShading !== true ) node = node.mul( faceDirection );
  8685. return node;
  8686. }, 'vec3' ).once() )().toVar( 'transformedNormalView' );
  8687. /**
  8688. * TSL object that represents the transformed vertex normal in world space of the current rendered object.
  8689. *
  8690. * @tsl
  8691. * @type {Node<vec3>}
  8692. */
  8693. const transformedNormalWorld = /*@__PURE__*/ transformedNormalView.transformDirection( cameraViewMatrix ).toVar( 'transformedNormalWorld' );
  8694. /**
  8695. * TSL object that represents the transformed clearcoat vertex normal in view space of the current rendered object.
  8696. *
  8697. * @tsl
  8698. * @type {Node<vec3>}
  8699. */
  8700. const transformedClearcoatNormalView = /*@__PURE__*/ ( Fn( ( builder ) => {
  8701. // Use getUV context to avoid side effects from nodes overwriting getUV in the context (e.g. EnvironmentNode)
  8702. let node = builder.context.setupClearcoatNormal().context( { getUV: null } );
  8703. if ( builder.material.flatShading !== true ) node = node.mul( faceDirection );
  8704. return node;
  8705. }, 'vec3' ).once() )().toVar( 'transformedClearcoatNormalView' );
  8706. /**
  8707. * Transforms the normal with the given matrix.
  8708. *
  8709. * @tsl
  8710. * @function
  8711. * @param {Node<vec3>} normal - The normal.
  8712. * @param {Node<mat3>} [matrix=modelWorldMatrix] - The matrix.
  8713. * @return {Node<vec3>} The transformed normal.
  8714. */
  8715. const transformNormal = /*@__PURE__*/ Fn( ( [ normal, matrix = modelWorldMatrix ] ) => {
  8716. const m = mat3( matrix );
  8717. const transformedNormal = normal.div( vec3( m[ 0 ].dot( m[ 0 ] ), m[ 1 ].dot( m[ 1 ] ), m[ 2 ].dot( m[ 2 ] ) ) );
  8718. return m.mul( transformedNormal ).xyz;
  8719. } );
  8720. /**
  8721. * Transforms the given normal from local to view space.
  8722. *
  8723. * @tsl
  8724. * @function
  8725. * @param {Node<vec3>} normal - The normal.
  8726. * @param {NodeBuilder} builder - The current node builder.
  8727. * @return {Node<vec3>} The transformed normal.
  8728. */
  8729. const transformNormalToView = /*@__PURE__*/ Fn( ( [ normal ], builder ) => {
  8730. const modelNormalViewMatrix = builder.renderer.overrideNodes.modelNormalViewMatrix;
  8731. if ( modelNormalViewMatrix !== null ) {
  8732. return modelNormalViewMatrix.transformDirection( normal );
  8733. }
  8734. //
  8735. const transformedNormal = modelNormalMatrix.mul( normal );
  8736. return cameraViewMatrix.transformDirection( transformedNormal );
  8737. } );
  8738. const _e1$1 = /*@__PURE__*/ new Euler();
  8739. const _m1$1 = /*@__PURE__*/ new Matrix4();
  8740. /**
  8741. * TSL object that represents the refraction ratio of the material used for rendering the current object.
  8742. *
  8743. * @tsl
  8744. * @type {UniformNode<float>}
  8745. */
  8746. const materialRefractionRatio = /*@__PURE__*/ uniform( 0 ).onReference( ( { material } ) => material ).onObjectUpdate( ( { material } ) => material.refractionRatio );
  8747. /**
  8748. * TSL object that represents the intensity of environment maps of PBR materials.
  8749. * When `material.envMap` is set, the value is `material.envMapIntensity` otherwise `scene.environmentIntensity`.
  8750. *
  8751. * @tsl
  8752. * @type {Node<float>}
  8753. */
  8754. const materialEnvIntensity = /*@__PURE__*/ uniform( 1 ).onReference( ( { material } ) => material ).onObjectUpdate( function ( { material, scene } ) {
  8755. return material.envMap ? material.envMapIntensity : scene.environmentIntensity;
  8756. } );
  8757. /**
  8758. * TSL object that represents the rotation of environment maps.
  8759. * When `material.envMap` is set, the value is `material.envMapRotation`. `scene.environmentRotation` controls the
  8760. * rotation of `scene.environment` instead.
  8761. *
  8762. * @tsl
  8763. * @type {Node<mat4>}
  8764. */
  8765. const materialEnvRotation = /*@__PURE__*/ uniform( new Matrix4() ).onReference( function ( frame ) {
  8766. return frame.material;
  8767. } ).onObjectUpdate( function ( { material, scene } ) {
  8768. const rotation = ( scene.environment !== null && material.envMap === null ) ? scene.environmentRotation : material.envMapRotation;
  8769. if ( rotation ) {
  8770. _e1$1.copy( rotation );
  8771. _m1$1.makeRotationFromEuler( _e1$1 );
  8772. } else {
  8773. _m1$1.identity();
  8774. }
  8775. return _m1$1;
  8776. } );
  8777. /**
  8778. * The reflect vector in view space.
  8779. *
  8780. * @tsl
  8781. * @type {Node<vec3>}
  8782. */
  8783. const reflectView = /*@__PURE__*/ positionViewDirection.negate().reflect( transformedNormalView );
  8784. /**
  8785. * The refract vector in view space.
  8786. *
  8787. * @tsl
  8788. * @type {Node<vec3>}
  8789. */
  8790. const refractView = /*@__PURE__*/ positionViewDirection.negate().refract( transformedNormalView, materialRefractionRatio );
  8791. /**
  8792. * Used for sampling cube maps when using cube reflection mapping.
  8793. *
  8794. * @tsl
  8795. * @type {Node<vec3>}
  8796. */
  8797. const reflectVector = /*@__PURE__*/ reflectView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8798. /**
  8799. * Used for sampling cube maps when using cube refraction mapping.
  8800. *
  8801. * @tsl
  8802. * @type {Node<vec3>}
  8803. */
  8804. const refractVector = /*@__PURE__*/ refractView.transformDirection( cameraViewMatrix ).toVar( 'reflectVector' );
  8805. const EmptyTexture = /*@__PURE__*/ new CubeTexture();
  8806. /**
  8807. * This type of uniform node represents a cube texture.
  8808. *
  8809. * @augments TextureNode
  8810. */
  8811. class CubeTextureNode extends TextureNode {
  8812. static get type() {
  8813. return 'CubeTextureNode';
  8814. }
  8815. /**
  8816. * Constructs a new cube texture node.
  8817. *
  8818. * @param {CubeTexture} value - The cube texture.
  8819. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8820. * @param {?Node<int>} [levelNode=null] - The level node.
  8821. * @param {?Node<float>} [biasNode=null] - The bias node.
  8822. */
  8823. constructor( value, uvNode = null, levelNode = null, biasNode = null ) {
  8824. super( value, uvNode, levelNode, biasNode );
  8825. /**
  8826. * This flag can be used for type testing.
  8827. *
  8828. * @type {boolean}
  8829. * @readonly
  8830. * @default true
  8831. */
  8832. this.isCubeTextureNode = true;
  8833. }
  8834. /**
  8835. * Overwrites the default implementation to return a fixed value `'cubeTexture'`.
  8836. *
  8837. * @param {NodeBuilder} builder - The current node builder.
  8838. * @return {string} The input type.
  8839. */
  8840. getInputType( /*builder*/ ) {
  8841. return 'cubeTexture';
  8842. }
  8843. /**
  8844. * Returns a default uvs based on the mapping type of the cube texture.
  8845. *
  8846. * @return {Node<vec3>} The default uv attribute.
  8847. */
  8848. getDefaultUV() {
  8849. const texture = this.value;
  8850. if ( texture.mapping === CubeReflectionMapping ) {
  8851. return reflectVector;
  8852. } else if ( texture.mapping === CubeRefractionMapping ) {
  8853. return refractVector;
  8854. } else {
  8855. console.error( 'THREE.CubeTextureNode: Mapping "%s" not supported.', texture.mapping );
  8856. return vec3( 0, 0, 0 );
  8857. }
  8858. }
  8859. /**
  8860. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  8861. * for cube textures. The uv transformation matrix is not applied to cube textures.
  8862. *
  8863. * @param {boolean} value - The update toggle.
  8864. */
  8865. setUpdateMatrix( /*updateMatrix*/ ) { } // Ignore .updateMatrix for CubeTextureNode
  8866. /**
  8867. * Setups the uv node. Depending on the backend as well as the texture type, it might be necessary
  8868. * to modify the uv node for correct sampling.
  8869. *
  8870. * @param {NodeBuilder} builder - The current node builder.
  8871. * @param {Node} uvNode - The uv node to setup.
  8872. * @return {Node} The updated uv node.
  8873. */
  8874. setupUV( builder, uvNode ) {
  8875. const texture = this.value;
  8876. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem || ! texture.isRenderTargetTexture ) {
  8877. uvNode = vec3( uvNode.x.negate(), uvNode.yz );
  8878. }
  8879. return materialEnvRotation.mul( uvNode );
  8880. }
  8881. /**
  8882. * Generates the uv code snippet.
  8883. *
  8884. * @param {NodeBuilder} builder - The current node builder.
  8885. * @param {Node} cubeUV - The uv node to generate code for.
  8886. * @return {string} The generated code snippet.
  8887. */
  8888. generateUV( builder, cubeUV ) {
  8889. return cubeUV.build( builder, 'vec3' );
  8890. }
  8891. }
  8892. /**
  8893. * TSL function for creating a cube texture node.
  8894. *
  8895. * @tsl
  8896. * @function
  8897. * @param {CubeTexture} value - The cube texture.
  8898. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8899. * @param {?Node<int>} [levelNode=null] - The level node.
  8900. * @param {?Node<float>} [biasNode=null] - The bias node.
  8901. * @returns {CubeTextureNode}
  8902. */
  8903. const cubeTextureBase = /*@__PURE__*/ nodeProxy( CubeTextureNode ).setParameterLength( 1, 4 ).setName( 'cubeTexture' );
  8904. /**
  8905. * TSL function for creating a cube texture uniform node.
  8906. *
  8907. * @tsl
  8908. * @function
  8909. * @param {?CubeTexture|CubeTextureNode} [value=EmptyTexture] - The cube texture.
  8910. * @param {?Node<vec3>} [uvNode=null] - The uv node.
  8911. * @param {?Node<int>} [levelNode=null] - The level node.
  8912. * @param {?Node<float>} [biasNode=null] - The bias node.
  8913. * @returns {CubeTextureNode}
  8914. */
  8915. const cubeTexture = ( value = EmptyTexture, uvNode = null, levelNode = null, biasNode = null ) => {
  8916. let textureNode;
  8917. if ( value && value.isCubeTextureNode === true ) {
  8918. textureNode = nodeObject( value.clone() );
  8919. textureNode.referenceNode = value.getSelf(); // Ensure the reference is set to the original node
  8920. if ( uvNode !== null ) textureNode.uvNode = nodeObject( uvNode );
  8921. if ( levelNode !== null ) textureNode.levelNode = nodeObject( levelNode );
  8922. if ( biasNode !== null ) textureNode.biasNode = nodeObject( biasNode );
  8923. } else {
  8924. textureNode = cubeTextureBase( value, uvNode, levelNode, biasNode );
  8925. }
  8926. return textureNode;
  8927. };
  8928. /**
  8929. * TSL function for creating a uniform cube texture node.
  8930. *
  8931. * @tsl
  8932. * @function
  8933. * @param {?CubeTexture} [value=EmptyTexture] - The cube texture.
  8934. * @returns {CubeTextureNode}
  8935. */
  8936. const uniformCubeTexture = ( value = EmptyTexture ) => cubeTextureBase( value );
  8937. // TODO: Avoid duplicated code and ues only ReferenceBaseNode or ReferenceNode
  8938. /**
  8939. * This class is only relevant if the referenced property is array-like.
  8940. * In this case, `ReferenceElementNode` allows to refer to a specific
  8941. * element inside the data structure via an index.
  8942. *
  8943. * @augments ArrayElementNode
  8944. */
  8945. class ReferenceElementNode extends ArrayElementNode {
  8946. static get type() {
  8947. return 'ReferenceElementNode';
  8948. }
  8949. /**
  8950. * Constructs a new reference element node.
  8951. *
  8952. * @param {?ReferenceNode} referenceNode - The reference node.
  8953. * @param {Node} indexNode - The index node that defines the element access.
  8954. */
  8955. constructor( referenceNode, indexNode ) {
  8956. super( referenceNode, indexNode );
  8957. /**
  8958. * Similar to {@link ReferenceNode#reference}, an additional
  8959. * property references to the current node.
  8960. *
  8961. * @type {?ReferenceNode}
  8962. * @default null
  8963. */
  8964. this.referenceNode = referenceNode;
  8965. /**
  8966. * This flag can be used for type testing.
  8967. *
  8968. * @type {boolean}
  8969. * @readonly
  8970. * @default true
  8971. */
  8972. this.isReferenceElementNode = true;
  8973. }
  8974. /**
  8975. * This method is overwritten since the node type is inferred from
  8976. * the uniform type of the reference node.
  8977. *
  8978. * @return {string} The node type.
  8979. */
  8980. getNodeType() {
  8981. return this.referenceNode.uniformType;
  8982. }
  8983. generate( builder ) {
  8984. const snippet = super.generate( builder );
  8985. const arrayType = this.referenceNode.getNodeType();
  8986. const elementType = this.getNodeType();
  8987. return builder.format( snippet, arrayType, elementType );
  8988. }
  8989. }
  8990. /**
  8991. * This type of node establishes a reference to a property of another object.
  8992. * In this way, the value of the node is automatically linked to the value of
  8993. * referenced object. Reference nodes internally represent the linked value
  8994. * as a uniform.
  8995. *
  8996. * @augments Node
  8997. */
  8998. class ReferenceNode extends Node {
  8999. static get type() {
  9000. return 'ReferenceNode';
  9001. }
  9002. /**
  9003. * Constructs a new reference node.
  9004. *
  9005. * @param {string} property - The name of the property the node refers to.
  9006. * @param {string} uniformType - The uniform type that should be used to represent the property value.
  9007. * @param {?Object} [object=null] - The object the property belongs to.
  9008. * @param {?number} [count=null] - When the linked property is an array-like, this parameter defines its length.
  9009. */
  9010. constructor( property, uniformType, object = null, count = null ) {
  9011. super();
  9012. /**
  9013. * The name of the property the node refers to.
  9014. *
  9015. * @type {string}
  9016. */
  9017. this.property = property;
  9018. /**
  9019. * The uniform type that should be used to represent the property value.
  9020. *
  9021. * @type {string}
  9022. */
  9023. this.uniformType = uniformType;
  9024. /**
  9025. * The object the property belongs to.
  9026. *
  9027. * @type {?Object}
  9028. * @default null
  9029. */
  9030. this.object = object;
  9031. /**
  9032. * When the linked property is an array, this parameter defines its length.
  9033. *
  9034. * @type {?number}
  9035. * @default null
  9036. */
  9037. this.count = count;
  9038. /**
  9039. * The property name might have dots so nested properties can be referred.
  9040. * The hierarchy of the names is stored inside this array.
  9041. *
  9042. * @type {Array<string>}
  9043. */
  9044. this.properties = property.split( '.' );
  9045. /**
  9046. * Points to the current referred object. This property exists next to {@link ReferenceNode#object}
  9047. * since the final reference might be updated from calling code.
  9048. *
  9049. * @type {?Object}
  9050. * @default null
  9051. */
  9052. this.reference = object;
  9053. /**
  9054. * The uniform node that holds the value of the reference node.
  9055. *
  9056. * @type {UniformNode}
  9057. * @default null
  9058. */
  9059. this.node = null;
  9060. /**
  9061. * The uniform group of the internal uniform.
  9062. *
  9063. * @type {UniformGroupNode}
  9064. * @default null
  9065. */
  9066. this.group = null;
  9067. /**
  9068. * An optional label of the internal uniform node.
  9069. *
  9070. * @type {?string}
  9071. * @default null
  9072. */
  9073. this.name = null;
  9074. /**
  9075. * Overwritten since reference nodes are updated per object.
  9076. *
  9077. * @type {string}
  9078. * @default 'object'
  9079. */
  9080. this.updateType = NodeUpdateType.OBJECT;
  9081. }
  9082. /**
  9083. * When the referred property is array-like, this method can be used
  9084. * to access elements via an index node.
  9085. *
  9086. * @param {IndexNode} indexNode - indexNode.
  9087. * @return {ReferenceElementNode} A reference to an element.
  9088. */
  9089. element( indexNode ) {
  9090. return nodeObject( new ReferenceElementNode( this, nodeObject( indexNode ) ) );
  9091. }
  9092. /**
  9093. * Sets the uniform group for this reference node.
  9094. *
  9095. * @param {UniformGroupNode} group - The uniform group to set.
  9096. * @return {ReferenceNode} A reference to this node.
  9097. */
  9098. setGroup( group ) {
  9099. this.group = group;
  9100. return this;
  9101. }
  9102. /**
  9103. * Sets the label for the internal uniform.
  9104. *
  9105. * @param {string} name - The label to set.
  9106. * @return {ReferenceNode} A reference to this node.
  9107. */
  9108. label( name ) {
  9109. this.name = name;
  9110. return this;
  9111. }
  9112. /**
  9113. * Sets the node type which automatically defines the internal
  9114. * uniform type.
  9115. *
  9116. * @param {string} uniformType - The type to set.
  9117. */
  9118. setNodeType( uniformType ) {
  9119. let node = null;
  9120. if ( this.count !== null ) {
  9121. node = buffer( null, uniformType, this.count );
  9122. } else if ( Array.isArray( this.getValueFromReference() ) ) {
  9123. node = uniformArray( null, uniformType );
  9124. } else if ( uniformType === 'texture' ) {
  9125. node = texture( null );
  9126. } else if ( uniformType === 'cubeTexture' ) {
  9127. node = cubeTexture( null );
  9128. } else {
  9129. node = uniform( null, uniformType );
  9130. }
  9131. if ( this.group !== null ) {
  9132. node.setGroup( this.group );
  9133. }
  9134. if ( this.name !== null ) node.label( this.name );
  9135. this.node = node.getSelf();
  9136. }
  9137. /**
  9138. * This method is overwritten since the node type is inferred from
  9139. * the type of the reference node.
  9140. *
  9141. * @param {NodeBuilder} builder - The current node builder.
  9142. * @return {string} The node type.
  9143. */
  9144. getNodeType( builder ) {
  9145. if ( this.node === null ) {
  9146. this.updateReference( builder );
  9147. this.updateValue();
  9148. }
  9149. return this.node.getNodeType( builder );
  9150. }
  9151. /**
  9152. * Returns the property value from the given referred object.
  9153. *
  9154. * @param {Object} [object=this.reference] - The object to retrieve the property value from.
  9155. * @return {any} The value.
  9156. */
  9157. getValueFromReference( object = this.reference ) {
  9158. const { properties } = this;
  9159. let value = object[ properties[ 0 ] ];
  9160. for ( let i = 1; i < properties.length; i ++ ) {
  9161. value = value[ properties[ i ] ];
  9162. }
  9163. return value;
  9164. }
  9165. /**
  9166. * Allows to update the reference based on the given state. The state is only
  9167. * evaluated {@link ReferenceNode#object} is not set.
  9168. *
  9169. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9170. * @return {Object} The updated reference.
  9171. */
  9172. updateReference( state ) {
  9173. this.reference = this.object !== null ? this.object : state.object;
  9174. return this.reference;
  9175. }
  9176. /**
  9177. * The output of the reference node is the internal uniform node.
  9178. *
  9179. * @param {NodeBuilder} builder - The current node builder.
  9180. * @return {UniformNode} The output node.
  9181. */
  9182. setup( /* builder */ ) {
  9183. this.updateValue();
  9184. return this.node;
  9185. }
  9186. /**
  9187. * Overwritten to update the internal uniform value.
  9188. *
  9189. * @param {NodeFrame} frame - A reference to the current node frame.
  9190. */
  9191. update( /*frame*/ ) {
  9192. this.updateValue();
  9193. }
  9194. /**
  9195. * Retrieves the value from the referred object property and uses it
  9196. * to updated the internal uniform.
  9197. */
  9198. updateValue() {
  9199. if ( this.node === null ) this.setNodeType( this.uniformType );
  9200. const value = this.getValueFromReference();
  9201. if ( Array.isArray( value ) ) {
  9202. this.node.array = value;
  9203. } else {
  9204. this.node.value = value;
  9205. }
  9206. }
  9207. }
  9208. /**
  9209. * TSL function for creating a reference node.
  9210. *
  9211. * @tsl
  9212. * @function
  9213. * @param {string} name - The name of the property the node refers to.
  9214. * @param {string} type - The uniform type that should be used to represent the property value.
  9215. * @param {?Object} [object] - The object the property belongs to.
  9216. * @returns {ReferenceNode}
  9217. */
  9218. const reference = ( name, type, object ) => nodeObject( new ReferenceNode( name, type, object ) );
  9219. /**
  9220. * TSL function for creating a reference node. Use this function if you want need a reference
  9221. * to an array-like property that should be represented as a uniform buffer.
  9222. *
  9223. * @tsl
  9224. * @function
  9225. * @param {string} name - The name of the property the node refers to.
  9226. * @param {string} type - The uniform type that should be used to represent the property value.
  9227. * @param {number} count - The number of value inside the array-like object.
  9228. * @param {Object} object - An array-like object the property belongs to.
  9229. * @returns {ReferenceNode}
  9230. */
  9231. const referenceBuffer = ( name, type, count, object ) => nodeObject( new ReferenceNode( name, type, object, count ) );
  9232. /**
  9233. * This node is a special type of reference node which is intended
  9234. * for linking material properties with node values.
  9235. * ```js
  9236. * const opacityNode = materialReference( 'opacity', 'float', material );
  9237. * ```
  9238. * When changing `material.opacity`, the node value of `opacityNode` will
  9239. * automatically be updated.
  9240. *
  9241. * @augments ReferenceNode
  9242. */
  9243. class MaterialReferenceNode extends ReferenceNode {
  9244. static get type() {
  9245. return 'MaterialReferenceNode';
  9246. }
  9247. /**
  9248. * Constructs a new material reference node.
  9249. *
  9250. * @param {string} property - The name of the property the node refers to.
  9251. * @param {string} inputType - The uniform type that should be used to represent the property value.
  9252. * @param {?Material} [material=null] - The material the property belongs to. When no material is set,
  9253. * the node refers to the material of the current rendered object.
  9254. */
  9255. constructor( property, inputType, material = null ) {
  9256. super( property, inputType, material );
  9257. /**
  9258. * The material the property belongs to. When no material is set,
  9259. * the node refers to the material of the current rendered object.
  9260. *
  9261. * @type {?Material}
  9262. * @default null
  9263. */
  9264. this.material = material;
  9265. /**
  9266. * This flag can be used for type testing.
  9267. *
  9268. * @type {boolean}
  9269. * @readonly
  9270. * @default true
  9271. */
  9272. this.isMaterialReferenceNode = true;
  9273. }
  9274. /**
  9275. * Updates the reference based on the given state. The state is only evaluated
  9276. * {@link MaterialReferenceNode#material} is not set.
  9277. *
  9278. * @param {(NodeFrame|NodeBuilder)} state - The current state.
  9279. * @return {Object} The updated reference.
  9280. */
  9281. updateReference( state ) {
  9282. this.reference = this.material !== null ? this.material : state.material;
  9283. return this.reference;
  9284. }
  9285. }
  9286. /**
  9287. * TSL function for creating a material reference node.
  9288. *
  9289. * @tsl
  9290. * @function
  9291. * @param {string} name - The name of the property the node refers to.
  9292. * @param {string} type - The uniform type that should be used to represent the property value.
  9293. * @param {?Material} [material=null] - The material the property belongs to.
  9294. * When no material is set, the node refers to the material of the current rendered object.
  9295. * @returns {MaterialReferenceNode}
  9296. */
  9297. const materialReference = ( name, type, material = null ) => nodeObject( new MaterialReferenceNode( name, type, material ) );
  9298. /**
  9299. * TSL object that represents the tangent attribute of the current rendered object.
  9300. *
  9301. * @tsl
  9302. * @type {Node<vec4>}
  9303. */
  9304. const tangentGeometry = /*@__PURE__*/ Fn( ( builder ) => {
  9305. if ( builder.geometry.hasAttribute( 'tangent' ) === false ) {
  9306. builder.geometry.computeTangents();
  9307. }
  9308. return attribute( 'tangent', 'vec4' );
  9309. } )();
  9310. /**
  9311. * TSL object that represents the vertex tangent in local space of the current rendered object.
  9312. *
  9313. * @tsl
  9314. * @type {Node<vec3>}
  9315. */
  9316. const tangentLocal = /*@__PURE__*/ tangentGeometry.xyz.toVar( 'tangentLocal' );
  9317. /**
  9318. * TSL object that represents the vertex tangent in view space of the current rendered object.
  9319. *
  9320. * @tsl
  9321. * @type {Node<vec3>}
  9322. */
  9323. const tangentView = /*@__PURE__*/ modelViewMatrix.mul( vec4( tangentLocal, 0 ) ).xyz.toVarying( 'v_tangentView' ).normalize().toVar( 'tangentView' );
  9324. /**
  9325. * TSL object that represents the vertex tangent in world space of the current rendered object.
  9326. *
  9327. * @tsl
  9328. * @type {Node<vec3>}
  9329. */
  9330. const tangentWorld = /*@__PURE__*/ tangentView.transformDirection( cameraViewMatrix ).toVarying( 'v_tangentWorld' ).normalize().toVar( 'tangentWorld' );
  9331. /**
  9332. * TSL object that represents the transformed vertex tangent in view space of the current rendered object.
  9333. *
  9334. * @tsl
  9335. * @type {Node<vec3>}
  9336. */
  9337. const transformedTangentView = /*@__PURE__*/ tangentView.toVar( 'transformedTangentView' );
  9338. /**
  9339. * TSL object that represents the transformed vertex tangent in world space of the current rendered object.
  9340. *
  9341. * @tsl
  9342. * @type {Node<vec3>}
  9343. */
  9344. const transformedTangentWorld = /*@__PURE__*/ transformedTangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedTangentWorld' );
  9345. /**
  9346. * Returns the bitangent node and assigns it to a varying if the material is not flat shaded.
  9347. *
  9348. * @tsl
  9349. * @private
  9350. * @param {Node<vec3>} crossNormalTangent - The cross product of the normal and tangent vectors.
  9351. * @param {string} varyingName - The name of the varying to assign the bitangent to.
  9352. * @returns {Node<vec3>} The bitangent node.
  9353. */
  9354. const getBitangent = /*@__PURE__*/ Fn( ( [ crossNormalTangent, varyingName ], builder ) => {
  9355. let bitangent = crossNormalTangent.mul( tangentGeometry.w ).xyz;
  9356. if ( builder.material.flatShading !== true ) {
  9357. bitangent = varying( bitangent, varyingName );
  9358. }
  9359. return bitangent;
  9360. } ).once();
  9361. /**
  9362. * TSL object that represents the bitangent attribute of the current rendered object.
  9363. *
  9364. * @tsl
  9365. * @type {Node<vec3>}
  9366. */
  9367. const bitangentGeometry = /*@__PURE__*/ getBitangent( normalGeometry.cross( tangentGeometry ), 'v_bitangentGeometry' ).normalize().toVar( 'bitangentGeometry' );
  9368. /**
  9369. * TSL object that represents the vertex bitangent in local space of the current rendered object.
  9370. *
  9371. * @tsl
  9372. * @type {Node<vec3>}
  9373. */
  9374. const bitangentLocal = /*@__PURE__*/ getBitangent( normalLocal.cross( tangentLocal ), 'v_bitangentLocal' ).normalize().toVar( 'bitangentLocal' );
  9375. /**
  9376. * TSL object that represents the vertex bitangent in view space of the current rendered object.
  9377. *
  9378. * @tsl
  9379. * @type {Node<vec3>}
  9380. */
  9381. const bitangentView = getBitangent( normalView.cross( tangentView ), 'v_bitangentView' ).normalize().toVar( 'bitangentView' );
  9382. /**
  9383. * TSL object that represents the vertex bitangent in world space of the current rendered object.
  9384. *
  9385. * @tsl
  9386. * @type {Node<vec3>}
  9387. */
  9388. const bitangentWorld = /*@__PURE__*/ getBitangent( normalWorld.cross( tangentWorld ), 'v_bitangentWorld' ).normalize().toVar( 'bitangentWorld' );
  9389. /**
  9390. * TSL object that represents the transformed vertex bitangent in view space of the current rendered object.
  9391. *
  9392. * @tsl
  9393. * @type {Node<vec3>}
  9394. */
  9395. const transformedBitangentView = /*@__PURE__*/ getBitangent( transformedNormalView.cross( transformedTangentView ), 'v_transformedBitangentView' ).normalize().toVar( 'transformedBitangentView' );
  9396. /**
  9397. * TSL object that represents the transformed vertex bitangent in world space of the current rendered object.
  9398. *
  9399. * @tsl
  9400. * @type {Node<vec4>}
  9401. */
  9402. const transformedBitangentWorld = /*@__PURE__*/ transformedBitangentView.transformDirection( cameraViewMatrix ).normalize().toVar( 'transformedBitangentWorld' );
  9403. /**
  9404. * TSL object that represents the TBN matrix in view space.
  9405. *
  9406. * @tsl
  9407. * @type {Node<mat3>}
  9408. */
  9409. const TBNViewMatrix = /*@__PURE__*/ mat3( tangentView, bitangentView, normalView );
  9410. /**
  9411. * TSL object that represents the parallax direction.
  9412. *
  9413. * @tsl
  9414. * @type {Node<mat3>}
  9415. */
  9416. const parallaxDirection = /*@__PURE__*/ positionViewDirection.mul( TBNViewMatrix )/*.normalize()*/;
  9417. /**
  9418. * TSL function for computing parallax uv coordinates.
  9419. *
  9420. * @tsl
  9421. * @function
  9422. * @param {Node<vec2>} uv - A uv node.
  9423. * @param {Node<vec2>} scale - A scale node.
  9424. * @returns {Node<vec2>} Parallax uv coordinates.
  9425. */
  9426. const parallaxUV = ( uv, scale ) => uv.sub( parallaxDirection.mul( scale ) );
  9427. /**
  9428. * TSL function for computing bent normals.
  9429. *
  9430. * @tsl
  9431. * @function
  9432. * @returns {Node<vec3>} Bent normals.
  9433. */
  9434. const transformedBentNormalView = /*@__PURE__*/ ( () => {
  9435. // https://google.github.io/filament/Filament.md.html#lighting/imagebasedlights/anisotropy
  9436. let bentNormal = anisotropyB.cross( positionViewDirection );
  9437. bentNormal = bentNormal.cross( anisotropyB ).normalize();
  9438. bentNormal = mix( bentNormal, transformedNormalView, anisotropy.mul( roughness.oneMinus() ).oneMinus().pow2().pow2() ).normalize();
  9439. return bentNormal;
  9440. } )();
  9441. // Normal Mapping Without Precomputed Tangents
  9442. // http://www.thetenthplanet.de/archives/1180
  9443. const perturbNormal2Arb = /*@__PURE__*/ Fn( ( inputs ) => {
  9444. const { eye_pos, surf_norm, mapN, uv } = inputs;
  9445. const q0 = eye_pos.dFdx();
  9446. const q1 = eye_pos.dFdy();
  9447. const st0 = uv.dFdx();
  9448. const st1 = uv.dFdy();
  9449. const N = surf_norm; // normalized
  9450. const q1perp = q1.cross( N );
  9451. const q0perp = N.cross( q0 );
  9452. const T = q1perp.mul( st0.x ).add( q0perp.mul( st1.x ) );
  9453. const B = q1perp.mul( st0.y ).add( q0perp.mul( st1.y ) );
  9454. const det = T.dot( T ).max( B.dot( B ) );
  9455. const scale = faceDirection.mul( det.inverseSqrt() );
  9456. return add( T.mul( mapN.x, scale ), B.mul( mapN.y, scale ), N.mul( mapN.z ) ).normalize();
  9457. } );
  9458. /**
  9459. * This class can be used for applying normals maps to materials.
  9460. *
  9461. * ```js
  9462. * material.normalNode = normalMap( texture( normalTex ) );
  9463. * ```
  9464. *
  9465. * @augments TempNode
  9466. */
  9467. class NormalMapNode extends TempNode {
  9468. static get type() {
  9469. return 'NormalMapNode';
  9470. }
  9471. /**
  9472. * Constructs a new normal map node.
  9473. *
  9474. * @param {Node<vec3>} node - Represents the normal map data.
  9475. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  9476. */
  9477. constructor( node, scaleNode = null ) {
  9478. super( 'vec3' );
  9479. /**
  9480. * Represents the normal map data.
  9481. *
  9482. * @type {Node<vec3>}
  9483. */
  9484. this.node = node;
  9485. /**
  9486. * Controls the intensity of the effect.
  9487. *
  9488. * @type {?Node<vec2>}
  9489. * @default null
  9490. */
  9491. this.scaleNode = scaleNode;
  9492. /**
  9493. * The normal map type.
  9494. *
  9495. * @type {(TangentSpaceNormalMap|ObjectSpaceNormalMap)}
  9496. * @default TangentSpaceNormalMap
  9497. */
  9498. this.normalMapType = TangentSpaceNormalMap;
  9499. }
  9500. setup( builder ) {
  9501. const { normalMapType, scaleNode } = this;
  9502. let normalMap = this.node.mul( 2.0 ).sub( 1.0 );
  9503. if ( scaleNode !== null ) {
  9504. normalMap = vec3( normalMap.xy.mul( scaleNode ), normalMap.z );
  9505. }
  9506. let outputNode = null;
  9507. if ( normalMapType === ObjectSpaceNormalMap ) {
  9508. outputNode = transformNormalToView( normalMap );
  9509. } else if ( normalMapType === TangentSpaceNormalMap ) {
  9510. const tangent = builder.hasGeometryAttribute( 'tangent' );
  9511. if ( tangent === true ) {
  9512. outputNode = TBNViewMatrix.mul( normalMap ).normalize();
  9513. } else {
  9514. outputNode = perturbNormal2Arb( {
  9515. eye_pos: positionView,
  9516. surf_norm: normalView,
  9517. mapN: normalMap,
  9518. uv: uv()
  9519. } );
  9520. }
  9521. }
  9522. return outputNode;
  9523. }
  9524. }
  9525. /**
  9526. * TSL function for creating a normal map node.
  9527. *
  9528. * @tsl
  9529. * @function
  9530. * @param {Node<vec3>} node - Represents the normal map data.
  9531. * @param {?Node<vec2>} [scaleNode=null] - Controls the intensity of the effect.
  9532. * @returns {NormalMapNode}
  9533. */
  9534. const normalMap = /*@__PURE__*/ nodeProxy( NormalMapNode ).setParameterLength( 1, 2 );
  9535. // Bump Mapping Unparametrized Surfaces on the GPU by Morten S. Mikkelsen
  9536. // https://mmikk.github.io/papers3d/mm_sfgrad_bump.pdf
  9537. const dHdxy_fwd = Fn( ( { textureNode, bumpScale } ) => {
  9538. // It's used to preserve the same TextureNode instance
  9539. const sampleTexture = ( callback ) => textureNode.cache().context( { getUV: ( texNode ) => callback( texNode.uvNode || uv() ), forceUVContext: true } );
  9540. const Hll = float( sampleTexture( ( uvNode ) => uvNode ) );
  9541. return vec2(
  9542. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdx() ) ) ).sub( Hll ),
  9543. float( sampleTexture( ( uvNode ) => uvNode.add( uvNode.dFdy() ) ) ).sub( Hll )
  9544. ).mul( bumpScale );
  9545. } );
  9546. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9547. const perturbNormalArb = Fn( ( inputs ) => {
  9548. const { surf_pos, surf_norm, dHdxy } = inputs;
  9549. // normalize is done to ensure that the bump map looks the same regardless of the texture's scale
  9550. const vSigmaX = surf_pos.dFdx().normalize();
  9551. const vSigmaY = surf_pos.dFdy().normalize();
  9552. const vN = surf_norm; // normalized
  9553. const R1 = vSigmaY.cross( vN );
  9554. const R2 = vN.cross( vSigmaX );
  9555. const fDet = vSigmaX.dot( R1 ).mul( faceDirection );
  9556. const vGrad = fDet.sign().mul( dHdxy.x.mul( R1 ).add( dHdxy.y.mul( R2 ) ) );
  9557. return fDet.abs().mul( surf_norm ).sub( vGrad ).normalize();
  9558. } );
  9559. /**
  9560. * This class can be used for applying bump maps to materials.
  9561. *
  9562. * ```js
  9563. * material.normalNode = bumpMap( texture( bumpTex ) );
  9564. * ```
  9565. *
  9566. * @augments TempNode
  9567. */
  9568. class BumpMapNode extends TempNode {
  9569. static get type() {
  9570. return 'BumpMapNode';
  9571. }
  9572. /**
  9573. * Constructs a new bump map node.
  9574. *
  9575. * @param {Node<float>} textureNode - Represents the bump map data.
  9576. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  9577. */
  9578. constructor( textureNode, scaleNode = null ) {
  9579. super( 'vec3' );
  9580. /**
  9581. * Represents the bump map data.
  9582. *
  9583. * @type {Node<float>}
  9584. */
  9585. this.textureNode = textureNode;
  9586. /**
  9587. * Controls the intensity of the bump effect.
  9588. *
  9589. * @type {?Node<float>}
  9590. * @default null
  9591. */
  9592. this.scaleNode = scaleNode;
  9593. }
  9594. setup() {
  9595. const bumpScale = this.scaleNode !== null ? this.scaleNode : 1;
  9596. const dHdxy = dHdxy_fwd( { textureNode: this.textureNode, bumpScale } );
  9597. return perturbNormalArb( {
  9598. surf_pos: positionView,
  9599. surf_norm: normalView,
  9600. dHdxy
  9601. } );
  9602. }
  9603. }
  9604. /**
  9605. * TSL function for creating a bump map node.
  9606. *
  9607. * @tsl
  9608. * @function
  9609. * @param {Node<float>} textureNode - Represents the bump map data.
  9610. * @param {?Node<float>} [scaleNode=null] - Controls the intensity of the bump effect.
  9611. * @returns {BumpMapNode}
  9612. */
  9613. const bumpMap = /*@__PURE__*/ nodeProxy( BumpMapNode ).setParameterLength( 1, 2 );
  9614. const _propertyCache = new Map();
  9615. /**
  9616. * This class should simplify the node access to material properties.
  9617. * It internal uses reference nodes to make sure changes to material
  9618. * properties are automatically reflected to predefined TSL objects
  9619. * like e.g. `materialColor`.
  9620. *
  9621. * @augments Node
  9622. */
  9623. class MaterialNode extends Node {
  9624. static get type() {
  9625. return 'MaterialNode';
  9626. }
  9627. /**
  9628. * Constructs a new material node.
  9629. *
  9630. * @param {string} scope - The scope defines what kind of material property is referred by the node.
  9631. */
  9632. constructor( scope ) {
  9633. super();
  9634. /**
  9635. * The scope defines what material property is referred by the node.
  9636. *
  9637. * @type {string}
  9638. */
  9639. this.scope = scope;
  9640. }
  9641. /**
  9642. * Returns a cached reference node for the given property and type.
  9643. *
  9644. * @param {string} property - The name of the material property.
  9645. * @param {string} type - The uniform type of the property.
  9646. * @return {MaterialReferenceNode} A material reference node representing the property access.
  9647. */
  9648. getCache( property, type ) {
  9649. let node = _propertyCache.get( property );
  9650. if ( node === undefined ) {
  9651. node = materialReference( property, type );
  9652. _propertyCache.set( property, node );
  9653. }
  9654. return node;
  9655. }
  9656. /**
  9657. * Returns a float-typed material reference node for the given property name.
  9658. *
  9659. * @param {string} property - The name of the material property.
  9660. * @return {MaterialReferenceNode<float>} A material reference node representing the property access.
  9661. */
  9662. getFloat( property ) {
  9663. return this.getCache( property, 'float' );
  9664. }
  9665. /**
  9666. * Returns a color-typed material reference node for the given property name.
  9667. *
  9668. * @param {string} property - The name of the material property.
  9669. * @return {MaterialReferenceNode<color>} A material reference node representing the property access.
  9670. */
  9671. getColor( property ) {
  9672. return this.getCache( property, 'color' );
  9673. }
  9674. /**
  9675. * Returns a texture-typed material reference node for the given property name.
  9676. *
  9677. * @param {string} property - The name of the material property.
  9678. * @return {MaterialReferenceNode} A material reference node representing the property access.
  9679. */
  9680. getTexture( property ) {
  9681. return this.getCache( property === 'map' ? 'map' : property + 'Map', 'texture' );
  9682. }
  9683. /**
  9684. * The node setup is done depending on the selected scope. Multiple material properties
  9685. * might be grouped into a single node composition if they logically belong together.
  9686. *
  9687. * @param {NodeBuilder} builder - The current node builder.
  9688. * @return {Node} The node representing the selected scope.
  9689. */
  9690. setup( builder ) {
  9691. const material = builder.context.material;
  9692. const scope = this.scope;
  9693. let node = null;
  9694. if ( scope === MaterialNode.COLOR ) {
  9695. const colorNode = material.color !== undefined ? this.getColor( scope ) : vec3();
  9696. if ( material.map && material.map.isTexture === true ) {
  9697. node = colorNode.mul( this.getTexture( 'map' ) );
  9698. } else {
  9699. node = colorNode;
  9700. }
  9701. } else if ( scope === MaterialNode.OPACITY ) {
  9702. const opacityNode = this.getFloat( scope );
  9703. if ( material.alphaMap && material.alphaMap.isTexture === true ) {
  9704. node = opacityNode.mul( this.getTexture( 'alpha' ) );
  9705. } else {
  9706. node = opacityNode;
  9707. }
  9708. } else if ( scope === MaterialNode.SPECULAR_STRENGTH ) {
  9709. if ( material.specularMap && material.specularMap.isTexture === true ) {
  9710. node = this.getTexture( 'specular' ).r;
  9711. } else {
  9712. node = float( 1 );
  9713. }
  9714. } else if ( scope === MaterialNode.SPECULAR_INTENSITY ) {
  9715. const specularIntensityNode = this.getFloat( scope );
  9716. if ( material.specularIntensityMap && material.specularIntensityMap.isTexture === true ) {
  9717. node = specularIntensityNode.mul( this.getTexture( scope ).a );
  9718. } else {
  9719. node = specularIntensityNode;
  9720. }
  9721. } else if ( scope === MaterialNode.SPECULAR_COLOR ) {
  9722. const specularColorNode = this.getColor( scope );
  9723. if ( material.specularColorMap && material.specularColorMap.isTexture === true ) {
  9724. node = specularColorNode.mul( this.getTexture( scope ).rgb );
  9725. } else {
  9726. node = specularColorNode;
  9727. }
  9728. } else if ( scope === MaterialNode.ROUGHNESS ) { // TODO: cleanup similar branches
  9729. const roughnessNode = this.getFloat( scope );
  9730. if ( material.roughnessMap && material.roughnessMap.isTexture === true ) {
  9731. node = roughnessNode.mul( this.getTexture( scope ).g );
  9732. } else {
  9733. node = roughnessNode;
  9734. }
  9735. } else if ( scope === MaterialNode.METALNESS ) {
  9736. const metalnessNode = this.getFloat( scope );
  9737. if ( material.metalnessMap && material.metalnessMap.isTexture === true ) {
  9738. node = metalnessNode.mul( this.getTexture( scope ).b );
  9739. } else {
  9740. node = metalnessNode;
  9741. }
  9742. } else if ( scope === MaterialNode.EMISSIVE ) {
  9743. const emissiveIntensityNode = this.getFloat( 'emissiveIntensity' );
  9744. const emissiveNode = this.getColor( scope ).mul( emissiveIntensityNode );
  9745. if ( material.emissiveMap && material.emissiveMap.isTexture === true ) {
  9746. node = emissiveNode.mul( this.getTexture( scope ) );
  9747. } else {
  9748. node = emissiveNode;
  9749. }
  9750. } else if ( scope === MaterialNode.NORMAL ) {
  9751. if ( material.normalMap ) {
  9752. node = normalMap( this.getTexture( 'normal' ), this.getCache( 'normalScale', 'vec2' ) );
  9753. node.normalMapType = material.normalMapType;
  9754. } else if ( material.bumpMap ) {
  9755. node = bumpMap( this.getTexture( 'bump' ).r, this.getFloat( 'bumpScale' ) );
  9756. } else {
  9757. node = normalView;
  9758. }
  9759. } else if ( scope === MaterialNode.CLEARCOAT ) {
  9760. const clearcoatNode = this.getFloat( scope );
  9761. if ( material.clearcoatMap && material.clearcoatMap.isTexture === true ) {
  9762. node = clearcoatNode.mul( this.getTexture( scope ).r );
  9763. } else {
  9764. node = clearcoatNode;
  9765. }
  9766. } else if ( scope === MaterialNode.CLEARCOAT_ROUGHNESS ) {
  9767. const clearcoatRoughnessNode = this.getFloat( scope );
  9768. if ( material.clearcoatRoughnessMap && material.clearcoatRoughnessMap.isTexture === true ) {
  9769. node = clearcoatRoughnessNode.mul( this.getTexture( scope ).r );
  9770. } else {
  9771. node = clearcoatRoughnessNode;
  9772. }
  9773. } else if ( scope === MaterialNode.CLEARCOAT_NORMAL ) {
  9774. if ( material.clearcoatNormalMap ) {
  9775. node = normalMap( this.getTexture( scope ), this.getCache( scope + 'Scale', 'vec2' ) );
  9776. } else {
  9777. node = normalView;
  9778. }
  9779. } else if ( scope === MaterialNode.SHEEN ) {
  9780. const sheenNode = this.getColor( 'sheenColor' ).mul( this.getFloat( 'sheen' ) ); // Move this mul() to CPU
  9781. if ( material.sheenColorMap && material.sheenColorMap.isTexture === true ) {
  9782. node = sheenNode.mul( this.getTexture( 'sheenColor' ).rgb );
  9783. } else {
  9784. node = sheenNode;
  9785. }
  9786. } else if ( scope === MaterialNode.SHEEN_ROUGHNESS ) {
  9787. const sheenRoughnessNode = this.getFloat( scope );
  9788. if ( material.sheenRoughnessMap && material.sheenRoughnessMap.isTexture === true ) {
  9789. node = sheenRoughnessNode.mul( this.getTexture( scope ).a );
  9790. } else {
  9791. node = sheenRoughnessNode;
  9792. }
  9793. node = node.clamp( 0.07, 1.0 );
  9794. } else if ( scope === MaterialNode.ANISOTROPY ) {
  9795. if ( material.anisotropyMap && material.anisotropyMap.isTexture === true ) {
  9796. const anisotropyPolar = this.getTexture( scope );
  9797. const anisotropyMat = mat2( materialAnisotropyVector.x, materialAnisotropyVector.y, materialAnisotropyVector.y.negate(), materialAnisotropyVector.x );
  9798. node = anisotropyMat.mul( anisotropyPolar.rg.mul( 2.0 ).sub( vec2( 1.0 ) ).normalize().mul( anisotropyPolar.b ) );
  9799. } else {
  9800. node = materialAnisotropyVector;
  9801. }
  9802. } else if ( scope === MaterialNode.IRIDESCENCE_THICKNESS ) {
  9803. const iridescenceThicknessMaximum = reference( '1', 'float', material.iridescenceThicknessRange );
  9804. if ( material.iridescenceThicknessMap ) {
  9805. const iridescenceThicknessMinimum = reference( '0', 'float', material.iridescenceThicknessRange );
  9806. node = iridescenceThicknessMaximum.sub( iridescenceThicknessMinimum ).mul( this.getTexture( scope ).g ).add( iridescenceThicknessMinimum );
  9807. } else {
  9808. node = iridescenceThicknessMaximum;
  9809. }
  9810. } else if ( scope === MaterialNode.TRANSMISSION ) {
  9811. const transmissionNode = this.getFloat( scope );
  9812. if ( material.transmissionMap ) {
  9813. node = transmissionNode.mul( this.getTexture( scope ).r );
  9814. } else {
  9815. node = transmissionNode;
  9816. }
  9817. } else if ( scope === MaterialNode.THICKNESS ) {
  9818. const thicknessNode = this.getFloat( scope );
  9819. if ( material.thicknessMap ) {
  9820. node = thicknessNode.mul( this.getTexture( scope ).g );
  9821. } else {
  9822. node = thicknessNode;
  9823. }
  9824. } else if ( scope === MaterialNode.IOR ) {
  9825. node = this.getFloat( scope );
  9826. } else if ( scope === MaterialNode.LIGHT_MAP ) {
  9827. node = this.getTexture( scope ).rgb.mul( this.getFloat( 'lightMapIntensity' ) );
  9828. } else if ( scope === MaterialNode.AO ) {
  9829. node = this.getTexture( scope ).r.sub( 1.0 ).mul( this.getFloat( 'aoMapIntensity' ) ).add( 1.0 );
  9830. } else if ( scope === MaterialNode.LINE_DASH_OFFSET ) {
  9831. node = ( material.dashOffset ) ? this.getFloat( scope ) : float( 0 );
  9832. } else {
  9833. const outputType = this.getNodeType( builder );
  9834. node = this.getCache( scope, outputType );
  9835. }
  9836. return node;
  9837. }
  9838. }
  9839. MaterialNode.ALPHA_TEST = 'alphaTest';
  9840. MaterialNode.COLOR = 'color';
  9841. MaterialNode.OPACITY = 'opacity';
  9842. MaterialNode.SHININESS = 'shininess';
  9843. MaterialNode.SPECULAR = 'specular';
  9844. MaterialNode.SPECULAR_STRENGTH = 'specularStrength';
  9845. MaterialNode.SPECULAR_INTENSITY = 'specularIntensity';
  9846. MaterialNode.SPECULAR_COLOR = 'specularColor';
  9847. MaterialNode.REFLECTIVITY = 'reflectivity';
  9848. MaterialNode.ROUGHNESS = 'roughness';
  9849. MaterialNode.METALNESS = 'metalness';
  9850. MaterialNode.NORMAL = 'normal';
  9851. MaterialNode.CLEARCOAT = 'clearcoat';
  9852. MaterialNode.CLEARCOAT_ROUGHNESS = 'clearcoatRoughness';
  9853. MaterialNode.CLEARCOAT_NORMAL = 'clearcoatNormal';
  9854. MaterialNode.EMISSIVE = 'emissive';
  9855. MaterialNode.ROTATION = 'rotation';
  9856. MaterialNode.SHEEN = 'sheen';
  9857. MaterialNode.SHEEN_ROUGHNESS = 'sheenRoughness';
  9858. MaterialNode.ANISOTROPY = 'anisotropy';
  9859. MaterialNode.IRIDESCENCE = 'iridescence';
  9860. MaterialNode.IRIDESCENCE_IOR = 'iridescenceIOR';
  9861. MaterialNode.IRIDESCENCE_THICKNESS = 'iridescenceThickness';
  9862. MaterialNode.IOR = 'ior';
  9863. MaterialNode.TRANSMISSION = 'transmission';
  9864. MaterialNode.THICKNESS = 'thickness';
  9865. MaterialNode.ATTENUATION_DISTANCE = 'attenuationDistance';
  9866. MaterialNode.ATTENUATION_COLOR = 'attenuationColor';
  9867. MaterialNode.LINE_SCALE = 'scale';
  9868. MaterialNode.LINE_DASH_SIZE = 'dashSize';
  9869. MaterialNode.LINE_GAP_SIZE = 'gapSize';
  9870. MaterialNode.LINE_WIDTH = 'linewidth';
  9871. MaterialNode.LINE_DASH_OFFSET = 'dashOffset';
  9872. MaterialNode.POINT_SIZE = 'size';
  9873. MaterialNode.DISPERSION = 'dispersion';
  9874. MaterialNode.LIGHT_MAP = 'light';
  9875. MaterialNode.AO = 'ao';
  9876. /**
  9877. * TSL object that represents alpha test of the current material.
  9878. *
  9879. * @tsl
  9880. * @type {Node<float>}
  9881. */
  9882. const materialAlphaTest = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ALPHA_TEST );
  9883. /**
  9884. * TSL object that represents the diffuse color of the current material.
  9885. * The value is composed via `color` * `map`.
  9886. *
  9887. * @tsl
  9888. * @type {Node<vec3>}
  9889. */
  9890. const materialColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.COLOR );
  9891. /**
  9892. * TSL object that represents the shininess of the current material.
  9893. *
  9894. * @tsl
  9895. * @type {Node<float>}
  9896. */
  9897. const materialShininess = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHININESS );
  9898. /**
  9899. * TSL object that represents the emissive color of the current material.
  9900. * The value is composed via `emissive` * `emissiveIntensity` * `emissiveMap`.
  9901. *
  9902. * @tsl
  9903. * @type {Node<vec3>}
  9904. */
  9905. const materialEmissive = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.EMISSIVE );
  9906. /**
  9907. * TSL object that represents the opacity of the current material.
  9908. * The value is composed via `opacity` * `alphaMap`.
  9909. *
  9910. * @tsl
  9911. * @type {Node<float>}
  9912. */
  9913. const materialOpacity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.OPACITY );
  9914. /**
  9915. * TSL object that represents the specular of the current material.
  9916. *
  9917. * @tsl
  9918. * @type {Node<vec3>}
  9919. */
  9920. const materialSpecular = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR );
  9921. /**
  9922. * TSL object that represents the specular intensity of the current material.
  9923. * The value is composed via `specularIntensity` * `specularMap.a`.
  9924. *
  9925. * @tsl
  9926. * @type {Node<float>}
  9927. */
  9928. const materialSpecularIntensity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_INTENSITY );
  9929. /**
  9930. * TSL object that represents the specular color of the current material.
  9931. * The value is composed via `specularColor` * `specularMap.rgb`.
  9932. *
  9933. * @tsl
  9934. * @type {Node<vec3>}
  9935. */
  9936. const materialSpecularColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_COLOR );
  9937. /**
  9938. * TSL object that represents the specular strength of the current material.
  9939. * The value is composed via `specularMap.r`.
  9940. *
  9941. * @tsl
  9942. * @type {Node<float>}
  9943. */
  9944. const materialSpecularStrength = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SPECULAR_STRENGTH );
  9945. /**
  9946. * TSL object that represents the reflectivity of the current material.
  9947. *
  9948. * @tsl
  9949. * @type {Node<float>}
  9950. */
  9951. const materialReflectivity = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.REFLECTIVITY );
  9952. /**
  9953. * TSL object that represents the roughness of the current material.
  9954. * The value is composed via `roughness` * `roughnessMap.g`.
  9955. *
  9956. * @tsl
  9957. * @type {Node<float>}
  9958. */
  9959. const materialRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROUGHNESS );
  9960. /**
  9961. * TSL object that represents the metalness of the current material.
  9962. * The value is composed via `metalness` * `metalnessMap.b`.
  9963. *
  9964. * @tsl
  9965. * @type {Node<float>}
  9966. */
  9967. const materialMetalness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.METALNESS );
  9968. /**
  9969. * TSL object that represents the normal of the current material.
  9970. * The value will be either `normalMap` * `normalScale`, `bumpMap` * `bumpScale` or `normalView`.
  9971. *
  9972. * @tsl
  9973. * @type {Node<vec3>}
  9974. */
  9975. const materialNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.NORMAL );
  9976. /**
  9977. * TSL object that represents the clearcoat of the current material.
  9978. * The value is composed via `clearcoat` * `clearcoatMap.r`
  9979. *
  9980. * @tsl
  9981. * @type {Node<float>}
  9982. */
  9983. const materialClearcoat = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT );
  9984. /**
  9985. * TSL object that represents the clearcoat roughness of the current material.
  9986. * The value is composed via `clearcoatRoughness` * `clearcoatRoughnessMap.r`.
  9987. *
  9988. * @tsl
  9989. * @type {Node<float>}
  9990. */
  9991. const materialClearcoatRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_ROUGHNESS );
  9992. /**
  9993. * TSL object that represents the clearcoat normal of the current material.
  9994. * The value will be either `clearcoatNormalMap` or `normalView`.
  9995. *
  9996. * @tsl
  9997. * @type {Node<vec3>}
  9998. */
  9999. const materialClearcoatNormal = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.CLEARCOAT_NORMAL );
  10000. /**
  10001. * TSL object that represents the rotation of the current sprite material.
  10002. *
  10003. * @tsl
  10004. * @type {Node<float>}
  10005. */
  10006. const materialRotation = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ROTATION );
  10007. /**
  10008. * TSL object that represents the sheen color of the current material.
  10009. * The value is composed via `sheen` * `sheenColor` * `sheenColorMap`.
  10010. *
  10011. * @tsl
  10012. * @type {Node<vec3>}
  10013. */
  10014. const materialSheen = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN );
  10015. /**
  10016. * TSL object that represents the sheen roughness of the current material.
  10017. * The value is composed via `sheenRoughness` * `sheenRoughnessMap.a`.
  10018. *
  10019. * @tsl
  10020. * @type {Node<float>}
  10021. */
  10022. const materialSheenRoughness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.SHEEN_ROUGHNESS );
  10023. /**
  10024. * TSL object that represents the anisotropy of the current material.
  10025. *
  10026. * @tsl
  10027. * @type {Node<vec2>}
  10028. */
  10029. const materialAnisotropy = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ANISOTROPY );
  10030. /**
  10031. * TSL object that represents the iridescence of the current material.
  10032. *
  10033. * @tsl
  10034. * @type {Node<float>}
  10035. */
  10036. const materialIridescence = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE );
  10037. /**
  10038. * TSL object that represents the iridescence IOR of the current material.
  10039. *
  10040. * @tsl
  10041. * @type {Node<float>}
  10042. */
  10043. const materialIridescenceIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_IOR );
  10044. /**
  10045. * TSL object that represents the iridescence thickness of the current material.
  10046. *
  10047. * @tsl
  10048. * @type {Node<float>}
  10049. */
  10050. const materialIridescenceThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IRIDESCENCE_THICKNESS );
  10051. /**
  10052. * TSL object that represents the transmission of the current material.
  10053. * The value is composed via `transmission` * `transmissionMap.r`.
  10054. *
  10055. * @tsl
  10056. * @type {Node<float>}
  10057. */
  10058. const materialTransmission = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.TRANSMISSION );
  10059. /**
  10060. * TSL object that represents the thickness of the current material.
  10061. * The value is composed via `thickness` * `thicknessMap.g`.
  10062. *
  10063. * @tsl
  10064. * @type {Node<float>}
  10065. */
  10066. const materialThickness = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.THICKNESS );
  10067. /**
  10068. * TSL object that represents the IOR of the current material.
  10069. *
  10070. * @tsl
  10071. * @type {Node<float>}
  10072. */
  10073. const materialIOR = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.IOR );
  10074. /**
  10075. * TSL object that represents the attenuation distance of the current material.
  10076. *
  10077. * @tsl
  10078. * @type {Node<float>}
  10079. */
  10080. const materialAttenuationDistance = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_DISTANCE );
  10081. /**
  10082. * TSL object that represents the attenuation color of the current material.
  10083. *
  10084. * @tsl
  10085. * @type {Node<vec3>}
  10086. */
  10087. const materialAttenuationColor = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.ATTENUATION_COLOR );
  10088. /**
  10089. * TSL object that represents the scale of the current dashed line material.
  10090. *
  10091. * @tsl
  10092. * @type {Node<float>}
  10093. */
  10094. const materialLineScale = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_SCALE );
  10095. /**
  10096. * TSL object that represents the dash size of the current dashed line material.
  10097. *
  10098. * @tsl
  10099. * @type {Node<float>}
  10100. */
  10101. const materialLineDashSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_SIZE );
  10102. /**
  10103. * TSL object that represents the gap size of the current dashed line material.
  10104. *
  10105. * @tsl
  10106. * @type {Node<float>}
  10107. */
  10108. const materialLineGapSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_GAP_SIZE );
  10109. /**
  10110. * TSL object that represents the line width of the current line material.
  10111. *
  10112. * @tsl
  10113. * @type {Node<float>}
  10114. */
  10115. const materialLineWidth = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_WIDTH );
  10116. /**
  10117. * TSL object that represents the dash offset of the current line material.
  10118. *
  10119. * @tsl
  10120. * @type {Node<float>}
  10121. */
  10122. const materialLineDashOffset = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LINE_DASH_OFFSET );
  10123. /**
  10124. * TSL object that represents the point size of the current points material.
  10125. *
  10126. * @tsl
  10127. * @type {Node<float>}
  10128. */
  10129. const materialPointSize = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.POINT_SIZE );
  10130. /**
  10131. * TSL object that represents the dispersion of the current material.
  10132. *
  10133. * @tsl
  10134. * @type {Node<float>}
  10135. */
  10136. const materialDispersion = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.DISPERSION );
  10137. /**
  10138. * TSL object that represents the light map of the current material.
  10139. * The value is composed via `lightMapIntensity` * `lightMap.rgb`.
  10140. *
  10141. * @tsl
  10142. * @type {Node<vec3>}
  10143. */
  10144. const materialLightMap = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.LIGHT_MAP );
  10145. /**
  10146. * TSL object that represents the ambient occlusion map of the current material.
  10147. * The value is composed via `aoMap.r` - 1 * `aoMapIntensity` + 1.
  10148. *
  10149. * @tsl
  10150. * @type {Node<float>}
  10151. */
  10152. const materialAO = /*@__PURE__*/ nodeImmutable( MaterialNode, MaterialNode.AO );
  10153. /**
  10154. * TSL object that represents the anisotropy vector of the current material.
  10155. *
  10156. * @tsl
  10157. * @type {Node<vec2>}
  10158. */
  10159. const materialAnisotropyVector = /*@__PURE__*/ uniform( new Vector2() ).onReference( function ( frame ) {
  10160. return frame.material;
  10161. } ).onRenderUpdate( function ( { material } ) {
  10162. this.value.set( material.anisotropy * Math.cos( material.anisotropyRotation ), material.anisotropy * Math.sin( material.anisotropyRotation ) );
  10163. } );
  10164. /**
  10165. * TSL object that represents the position in clip space after the model-view-projection transform of the current rendered object.
  10166. *
  10167. * @tsl
  10168. * @type {VaryingNode<vec4>}
  10169. */
  10170. const modelViewProjection = /*@__PURE__*/ ( Fn( ( builder ) => {
  10171. return builder.context.setupModelViewProjection();
  10172. }, 'vec4' ).once() )().toVarying( 'v_modelViewProjection' );
  10173. /**
  10174. * This class represents shader indices of different types. The following predefined node
  10175. * objects cover frequent use cases:
  10176. *
  10177. * - `vertexIndex`: The index of a vertex within a mesh.
  10178. * - `instanceIndex`: The index of either a mesh instance or an invocation of a compute shader.
  10179. * - `drawIndex`: The index of a draw call.
  10180. * - `invocationLocalIndex`: The index of a compute invocation within the scope of a workgroup load.
  10181. * - `invocationSubgroupIndex`: The index of a compute invocation within the scope of a subgroup.
  10182. * - `subgroupIndex`: The index of the subgroup the current compute invocation belongs to.
  10183. *
  10184. * @augments Node
  10185. */
  10186. class IndexNode extends Node {
  10187. static get type() {
  10188. return 'IndexNode';
  10189. }
  10190. /**
  10191. * Constructs a new index node.
  10192. *
  10193. * @param {('vertex'|'instance'|'subgroup'|'invocationLocal'|'invocationSubgroup'|'draw')} scope - The scope of the index node.
  10194. */
  10195. constructor( scope ) {
  10196. super( 'uint' );
  10197. /**
  10198. * The scope of the index node.
  10199. *
  10200. * @type {string}
  10201. */
  10202. this.scope = scope;
  10203. /**
  10204. * This flag can be used for type testing.
  10205. *
  10206. * @type {boolean}
  10207. * @readonly
  10208. * @default true
  10209. */
  10210. this.isIndexNode = true;
  10211. }
  10212. generate( builder ) {
  10213. const nodeType = this.getNodeType( builder );
  10214. const scope = this.scope;
  10215. let propertyName;
  10216. if ( scope === IndexNode.VERTEX ) {
  10217. propertyName = builder.getVertexIndex();
  10218. } else if ( scope === IndexNode.INSTANCE ) {
  10219. propertyName = builder.getInstanceIndex();
  10220. } else if ( scope === IndexNode.DRAW ) {
  10221. propertyName = builder.getDrawIndex();
  10222. } else if ( scope === IndexNode.INVOCATION_LOCAL ) {
  10223. propertyName = builder.getInvocationLocalIndex();
  10224. } else if ( scope === IndexNode.INVOCATION_SUBGROUP ) {
  10225. propertyName = builder.getInvocationSubgroupIndex();
  10226. } else if ( scope === IndexNode.SUBGROUP ) {
  10227. propertyName = builder.getSubgroupIndex();
  10228. } else {
  10229. throw new Error( 'THREE.IndexNode: Unknown scope: ' + scope );
  10230. }
  10231. let output;
  10232. if ( builder.shaderStage === 'vertex' || builder.shaderStage === 'compute' ) {
  10233. output = propertyName;
  10234. } else {
  10235. const nodeVarying = varying( this );
  10236. output = nodeVarying.build( builder, nodeType );
  10237. }
  10238. return output;
  10239. }
  10240. }
  10241. IndexNode.VERTEX = 'vertex';
  10242. IndexNode.INSTANCE = 'instance';
  10243. IndexNode.SUBGROUP = 'subgroup';
  10244. IndexNode.INVOCATION_LOCAL = 'invocationLocal';
  10245. IndexNode.INVOCATION_SUBGROUP = 'invocationSubgroup';
  10246. IndexNode.DRAW = 'draw';
  10247. /**
  10248. * TSL object that represents the index of a vertex within a mesh.
  10249. *
  10250. * @tsl
  10251. * @type {IndexNode}
  10252. */
  10253. const vertexIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.VERTEX );
  10254. /**
  10255. * TSL object that represents the index of either a mesh instance or an invocation of a compute shader.
  10256. *
  10257. * @tsl
  10258. * @type {IndexNode}
  10259. */
  10260. const instanceIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INSTANCE );
  10261. /**
  10262. * TSL object that represents the index of the subgroup the current compute invocation belongs to.
  10263. *
  10264. * @tsl
  10265. * @type {IndexNode}
  10266. */
  10267. const subgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.SUBGROUP );
  10268. /**
  10269. * TSL object that represents the index of a compute invocation within the scope of a subgroup.
  10270. *
  10271. * @tsl
  10272. * @type {IndexNode}
  10273. */
  10274. const invocationSubgroupIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_SUBGROUP );
  10275. /**
  10276. * TSL object that represents the index of a compute invocation within the scope of a workgroup load.
  10277. *
  10278. * @tsl
  10279. * @type {IndexNode}
  10280. */
  10281. const invocationLocalIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.INVOCATION_LOCAL );
  10282. /**
  10283. * TSL object that represents the index of a draw call.
  10284. *
  10285. * @tsl
  10286. * @type {IndexNode}
  10287. */
  10288. const drawIndex = /*@__PURE__*/ nodeImmutable( IndexNode, IndexNode.DRAW );
  10289. /**
  10290. * This node implements the vertex shader logic which is required
  10291. * when rendering 3D objects via instancing. The code makes sure
  10292. * vertex positions, normals and colors can be modified via instanced
  10293. * data.
  10294. *
  10295. * @augments Node
  10296. */
  10297. class InstanceNode extends Node {
  10298. static get type() {
  10299. return 'InstanceNode';
  10300. }
  10301. /**
  10302. * Constructs a new instance node.
  10303. *
  10304. * @param {number} count - The number of instances.
  10305. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  10306. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  10307. */
  10308. constructor( count, instanceMatrix, instanceColor = null ) {
  10309. super( 'void' );
  10310. /**
  10311. * The number of instances.
  10312. *
  10313. * @type {number}
  10314. */
  10315. this.count = count;
  10316. /**
  10317. * Instanced buffer attribute representing the transformation of instances.
  10318. *
  10319. * @type {InstancedBufferAttribute}
  10320. */
  10321. this.instanceMatrix = instanceMatrix;
  10322. /**
  10323. * Instanced buffer attribute representing the color of instances.
  10324. *
  10325. * @type {InstancedBufferAttribute}
  10326. */
  10327. this.instanceColor = instanceColor;
  10328. /**
  10329. * The node that represents the instance matrix data.
  10330. *
  10331. * @type {?Node}
  10332. */
  10333. this.instanceMatrixNode = null;
  10334. /**
  10335. * The node that represents the instance color data.
  10336. *
  10337. * @type {?Node}
  10338. * @default null
  10339. */
  10340. this.instanceColorNode = null;
  10341. /**
  10342. * The update type is set to `frame` since an update
  10343. * of instanced buffer data must be checked per frame.
  10344. *
  10345. * @type {string}
  10346. * @default 'frame'
  10347. */
  10348. this.updateType = NodeUpdateType.FRAME;
  10349. /**
  10350. * A reference to a buffer that is used by `instanceMatrixNode`.
  10351. *
  10352. * @type {?InstancedInterleavedBuffer}
  10353. */
  10354. this.buffer = null;
  10355. /**
  10356. * A reference to a buffer that is used by `instanceColorNode`.
  10357. *
  10358. * @type {?InstancedBufferAttribute}
  10359. */
  10360. this.bufferColor = null;
  10361. }
  10362. /**
  10363. * Setups the internal buffers and nodes and assigns the transformed vertex data
  10364. * to predefined node variables for accumulation. That follows the same patterns
  10365. * like with morph and skinning nodes.
  10366. *
  10367. * @param {NodeBuilder} builder - The current node builder.
  10368. */
  10369. setup( builder ) {
  10370. const { count, instanceMatrix, instanceColor } = this;
  10371. let { instanceMatrixNode, instanceColorNode } = this;
  10372. if ( instanceMatrixNode === null ) {
  10373. // 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.
  10374. if ( count <= 1000 ) {
  10375. instanceMatrixNode = buffer( instanceMatrix.array, 'mat4', Math.max( count, 1 ) ).element( instanceIndex );
  10376. } else {
  10377. const buffer = new InstancedInterleavedBuffer( instanceMatrix.array, 16, 1 );
  10378. this.buffer = buffer;
  10379. const bufferFn = instanceMatrix.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  10380. const instanceBuffers = [
  10381. // F.Signature -> bufferAttribute( array, type, stride, offset )
  10382. bufferFn( buffer, 'vec4', 16, 0 ),
  10383. bufferFn( buffer, 'vec4', 16, 4 ),
  10384. bufferFn( buffer, 'vec4', 16, 8 ),
  10385. bufferFn( buffer, 'vec4', 16, 12 )
  10386. ];
  10387. instanceMatrixNode = mat4( ...instanceBuffers );
  10388. }
  10389. this.instanceMatrixNode = instanceMatrixNode;
  10390. }
  10391. if ( instanceColor && instanceColorNode === null ) {
  10392. const buffer = new InstancedBufferAttribute( instanceColor.array, 3 );
  10393. const bufferFn = instanceColor.usage === DynamicDrawUsage ? instancedDynamicBufferAttribute : instancedBufferAttribute;
  10394. this.bufferColor = buffer;
  10395. instanceColorNode = vec3( bufferFn( buffer, 'vec3', 3, 0 ) );
  10396. this.instanceColorNode = instanceColorNode;
  10397. }
  10398. // POSITION
  10399. const instancePosition = instanceMatrixNode.mul( positionLocal ).xyz;
  10400. positionLocal.assign( instancePosition );
  10401. // NORMAL
  10402. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  10403. const instanceNormal = transformNormal( normalLocal, instanceMatrixNode );
  10404. // ASSIGNS
  10405. normalLocal.assign( instanceNormal );
  10406. }
  10407. // COLOR
  10408. if ( this.instanceColorNode !== null ) {
  10409. varyingProperty( 'vec3', 'vInstanceColor' ).assign( this.instanceColorNode );
  10410. }
  10411. }
  10412. /**
  10413. * Checks if the internal buffers required an update.
  10414. *
  10415. * @param {NodeFrame} frame - The current node frame.
  10416. */
  10417. update( /*frame*/ ) {
  10418. if ( this.instanceMatrix.usage !== DynamicDrawUsage && this.buffer !== null && this.instanceMatrix.version !== this.buffer.version ) {
  10419. this.buffer.version = this.instanceMatrix.version;
  10420. }
  10421. if ( this.instanceColor && this.instanceColor.usage !== DynamicDrawUsage && this.bufferColor !== null && this.instanceColor.version !== this.bufferColor.version ) {
  10422. this.bufferColor.version = this.instanceColor.version;
  10423. }
  10424. }
  10425. }
  10426. /**
  10427. * TSL function for creating an instance node.
  10428. *
  10429. * @tsl
  10430. * @function
  10431. * @param {number} count - The number of instances.
  10432. * @param {InstancedBufferAttribute} instanceMatrix - Instanced buffer attribute representing the instance transformations.
  10433. * @param {?InstancedBufferAttribute} instanceColor - Instanced buffer attribute representing the instance colors.
  10434. * @returns {InstanceNode}
  10435. */
  10436. const instance = /*@__PURE__*/ nodeProxy( InstanceNode ).setParameterLength( 2, 3 );
  10437. /**
  10438. * This is a special version of `InstanceNode` which requires the usage of {@link InstancedMesh}.
  10439. * It allows an easier setup of the instance node.
  10440. *
  10441. * @augments InstanceNode
  10442. */
  10443. class InstancedMeshNode extends InstanceNode {
  10444. static get type() {
  10445. return 'InstancedMeshNode';
  10446. }
  10447. /**
  10448. * Constructs a new instanced mesh node.
  10449. *
  10450. * @param {InstancedMesh} instancedMesh - The instanced mesh.
  10451. */
  10452. constructor( instancedMesh ) {
  10453. const { count, instanceMatrix, instanceColor } = instancedMesh;
  10454. super( count, instanceMatrix, instanceColor );
  10455. /**
  10456. * A reference to the instanced mesh.
  10457. *
  10458. * @type {InstancedMesh}
  10459. */
  10460. this.instancedMesh = instancedMesh;
  10461. }
  10462. }
  10463. /**
  10464. * TSL function for creating an instanced mesh node.
  10465. *
  10466. * @tsl
  10467. * @function
  10468. * @param {InstancedMesh} instancedMesh - The instancedMesh.
  10469. * @returns {InstancedMeshNode}
  10470. */
  10471. const instancedMesh = /*@__PURE__*/ nodeProxy( InstancedMeshNode ).setParameterLength( 1 );
  10472. /**
  10473. * This node implements the vertex shader logic which is required
  10474. * when rendering 3D objects via batching. `BatchNode` must be used
  10475. * with instances of {@link BatchedMesh}.
  10476. *
  10477. * @augments Node
  10478. */
  10479. class BatchNode extends Node {
  10480. static get type() {
  10481. return 'BatchNode';
  10482. }
  10483. /**
  10484. * Constructs a new batch node.
  10485. *
  10486. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  10487. */
  10488. constructor( batchMesh ) {
  10489. super( 'void' );
  10490. /**
  10491. * A reference to batched mesh.
  10492. *
  10493. * @type {BatchedMesh}
  10494. */
  10495. this.batchMesh = batchMesh;
  10496. /**
  10497. * The batching index node.
  10498. *
  10499. * @type {?IndexNode}
  10500. * @default null
  10501. */
  10502. this.batchingIdNode = null;
  10503. }
  10504. /**
  10505. * Setups the internal buffers and nodes and assigns the transformed vertex data
  10506. * to predefined node variables for accumulation. That follows the same patterns
  10507. * like with morph and skinning nodes.
  10508. *
  10509. * @param {NodeBuilder} builder - The current node builder.
  10510. */
  10511. setup( builder ) {
  10512. if ( this.batchingIdNode === null ) {
  10513. if ( builder.getDrawIndex() === null ) {
  10514. this.batchingIdNode = instanceIndex;
  10515. } else {
  10516. this.batchingIdNode = drawIndex;
  10517. }
  10518. }
  10519. const getIndirectIndex = Fn( ( [ id ] ) => {
  10520. const size = int( textureSize( textureLoad( this.batchMesh._indirectTexture ), 0 ).x );
  10521. const x = int( id ).mod( size );
  10522. const y = int( id ).div( size );
  10523. return textureLoad( this.batchMesh._indirectTexture, ivec2( x, y ) ).x;
  10524. } ).setLayout( {
  10525. name: 'getIndirectIndex',
  10526. type: 'uint',
  10527. inputs: [
  10528. { name: 'id', type: 'int' }
  10529. ]
  10530. } );
  10531. const indirectId = getIndirectIndex( int( this.batchingIdNode ) );
  10532. const matricesTexture = this.batchMesh._matricesTexture;
  10533. const size = int( textureSize( textureLoad( matricesTexture ), 0 ).x );
  10534. const j = float( indirectId ).mul( 4 ).toInt().toVar();
  10535. const x = j.mod( size );
  10536. const y = j.div( size );
  10537. const batchingMatrix = mat4(
  10538. textureLoad( matricesTexture, ivec2( x, y ) ),
  10539. textureLoad( matricesTexture, ivec2( x.add( 1 ), y ) ),
  10540. textureLoad( matricesTexture, ivec2( x.add( 2 ), y ) ),
  10541. textureLoad( matricesTexture, ivec2( x.add( 3 ), y ) )
  10542. );
  10543. const colorsTexture = this.batchMesh._colorsTexture;
  10544. if ( colorsTexture !== null ) {
  10545. const getBatchingColor = Fn( ( [ id ] ) => {
  10546. const size = int( textureSize( textureLoad( colorsTexture ), 0 ).x );
  10547. const j = id;
  10548. const x = j.mod( size );
  10549. const y = j.div( size );
  10550. return textureLoad( colorsTexture, ivec2( x, y ) ).rgb;
  10551. } ).setLayout( {
  10552. name: 'getBatchingColor',
  10553. type: 'vec3',
  10554. inputs: [
  10555. { name: 'id', type: 'int' }
  10556. ]
  10557. } );
  10558. const color = getBatchingColor( indirectId );
  10559. varyingProperty( 'vec3', 'vBatchColor' ).assign( color );
  10560. }
  10561. const bm = mat3( batchingMatrix );
  10562. positionLocal.assign( batchingMatrix.mul( positionLocal ) );
  10563. const transformedNormal = normalLocal.div( vec3( bm[ 0 ].dot( bm[ 0 ] ), bm[ 1 ].dot( bm[ 1 ] ), bm[ 2 ].dot( bm[ 2 ] ) ) );
  10564. const batchingNormal = bm.mul( transformedNormal ).xyz;
  10565. normalLocal.assign( batchingNormal );
  10566. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  10567. tangentLocal.mulAssign( bm );
  10568. }
  10569. }
  10570. }
  10571. /**
  10572. * TSL function for creating a batch node.
  10573. *
  10574. * @tsl
  10575. * @function
  10576. * @param {BatchedMesh} batchMesh - A reference to batched mesh.
  10577. * @returns {BatchNode}
  10578. */
  10579. const batch = /*@__PURE__*/ nodeProxy( BatchNode ).setParameterLength( 1 );
  10580. /**
  10581. * This class enables element access on instances of {@link StorageBufferNode}.
  10582. * In most cases, it is indirectly used when accessing elements with the
  10583. * {@link StorageBufferNode#element} method.
  10584. *
  10585. * ```js
  10586. * const position = positionStorage.element( instanceIndex );
  10587. * ```
  10588. *
  10589. * @augments ArrayElementNode
  10590. */
  10591. class StorageArrayElementNode extends ArrayElementNode {
  10592. static get type() {
  10593. return 'StorageArrayElementNode';
  10594. }
  10595. /**
  10596. * Constructs storage buffer element node.
  10597. *
  10598. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  10599. * @param {Node} indexNode - The index node that defines the element access.
  10600. */
  10601. constructor( storageBufferNode, indexNode ) {
  10602. super( storageBufferNode, indexNode );
  10603. /**
  10604. * This flag can be used for type testing.
  10605. *
  10606. * @type {boolean}
  10607. * @readonly
  10608. * @default true
  10609. */
  10610. this.isStorageArrayElementNode = true;
  10611. }
  10612. /**
  10613. * The storage buffer node.
  10614. *
  10615. * @param {Node} value
  10616. * @type {StorageBufferNode}
  10617. */
  10618. set storageBufferNode( value ) {
  10619. this.node = value;
  10620. }
  10621. get storageBufferNode() {
  10622. return this.node;
  10623. }
  10624. getMemberType( builder, name ) {
  10625. const structTypeNode = this.storageBufferNode.structTypeNode;
  10626. if ( structTypeNode ) {
  10627. return structTypeNode.getMemberType( builder, name );
  10628. }
  10629. return 'void';
  10630. }
  10631. setup( builder ) {
  10632. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  10633. if ( this.node.isPBO === true ) {
  10634. builder.setupPBO( this.node );
  10635. }
  10636. }
  10637. return super.setup( builder );
  10638. }
  10639. generate( builder, output ) {
  10640. let snippet;
  10641. const isAssignContext = builder.context.assign;
  10642. //
  10643. if ( builder.isAvailable( 'storageBuffer' ) === false ) {
  10644. if ( this.node.isPBO === true && isAssignContext !== true && ( this.node.value.isInstancedBufferAttribute || builder.shaderStage !== 'compute' ) ) {
  10645. snippet = builder.generatePBO( this );
  10646. } else {
  10647. snippet = this.node.build( builder );
  10648. }
  10649. } else {
  10650. snippet = super.generate( builder );
  10651. }
  10652. if ( isAssignContext !== true ) {
  10653. const type = this.getNodeType( builder );
  10654. snippet = builder.format( snippet, type, output );
  10655. }
  10656. return snippet;
  10657. }
  10658. }
  10659. /**
  10660. * TSL function for creating a storage element node.
  10661. *
  10662. * @tsl
  10663. * @function
  10664. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  10665. * @param {Node} indexNode - The index node that defines the element access.
  10666. * @returns {StorageArrayElementNode}
  10667. */
  10668. const storageElement = /*@__PURE__*/ nodeProxy( StorageArrayElementNode ).setParameterLength( 2 );
  10669. /**
  10670. * This node is used in context of compute shaders and allows to define a
  10671. * storage buffer for data. A typical workflow is to create instances of
  10672. * this node with the convenience functions `attributeArray()` or `instancedArray()`,
  10673. * setup up a compute shader that writes into the buffers and then convert
  10674. * the storage buffers to attribute nodes for rendering.
  10675. *
  10676. * ```js
  10677. * const positionBuffer = instancedArray( particleCount, 'vec3' ); // the storage buffer node
  10678. *
  10679. * const computeInit = Fn( () => { // the compute shader
  10680. *
  10681. * const position = positionBuffer.element( instanceIndex );
  10682. *
  10683. * // compute position data
  10684. *
  10685. * position.x = 1;
  10686. * position.y = 1;
  10687. * position.z = 1;
  10688. *
  10689. * } )().compute( particleCount );
  10690. *
  10691. * const particleMaterial = new THREE.SpriteNodeMaterial();
  10692. * particleMaterial.positionNode = positionBuffer.toAttribute();
  10693. *
  10694. * renderer.computeAsync( computeInit );
  10695. *
  10696. * ```
  10697. *
  10698. * @augments BufferNode
  10699. */
  10700. class StorageBufferNode extends BufferNode {
  10701. static get type() {
  10702. return 'StorageBufferNode';
  10703. }
  10704. /**
  10705. * Constructs a new storage buffer node.
  10706. *
  10707. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  10708. * @param {?(string|Struct)} [bufferType=null] - The buffer type (e.g. `'vec3'`).
  10709. * @param {number} [bufferCount=0] - The buffer count.
  10710. */
  10711. constructor( value, bufferType = null, bufferCount = 0 ) {
  10712. let nodeType, structTypeNode = null;
  10713. if ( bufferType && bufferType.isStruct ) {
  10714. nodeType = 'struct';
  10715. structTypeNode = bufferType.layout;
  10716. if ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) {
  10717. bufferCount = value.count;
  10718. }
  10719. } else if ( bufferType === null && ( value.isStorageBufferAttribute || value.isStorageInstancedBufferAttribute ) ) {
  10720. nodeType = getTypeFromLength( value.itemSize );
  10721. bufferCount = value.count;
  10722. } else {
  10723. nodeType = bufferType;
  10724. }
  10725. super( value, nodeType, bufferCount );
  10726. /**
  10727. * This flag can be used for type testing.
  10728. *
  10729. * @type {boolean}
  10730. * @readonly
  10731. * @default true
  10732. */
  10733. this.isStorageBufferNode = true;
  10734. /**
  10735. * The buffer struct type.
  10736. *
  10737. * @type {?StructTypeNode}
  10738. * @default null
  10739. */
  10740. this.structTypeNode = structTypeNode;
  10741. /**
  10742. * The access type of the texture node.
  10743. *
  10744. * @type {string}
  10745. * @default 'readWrite'
  10746. */
  10747. this.access = NodeAccess.READ_WRITE;
  10748. /**
  10749. * Whether the node is atomic or not.
  10750. *
  10751. * @type {boolean}
  10752. * @default false
  10753. */
  10754. this.isAtomic = false;
  10755. /**
  10756. * Whether the node represents a PBO or not.
  10757. * Only relevant for WebGL.
  10758. *
  10759. * @type {boolean}
  10760. * @default false
  10761. */
  10762. this.isPBO = false;
  10763. /**
  10764. * A reference to the internal buffer attribute node.
  10765. *
  10766. * @type {?BufferAttributeNode}
  10767. * @default null
  10768. */
  10769. this._attribute = null;
  10770. /**
  10771. * A reference to the internal varying node.
  10772. *
  10773. * @type {?VaryingNode}
  10774. * @default null
  10775. */
  10776. this._varying = null;
  10777. /**
  10778. * `StorageBufferNode` sets this property to `true` by default.
  10779. *
  10780. * @type {boolean}
  10781. * @default true
  10782. */
  10783. this.global = true;
  10784. if ( value.isStorageBufferAttribute !== true && value.isStorageInstancedBufferAttribute !== true ) {
  10785. // TODO: Improve it, possibly adding a new property to the BufferAttribute to identify it as a storage buffer read-only attribute in Renderer
  10786. if ( value.isInstancedBufferAttribute ) value.isStorageInstancedBufferAttribute = true;
  10787. else value.isStorageBufferAttribute = true;
  10788. }
  10789. }
  10790. /**
  10791. * This method is overwritten since the buffer data might be shared
  10792. * and thus the hash should be shared as well.
  10793. *
  10794. * @param {NodeBuilder} builder - The current node builder.
  10795. * @return {string} The hash.
  10796. */
  10797. getHash( builder ) {
  10798. if ( this.bufferCount === 0 ) {
  10799. let bufferData = builder.globalCache.getData( this.value );
  10800. if ( bufferData === undefined ) {
  10801. bufferData = {
  10802. node: this
  10803. };
  10804. builder.globalCache.setData( this.value, bufferData );
  10805. }
  10806. return bufferData.node.uuid;
  10807. }
  10808. return this.uuid;
  10809. }
  10810. /**
  10811. * Overwrites the default implementation to return a fixed value `'indirectStorageBuffer'` or `'storageBuffer'`.
  10812. *
  10813. * @param {NodeBuilder} builder - The current node builder.
  10814. * @return {string} The input type.
  10815. */
  10816. getInputType( /*builder*/ ) {
  10817. return this.value.isIndirectStorageBufferAttribute ? 'indirectStorageBuffer' : 'storageBuffer';
  10818. }
  10819. /**
  10820. * Enables element access with the given index node.
  10821. *
  10822. * @param {IndexNode} indexNode - The index node.
  10823. * @return {StorageArrayElementNode} A node representing the element access.
  10824. */
  10825. element( indexNode ) {
  10826. return storageElement( this, indexNode );
  10827. }
  10828. /**
  10829. * Defines whether this node is a PBO or not. Only relevant for WebGL.
  10830. *
  10831. * @param {boolean} value - The value so set.
  10832. * @return {StorageBufferNode} A reference to this node.
  10833. */
  10834. setPBO( value ) {
  10835. this.isPBO = value;
  10836. return this;
  10837. }
  10838. /**
  10839. * Returns the `isPBO` value.
  10840. *
  10841. * @return {boolean} Whether the node represents a PBO or not.
  10842. */
  10843. getPBO() {
  10844. return this.isPBO;
  10845. }
  10846. /**
  10847. * Defines the node access.
  10848. *
  10849. * @param {string} value - The node access.
  10850. * @return {StorageBufferNode} A reference to this node.
  10851. */
  10852. setAccess( value ) {
  10853. this.access = value;
  10854. return this;
  10855. }
  10856. /**
  10857. * Convenience method for configuring a read-only node access.
  10858. *
  10859. * @return {StorageBufferNode} A reference to this node.
  10860. */
  10861. toReadOnly() {
  10862. return this.setAccess( NodeAccess.READ_ONLY );
  10863. }
  10864. /**
  10865. * Defines whether the node is atomic or not.
  10866. *
  10867. * @param {boolean} value - The atomic flag.
  10868. * @return {StorageBufferNode} A reference to this node.
  10869. */
  10870. setAtomic( value ) {
  10871. this.isAtomic = value;
  10872. return this;
  10873. }
  10874. /**
  10875. * Convenience method for making this node atomic.
  10876. *
  10877. * @return {StorageBufferNode} A reference to this node.
  10878. */
  10879. toAtomic() {
  10880. return this.setAtomic( true );
  10881. }
  10882. /**
  10883. * Returns attribute data for this storage buffer node.
  10884. *
  10885. * @return {{attribute: BufferAttributeNode, varying: VaryingNode}} The attribute data.
  10886. */
  10887. getAttributeData() {
  10888. if ( this._attribute === null ) {
  10889. this._attribute = bufferAttribute( this.value );
  10890. this._varying = varying( this._attribute );
  10891. }
  10892. return {
  10893. attribute: this._attribute,
  10894. varying: this._varying
  10895. };
  10896. }
  10897. /**
  10898. * This method is overwritten since the node type from the availability of storage buffers
  10899. * and the attribute data.
  10900. *
  10901. * @param {NodeBuilder} builder - The current node builder.
  10902. * @return {string} The node type.
  10903. */
  10904. getNodeType( builder ) {
  10905. if ( this.structTypeNode !== null ) {
  10906. return this.structTypeNode.getNodeType( builder );
  10907. }
  10908. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10909. return super.getNodeType( builder );
  10910. }
  10911. const { attribute } = this.getAttributeData();
  10912. return attribute.getNodeType( builder );
  10913. }
  10914. /**
  10915. * Returns the type of a member of the struct.
  10916. *
  10917. * @param {NodeBuilder} builder - The current node builder.
  10918. * @param {string} name - The name of the member.
  10919. * @return {string} The type of the member.
  10920. */
  10921. getMemberType( builder, name ) {
  10922. if ( this.structTypeNode !== null ) {
  10923. return this.structTypeNode.getMemberType( builder, name );
  10924. }
  10925. return 'void';
  10926. }
  10927. /**
  10928. * Generates the code snippet of the storage buffer node.
  10929. *
  10930. * @param {NodeBuilder} builder - The current node builder.
  10931. * @return {string} The generated code snippet.
  10932. */
  10933. generate( builder ) {
  10934. if ( this.structTypeNode !== null ) this.structTypeNode.build( builder );
  10935. if ( builder.isAvailable( 'storageBuffer' ) || builder.isAvailable( 'indirectStorageBuffer' ) ) {
  10936. return super.generate( builder );
  10937. }
  10938. const { attribute, varying } = this.getAttributeData();
  10939. const output = varying.build( builder );
  10940. builder.registerTransform( output, attribute );
  10941. return output;
  10942. }
  10943. }
  10944. /**
  10945. * TSL function for creating a storage buffer node.
  10946. *
  10947. * @tsl
  10948. * @function
  10949. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  10950. * @param {?(string|Struct)} [type=null] - The buffer type (e.g. `'vec3'`).
  10951. * @param {number} [count=0] - The buffer count.
  10952. * @returns {StorageBufferNode}
  10953. */
  10954. const storage = ( value, type = null, count = 0 ) => nodeObject( new StorageBufferNode( value, type, count ) );
  10955. /**
  10956. * @tsl
  10957. * @function
  10958. * @deprecated since r171. Use `storage().setPBO( true )` instead.
  10959. *
  10960. * @param {StorageBufferAttribute|StorageInstancedBufferAttribute|BufferAttribute} value - The buffer data.
  10961. * @param {?string} type - The buffer type (e.g. `'vec3'`).
  10962. * @param {number} count - The buffer count.
  10963. * @returns {StorageBufferNode}
  10964. */
  10965. const storageObject = ( value, type, count ) => { // @deprecated, r171
  10966. console.warn( 'THREE.TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.' );
  10967. return storage( value, type, count ).setPBO( true );
  10968. };
  10969. const _frameId = new WeakMap();
  10970. /**
  10971. * This node implements the vertex transformation shader logic which is required
  10972. * for skinning/skeletal animation.
  10973. *
  10974. * @augments Node
  10975. */
  10976. class SkinningNode extends Node {
  10977. static get type() {
  10978. return 'SkinningNode';
  10979. }
  10980. /**
  10981. * Constructs a new skinning node.
  10982. *
  10983. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  10984. */
  10985. constructor( skinnedMesh ) {
  10986. super( 'void' );
  10987. /**
  10988. * The skinned mesh.
  10989. *
  10990. * @type {SkinnedMesh}
  10991. */
  10992. this.skinnedMesh = skinnedMesh;
  10993. /**
  10994. * The update type overwritten since skinning nodes are updated per object.
  10995. *
  10996. * @type {string}
  10997. */
  10998. this.updateType = NodeUpdateType.OBJECT;
  10999. //
  11000. /**
  11001. * The skin index attribute.
  11002. *
  11003. * @type {AttributeNode}
  11004. */
  11005. this.skinIndexNode = attribute( 'skinIndex', 'uvec4' );
  11006. /**
  11007. * The skin weight attribute.
  11008. *
  11009. * @type {AttributeNode}
  11010. */
  11011. this.skinWeightNode = attribute( 'skinWeight', 'vec4' );
  11012. /**
  11013. * The bind matrix node.
  11014. *
  11015. * @type {Node<mat4>}
  11016. */
  11017. this.bindMatrixNode = reference( 'bindMatrix', 'mat4' );
  11018. /**
  11019. * The bind matrix inverse node.
  11020. *
  11021. * @type {Node<mat4>}
  11022. */
  11023. this.bindMatrixInverseNode = reference( 'bindMatrixInverse', 'mat4' );
  11024. /**
  11025. * The bind matrices as a uniform buffer node.
  11026. *
  11027. * @type {Node}
  11028. */
  11029. this.boneMatricesNode = referenceBuffer( 'skeleton.boneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11030. /**
  11031. * The current vertex position in local space.
  11032. *
  11033. * @type {Node<vec3>}
  11034. */
  11035. this.positionNode = positionLocal;
  11036. /**
  11037. * The result of vertex position in local space.
  11038. *
  11039. * @type {Node<vec3>}
  11040. */
  11041. this.toPositionNode = positionLocal;
  11042. /**
  11043. * The previous bind matrices as a uniform buffer node.
  11044. * Required for computing motion vectors.
  11045. *
  11046. * @type {?Node}
  11047. * @default null
  11048. */
  11049. this.previousBoneMatricesNode = null;
  11050. }
  11051. /**
  11052. * Transforms the given vertex position via skinning.
  11053. *
  11054. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11055. * @param {Node<vec3>} [position=this.positionNode] - The vertex position in local space.
  11056. * @return {Node<vec3>} The transformed vertex position.
  11057. */
  11058. getSkinnedPosition( boneMatrices = this.boneMatricesNode, position = this.positionNode ) {
  11059. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11060. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11061. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11062. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11063. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11064. // POSITION
  11065. const skinVertex = bindMatrixNode.mul( position );
  11066. const skinned = add(
  11067. boneMatX.mul( skinWeightNode.x ).mul( skinVertex ),
  11068. boneMatY.mul( skinWeightNode.y ).mul( skinVertex ),
  11069. boneMatZ.mul( skinWeightNode.z ).mul( skinVertex ),
  11070. boneMatW.mul( skinWeightNode.w ).mul( skinVertex )
  11071. );
  11072. return bindMatrixInverseNode.mul( skinned ).xyz;
  11073. }
  11074. /**
  11075. * Transforms the given vertex normal via skinning.
  11076. *
  11077. * @param {Node} [boneMatrices=this.boneMatricesNode] - The bone matrices
  11078. * @param {Node<vec3>} [normal=normalLocal] - The vertex normal in local space.
  11079. * @return {Node<vec3>} The transformed vertex normal.
  11080. */
  11081. getSkinnedNormal( boneMatrices = this.boneMatricesNode, normal = normalLocal ) {
  11082. const { skinIndexNode, skinWeightNode, bindMatrixNode, bindMatrixInverseNode } = this;
  11083. const boneMatX = boneMatrices.element( skinIndexNode.x );
  11084. const boneMatY = boneMatrices.element( skinIndexNode.y );
  11085. const boneMatZ = boneMatrices.element( skinIndexNode.z );
  11086. const boneMatW = boneMatrices.element( skinIndexNode.w );
  11087. // NORMAL
  11088. let skinMatrix = add(
  11089. skinWeightNode.x.mul( boneMatX ),
  11090. skinWeightNode.y.mul( boneMatY ),
  11091. skinWeightNode.z.mul( boneMatZ ),
  11092. skinWeightNode.w.mul( boneMatW )
  11093. );
  11094. skinMatrix = bindMatrixInverseNode.mul( skinMatrix ).mul( bindMatrixNode );
  11095. return skinMatrix.transformDirection( normal ).xyz;
  11096. }
  11097. /**
  11098. * Computes the transformed/skinned vertex position of the previous frame.
  11099. *
  11100. * @param {NodeBuilder} builder - The current node builder.
  11101. * @return {Node<vec3>} The skinned position from the previous frame.
  11102. */
  11103. getPreviousSkinnedPosition( builder ) {
  11104. const skinnedMesh = builder.object;
  11105. if ( this.previousBoneMatricesNode === null ) {
  11106. skinnedMesh.skeleton.previousBoneMatrices = new Float32Array( skinnedMesh.skeleton.boneMatrices );
  11107. this.previousBoneMatricesNode = referenceBuffer( 'skeleton.previousBoneMatrices', 'mat4', skinnedMesh.skeleton.bones.length );
  11108. }
  11109. return this.getSkinnedPosition( this.previousBoneMatricesNode, positionPrevious );
  11110. }
  11111. /**
  11112. * Returns `true` if bone matrices from the previous frame are required. Relevant
  11113. * when computing motion vectors with {@link VelocityNode}.
  11114. *
  11115. * @param {NodeBuilder} builder - The current node builder.
  11116. * @return {boolean} Whether bone matrices from the previous frame are required or not.
  11117. */
  11118. needsPreviousBoneMatrices( builder ) {
  11119. const mrt = builder.renderer.getMRT();
  11120. return ( mrt && mrt.has( 'velocity' ) ) || getDataFromObject( builder.object ).useVelocity === true;
  11121. }
  11122. /**
  11123. * Setups the skinning node by assigning the transformed vertex data to predefined node variables.
  11124. *
  11125. * @param {NodeBuilder} builder - The current node builder.
  11126. * @return {Node<vec3>} The transformed vertex position.
  11127. */
  11128. setup( builder ) {
  11129. if ( this.needsPreviousBoneMatrices( builder ) ) {
  11130. positionPrevious.assign( this.getPreviousSkinnedPosition( builder ) );
  11131. }
  11132. const skinPosition = this.getSkinnedPosition();
  11133. if ( this.toPositionNode ) this.toPositionNode.assign( skinPosition );
  11134. //
  11135. if ( builder.hasGeometryAttribute( 'normal' ) ) {
  11136. const skinNormal = this.getSkinnedNormal();
  11137. normalLocal.assign( skinNormal );
  11138. if ( builder.hasGeometryAttribute( 'tangent' ) ) {
  11139. tangentLocal.assign( skinNormal );
  11140. }
  11141. }
  11142. return skinPosition;
  11143. }
  11144. /**
  11145. * Generates the code snippet of the skinning node.
  11146. *
  11147. * @param {NodeBuilder} builder - The current node builder.
  11148. * @param {string} output - The current output.
  11149. * @return {string} The generated code snippet.
  11150. */
  11151. generate( builder, output ) {
  11152. if ( output !== 'void' ) {
  11153. return super.generate( builder, output );
  11154. }
  11155. }
  11156. /**
  11157. * Updates the state of the skinned mesh by updating the skeleton once per frame.
  11158. *
  11159. * @param {NodeFrame} frame - The current node frame.
  11160. */
  11161. update( frame ) {
  11162. const skeleton = frame.object && frame.object.skeleton ? frame.object.skeleton : this.skinnedMesh.skeleton;
  11163. if ( _frameId.get( skeleton ) === frame.frameId ) return;
  11164. _frameId.set( skeleton, frame.frameId );
  11165. if ( this.previousBoneMatricesNode !== null ) skeleton.previousBoneMatrices.set( skeleton.boneMatrices );
  11166. skeleton.update();
  11167. }
  11168. }
  11169. /**
  11170. * TSL function for creating a skinning node.
  11171. *
  11172. * @tsl
  11173. * @function
  11174. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11175. * @returns {SkinningNode}
  11176. */
  11177. const skinning = ( skinnedMesh ) => nodeObject( new SkinningNode( skinnedMesh ) );
  11178. /**
  11179. * TSL function for computing skinning.
  11180. *
  11181. * @tsl
  11182. * @function
  11183. * @param {SkinnedMesh} skinnedMesh - The skinned mesh.
  11184. * @param {Node<vec3>} [toPosition=null] - The target position.
  11185. * @returns {SkinningNode}
  11186. */
  11187. const computeSkinning = ( skinnedMesh, toPosition = null ) => {
  11188. const node = new SkinningNode( skinnedMesh );
  11189. node.positionNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'position' ).array, 3 ), 'vec3' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11190. node.skinIndexNode = storage( new InstancedBufferAttribute( new Uint32Array( skinnedMesh.geometry.getAttribute( 'skinIndex' ).array ), 4 ), 'uvec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11191. node.skinWeightNode = storage( new InstancedBufferAttribute( skinnedMesh.geometry.getAttribute( 'skinWeight' ).array, 4 ), 'vec4' ).setPBO( true ).toReadOnly().element( instanceIndex ).toVar();
  11192. node.bindMatrixNode = uniform( skinnedMesh.bindMatrix, 'mat4' );
  11193. node.bindMatrixInverseNode = uniform( skinnedMesh.bindMatrixInverse, 'mat4' );
  11194. node.boneMatricesNode = buffer( skinnedMesh.skeleton.boneMatrices, 'mat4', skinnedMesh.skeleton.bones.length );
  11195. node.toPositionNode = toPosition;
  11196. return nodeObject( node );
  11197. };
  11198. /**
  11199. * This module offers a variety of ways to implement loops in TSL. In it's basic form it's:
  11200. * ```js
  11201. * Loop( count, ( { i } ) => {
  11202. *
  11203. * } );
  11204. * ```
  11205. * However, it is also possible to define a start and end ranges, data types and loop conditions:
  11206. * ```js
  11207. * Loop( { start: int( 0 ), end: int( 10 ), type: 'int', condition: '<' }, ( { i } ) => {
  11208. *
  11209. * } );
  11210. *```
  11211. * Nested loops can be defined in a compacted form:
  11212. * ```js
  11213. * Loop( 10, 5, ( { i, j } ) => {
  11214. *
  11215. * } );
  11216. * ```
  11217. * Loops that should run backwards can be defined like so:
  11218. * ```js
  11219. * Loop( { start: 10 }, () => {} );
  11220. * ```
  11221. * It is possible to execute with boolean values, similar to the `while` syntax.
  11222. * ```js
  11223. * const value = float( 0 ).toVar();
  11224. *
  11225. * Loop( value.lessThan( 10 ), () => {
  11226. *
  11227. * value.addAssign( 1 );
  11228. *
  11229. * } );
  11230. * ```
  11231. * The module also provides `Break()` and `Continue()` TSL expression for loop control.
  11232. * @augments Node
  11233. */
  11234. class LoopNode extends Node {
  11235. static get type() {
  11236. return 'LoopNode';
  11237. }
  11238. /**
  11239. * Constructs a new loop node.
  11240. *
  11241. * @param {Array<any>} params - Depending on the loop type, array holds different parameterization values for the loop.
  11242. */
  11243. constructor( params = [] ) {
  11244. super();
  11245. this.params = params;
  11246. }
  11247. /**
  11248. * Returns a loop variable name based on an index. The pattern is
  11249. * `0` = `i`, `1`= `j`, `2`= `k` and so on.
  11250. *
  11251. * @param {number} index - The index.
  11252. * @return {string} The loop variable name.
  11253. */
  11254. getVarName( index ) {
  11255. return String.fromCharCode( 'i'.charCodeAt( 0 ) + index );
  11256. }
  11257. /**
  11258. * Returns properties about this node.
  11259. *
  11260. * @param {NodeBuilder} builder - The current node builder.
  11261. * @return {Object} The node properties.
  11262. */
  11263. getProperties( builder ) {
  11264. const properties = builder.getNodeProperties( this );
  11265. if ( properties.stackNode !== undefined ) return properties;
  11266. //
  11267. const inputs = {};
  11268. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  11269. const param = this.params[ i ];
  11270. const name = ( param.isNode !== true && param.name ) || this.getVarName( i );
  11271. const type = ( param.isNode !== true && param.type ) || 'int';
  11272. inputs[ name ] = expression( name, type );
  11273. }
  11274. const stack = builder.addStack(); // TODO: cache() it
  11275. properties.returnsNode = this.params[ this.params.length - 1 ]( inputs, builder );
  11276. properties.stackNode = stack;
  11277. const baseParam = this.params[ 0 ];
  11278. if ( baseParam.isNode !== true && typeof baseParam.update === 'function' ) {
  11279. properties.updateNode = Fn( this.params[ 0 ].update )( inputs );
  11280. }
  11281. builder.removeStack();
  11282. return properties;
  11283. }
  11284. /**
  11285. * This method is overwritten since the node type is inferred based on the loop configuration.
  11286. *
  11287. * @param {NodeBuilder} builder - The current node builder.
  11288. * @return {string} The node type.
  11289. */
  11290. getNodeType( builder ) {
  11291. const { returnsNode } = this.getProperties( builder );
  11292. return returnsNode ? returnsNode.getNodeType( builder ) : 'void';
  11293. }
  11294. setup( builder ) {
  11295. // setup properties
  11296. this.getProperties( builder );
  11297. }
  11298. generate( builder ) {
  11299. const properties = this.getProperties( builder );
  11300. const params = this.params;
  11301. const stackNode = properties.stackNode;
  11302. for ( let i = 0, l = params.length - 1; i < l; i ++ ) {
  11303. const param = params[ i ];
  11304. let isWhile = false, start = null, end = null, name = null, type = null, condition = null, update = null;
  11305. if ( param.isNode ) {
  11306. if ( param.getNodeType( builder ) === 'bool' ) {
  11307. isWhile = true;
  11308. type = 'bool';
  11309. end = param.build( builder, type );
  11310. } else {
  11311. type = 'int';
  11312. name = this.getVarName( i );
  11313. start = '0';
  11314. end = param.build( builder, type );
  11315. condition = '<';
  11316. }
  11317. } else {
  11318. type = param.type || 'int';
  11319. name = param.name || this.getVarName( i );
  11320. start = param.start;
  11321. end = param.end;
  11322. condition = param.condition;
  11323. update = param.update;
  11324. if ( typeof start === 'number' ) start = builder.generateConst( type, start );
  11325. else if ( start && start.isNode ) start = start.build( builder, type );
  11326. if ( typeof end === 'number' ) end = builder.generateConst( type, end );
  11327. else if ( end && end.isNode ) end = end.build( builder, type );
  11328. if ( start !== undefined && end === undefined ) {
  11329. start = start + ' - 1';
  11330. end = '0';
  11331. condition = '>=';
  11332. } else if ( end !== undefined && start === undefined ) {
  11333. start = '0';
  11334. condition = '<';
  11335. }
  11336. if ( condition === undefined ) {
  11337. if ( Number( start ) > Number( end ) ) {
  11338. condition = '>=';
  11339. } else {
  11340. condition = '<';
  11341. }
  11342. }
  11343. }
  11344. let loopSnippet;
  11345. if ( isWhile ) {
  11346. loopSnippet = `while ( ${ end } )`;
  11347. } else {
  11348. const internalParam = { start, end};
  11349. //
  11350. const startSnippet = internalParam.start;
  11351. const endSnippet = internalParam.end;
  11352. let updateSnippet;
  11353. const deltaOperator = () => condition.includes( '<' ) ? '+=' : '-=';
  11354. if ( update !== undefined && update !== null ) {
  11355. switch ( typeof update ) {
  11356. case 'function':
  11357. const flow = builder.flowStagesNode( properties.updateNode, 'void' );
  11358. const snippet = flow.code.replace( /\t|;/g, '' );
  11359. updateSnippet = snippet;
  11360. break;
  11361. case 'number':
  11362. updateSnippet = name + ' ' + deltaOperator() + ' ' + builder.generateConst( type, update );
  11363. break;
  11364. case 'string':
  11365. updateSnippet = name + ' ' + update;
  11366. break;
  11367. default:
  11368. if ( update.isNode ) {
  11369. updateSnippet = name + ' ' + deltaOperator() + ' ' + update.build( builder );
  11370. } else {
  11371. console.error( 'THREE.TSL: \'Loop( { update: ... } )\' is not a function, string or number.' );
  11372. updateSnippet = 'break /* invalid update */';
  11373. }
  11374. }
  11375. } else {
  11376. if ( type === 'int' || type === 'uint' ) {
  11377. update = condition.includes( '<' ) ? '++' : '--';
  11378. } else {
  11379. update = deltaOperator() + ' 1.';
  11380. }
  11381. updateSnippet = name + ' ' + update;
  11382. }
  11383. const declarationSnippet = builder.getVar( type, name ) + ' = ' + startSnippet;
  11384. const conditionalSnippet = name + ' ' + condition + ' ' + endSnippet;
  11385. loopSnippet = `for ( ${ declarationSnippet }; ${ conditionalSnippet }; ${ updateSnippet } )`;
  11386. }
  11387. builder.addFlowCode( ( i === 0 ? '\n' : '' ) + builder.tab + loopSnippet + ' {\n\n' ).addFlowTab();
  11388. }
  11389. const stackSnippet = stackNode.build( builder, 'void' );
  11390. const returnsSnippet = properties.returnsNode ? properties.returnsNode.build( builder ) : '';
  11391. builder.removeFlowTab().addFlowCode( '\n' + builder.tab + stackSnippet );
  11392. for ( let i = 0, l = this.params.length - 1; i < l; i ++ ) {
  11393. builder.addFlowCode( ( i === 0 ? '' : builder.tab ) + '}\n\n' ).removeFlowTab();
  11394. }
  11395. builder.addFlowTab();
  11396. return returnsSnippet;
  11397. }
  11398. }
  11399. /**
  11400. * TSL function for creating a loop node.
  11401. *
  11402. * @tsl
  11403. * @function
  11404. * @param {...any} params - A list of parameters.
  11405. * @returns {LoopNode}
  11406. */
  11407. const Loop = ( ...params ) => nodeObject( new LoopNode( nodeArray( params, 'int' ) ) ).toStack();
  11408. /**
  11409. * TSL function for creating a `Continue()` expression.
  11410. *
  11411. * @tsl
  11412. * @function
  11413. * @returns {ExpressionNode}
  11414. */
  11415. const Continue = () => expression( 'continue' ).toStack();
  11416. /**
  11417. * TSL function for creating a `Break()` expression.
  11418. *
  11419. * @tsl
  11420. * @function
  11421. * @returns {ExpressionNode}
  11422. */
  11423. const Break = () => expression( 'break' ).toStack();
  11424. // Deprecated
  11425. /**
  11426. * @tsl
  11427. * @function
  11428. * @deprecated since r168. Use {@link Loop} instead.
  11429. *
  11430. * @param {...any} params
  11431. * @returns {LoopNode}
  11432. */
  11433. const loop = ( ...params ) => { // @deprecated, r168
  11434. console.warn( 'THREE.TSL: loop() has been renamed to Loop().' );
  11435. return Loop( ...params );
  11436. };
  11437. const _morphTextures = /*@__PURE__*/ new WeakMap();
  11438. const _morphVec4 = /*@__PURE__*/ new Vector4();
  11439. const getMorph = /*@__PURE__*/ Fn( ( { bufferMap, influence, stride, width, depth, offset } ) => {
  11440. const texelIndex = int( vertexIndex ).mul( stride ).add( offset );
  11441. const y = texelIndex.div( width );
  11442. const x = texelIndex.sub( y.mul( width ) );
  11443. const bufferAttrib = textureLoad( bufferMap, ivec2( x, y ) ).depth( depth ).xyz;
  11444. return bufferAttrib.mul( influence );
  11445. } );
  11446. function getEntry( geometry ) {
  11447. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  11448. const hasMorphNormals = geometry.morphAttributes.normal !== undefined;
  11449. const hasMorphColors = geometry.morphAttributes.color !== undefined;
  11450. // instead of using attributes, the WebGL 2 code path encodes morph targets
  11451. // into an array of data textures. Each layer represents a single morph target.
  11452. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11453. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11454. let entry = _morphTextures.get( geometry );
  11455. if ( entry === undefined || entry.count !== morphTargetsCount ) {
  11456. if ( entry !== undefined ) entry.texture.dispose();
  11457. const morphTargets = geometry.morphAttributes.position || [];
  11458. const morphNormals = geometry.morphAttributes.normal || [];
  11459. const morphColors = geometry.morphAttributes.color || [];
  11460. let vertexDataCount = 0;
  11461. if ( hasMorphPosition === true ) vertexDataCount = 1;
  11462. if ( hasMorphNormals === true ) vertexDataCount = 2;
  11463. if ( hasMorphColors === true ) vertexDataCount = 3;
  11464. let width = geometry.attributes.position.count * vertexDataCount;
  11465. let height = 1;
  11466. const maxTextureSize = 4096; // @TODO: Use 'capabilities.maxTextureSize'
  11467. if ( width > maxTextureSize ) {
  11468. height = Math.ceil( width / maxTextureSize );
  11469. width = maxTextureSize;
  11470. }
  11471. const buffer = new Float32Array( width * height * 4 * morphTargetsCount );
  11472. const bufferTexture = new DataArrayTexture( buffer, width, height, morphTargetsCount );
  11473. bufferTexture.type = FloatType;
  11474. bufferTexture.needsUpdate = true;
  11475. // fill buffer
  11476. const vertexDataStride = vertexDataCount * 4;
  11477. for ( let i = 0; i < morphTargetsCount; i ++ ) {
  11478. const morphTarget = morphTargets[ i ];
  11479. const morphNormal = morphNormals[ i ];
  11480. const morphColor = morphColors[ i ];
  11481. const offset = width * height * 4 * i;
  11482. for ( let j = 0; j < morphTarget.count; j ++ ) {
  11483. const stride = j * vertexDataStride;
  11484. if ( hasMorphPosition === true ) {
  11485. _morphVec4.fromBufferAttribute( morphTarget, j );
  11486. buffer[ offset + stride + 0 ] = _morphVec4.x;
  11487. buffer[ offset + stride + 1 ] = _morphVec4.y;
  11488. buffer[ offset + stride + 2 ] = _morphVec4.z;
  11489. buffer[ offset + stride + 3 ] = 0;
  11490. }
  11491. if ( hasMorphNormals === true ) {
  11492. _morphVec4.fromBufferAttribute( morphNormal, j );
  11493. buffer[ offset + stride + 4 ] = _morphVec4.x;
  11494. buffer[ offset + stride + 5 ] = _morphVec4.y;
  11495. buffer[ offset + stride + 6 ] = _morphVec4.z;
  11496. buffer[ offset + stride + 7 ] = 0;
  11497. }
  11498. if ( hasMorphColors === true ) {
  11499. _morphVec4.fromBufferAttribute( morphColor, j );
  11500. buffer[ offset + stride + 8 ] = _morphVec4.x;
  11501. buffer[ offset + stride + 9 ] = _morphVec4.y;
  11502. buffer[ offset + stride + 10 ] = _morphVec4.z;
  11503. buffer[ offset + stride + 11 ] = ( morphColor.itemSize === 4 ) ? _morphVec4.w : 1;
  11504. }
  11505. }
  11506. }
  11507. entry = {
  11508. count: morphTargetsCount,
  11509. texture: bufferTexture,
  11510. stride: vertexDataCount,
  11511. size: new Vector2( width, height )
  11512. };
  11513. _morphTextures.set( geometry, entry );
  11514. function disposeTexture() {
  11515. bufferTexture.dispose();
  11516. _morphTextures.delete( geometry );
  11517. geometry.removeEventListener( 'dispose', disposeTexture );
  11518. }
  11519. geometry.addEventListener( 'dispose', disposeTexture );
  11520. }
  11521. return entry;
  11522. }
  11523. /**
  11524. * This node implements the vertex transformation shader logic which is required
  11525. * for morph target animation.
  11526. *
  11527. * @augments Node
  11528. */
  11529. class MorphNode extends Node {
  11530. static get type() {
  11531. return 'MorphNode';
  11532. }
  11533. /**
  11534. * Constructs a new morph node.
  11535. *
  11536. * @param {Mesh} mesh - The mesh holding the morph targets.
  11537. */
  11538. constructor( mesh ) {
  11539. super( 'void' );
  11540. /**
  11541. * The mesh holding the morph targets.
  11542. *
  11543. * @type {Mesh}
  11544. */
  11545. this.mesh = mesh;
  11546. /**
  11547. * A uniform node which represents the morph base influence value.
  11548. *
  11549. * @type {UniformNode<float>}
  11550. */
  11551. this.morphBaseInfluence = uniform( 1 );
  11552. /**
  11553. * The update type overwritten since morph nodes are updated per object.
  11554. *
  11555. * @type {string}
  11556. */
  11557. this.updateType = NodeUpdateType.OBJECT;
  11558. }
  11559. /**
  11560. * Setups the morph node by assigning the transformed vertex data to predefined node variables.
  11561. *
  11562. * @param {NodeBuilder} builder - The current node builder.
  11563. */
  11564. setup( builder ) {
  11565. const { geometry } = builder;
  11566. const hasMorphPosition = geometry.morphAttributes.position !== undefined;
  11567. const hasMorphNormals = geometry.hasAttribute( 'normal' ) && geometry.morphAttributes.normal !== undefined;
  11568. const morphAttribute = geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color;
  11569. const morphTargetsCount = ( morphAttribute !== undefined ) ? morphAttribute.length : 0;
  11570. // nodes
  11571. const { texture: bufferMap, stride, size } = getEntry( geometry );
  11572. if ( hasMorphPosition === true ) positionLocal.mulAssign( this.morphBaseInfluence );
  11573. if ( hasMorphNormals === true ) normalLocal.mulAssign( this.morphBaseInfluence );
  11574. const width = int( size.width );
  11575. Loop( morphTargetsCount, ( { i } ) => {
  11576. const influence = float( 0 ).toVar();
  11577. if ( this.mesh.count > 1 && ( this.mesh.morphTexture !== null && this.mesh.morphTexture !== undefined ) ) {
  11578. influence.assign( textureLoad( this.mesh.morphTexture, ivec2( int( i ).add( 1 ), int( instanceIndex ) ) ).r );
  11579. } else {
  11580. influence.assign( reference( 'morphTargetInfluences', 'float' ).element( i ).toVar() );
  11581. }
  11582. If( influence.notEqual( 0 ), () => {
  11583. if ( hasMorphPosition === true ) {
  11584. positionLocal.addAssign( getMorph( {
  11585. bufferMap,
  11586. influence,
  11587. stride,
  11588. width,
  11589. depth: i,
  11590. offset: int( 0 )
  11591. } ) );
  11592. }
  11593. if ( hasMorphNormals === true ) {
  11594. normalLocal.addAssign( getMorph( {
  11595. bufferMap,
  11596. influence,
  11597. stride,
  11598. width,
  11599. depth: i,
  11600. offset: int( 1 )
  11601. } ) );
  11602. }
  11603. } );
  11604. } );
  11605. }
  11606. /**
  11607. * Updates the state of the morphed mesh by updating the base influence.
  11608. *
  11609. * @param {NodeFrame} frame - The current node frame.
  11610. */
  11611. update( /*frame*/ ) {
  11612. const morphBaseInfluence = this.morphBaseInfluence;
  11613. if ( this.mesh.geometry.morphTargetsRelative ) {
  11614. morphBaseInfluence.value = 1;
  11615. } else {
  11616. morphBaseInfluence.value = 1 - this.mesh.morphTargetInfluences.reduce( ( a, b ) => a + b, 0 );
  11617. }
  11618. }
  11619. }
  11620. /**
  11621. * TSL function for creating a morph node.
  11622. *
  11623. * @tsl
  11624. * @function
  11625. * @param {Mesh} mesh - The mesh holding the morph targets.
  11626. * @returns {MorphNode}
  11627. */
  11628. const morphReference = /*@__PURE__*/ nodeProxy( MorphNode ).setParameterLength( 1 );
  11629. /**
  11630. * Base class for lighting nodes.
  11631. *
  11632. * @augments Node
  11633. */
  11634. class LightingNode extends Node {
  11635. static get type() {
  11636. return 'LightingNode';
  11637. }
  11638. /**
  11639. * Constructs a new lighting node.
  11640. */
  11641. constructor() {
  11642. super( 'vec3' );
  11643. /**
  11644. * This flag can be used for type testing.
  11645. *
  11646. * @type {boolean}
  11647. * @readonly
  11648. * @default true
  11649. */
  11650. this.isLightingNode = true;
  11651. }
  11652. }
  11653. /**
  11654. * A generic class that can be used by nodes which contribute
  11655. * ambient occlusion to the scene. E.g. an ambient occlusion map
  11656. * node can be used as input for this module. Used in {@link NodeMaterial}.
  11657. *
  11658. * @augments LightingNode
  11659. */
  11660. class AONode extends LightingNode {
  11661. static get type() {
  11662. return 'AONode';
  11663. }
  11664. /**
  11665. * Constructs a new AO node.
  11666. *
  11667. * @param {?Node<float>} [aoNode=null] - The ambient occlusion node.
  11668. */
  11669. constructor( aoNode = null ) {
  11670. super();
  11671. /**
  11672. * The ambient occlusion node.
  11673. *
  11674. * @type {?Node<float>}
  11675. * @default null
  11676. */
  11677. this.aoNode = aoNode;
  11678. }
  11679. setup( builder ) {
  11680. builder.context.ambientOcclusion.mulAssign( this.aoNode );
  11681. }
  11682. }
  11683. /**
  11684. * `LightingContextNode` represents an extension of the {@link ContextNode} module
  11685. * by adding lighting specific context data. It represents the runtime context of
  11686. * {@link LightsNode}.
  11687. *
  11688. * @augments ContextNode
  11689. */
  11690. class LightingContextNode extends ContextNode {
  11691. static get type() {
  11692. return 'LightingContextNode';
  11693. }
  11694. /**
  11695. * Constructs a new lighting context node.
  11696. *
  11697. * @param {LightsNode} lightsNode - The lights node.
  11698. * @param {?LightingModel} [lightingModel=null] - The current lighting model.
  11699. * @param {?Node<vec3>} [backdropNode=null] - A backdrop node.
  11700. * @param {?Node<float>} [backdropAlphaNode=null] - A backdrop alpha node.
  11701. */
  11702. constructor( lightsNode, lightingModel = null, backdropNode = null, backdropAlphaNode = null ) {
  11703. super( lightsNode );
  11704. /**
  11705. * The current lighting model.
  11706. *
  11707. * @type {?LightingModel}
  11708. * @default null
  11709. */
  11710. this.lightingModel = lightingModel;
  11711. /**
  11712. * A backdrop node.
  11713. *
  11714. * @type {?Node<vec3>}
  11715. * @default null
  11716. */
  11717. this.backdropNode = backdropNode;
  11718. /**
  11719. * A backdrop alpha node.
  11720. *
  11721. * @type {?Node<float>}
  11722. * @default null
  11723. */
  11724. this.backdropAlphaNode = backdropAlphaNode;
  11725. this._value = null;
  11726. }
  11727. /**
  11728. * Returns a lighting context object.
  11729. *
  11730. * @return {{
  11731. * radiance: Node<vec3>,
  11732. * irradiance: Node<vec3>,
  11733. * iblIrradiance: Node<vec3>,
  11734. * ambientOcclusion: Node<float>,
  11735. * reflectedLight: {directDiffuse: Node<vec3>, directSpecular: Node<vec3>, indirectDiffuse: Node<vec3>, indirectSpecular: Node<vec3>},
  11736. * backdrop: Node<vec3>,
  11737. * backdropAlpha: Node<float>
  11738. * }} The lighting context object.
  11739. */
  11740. getContext() {
  11741. const { backdropNode, backdropAlphaNode } = this;
  11742. const directDiffuse = vec3().toVar( 'directDiffuse' ),
  11743. directSpecular = vec3().toVar( 'directSpecular' ),
  11744. indirectDiffuse = vec3().toVar( 'indirectDiffuse' ),
  11745. indirectSpecular = vec3().toVar( 'indirectSpecular' );
  11746. const reflectedLight = {
  11747. directDiffuse,
  11748. directSpecular,
  11749. indirectDiffuse,
  11750. indirectSpecular
  11751. };
  11752. const context = {
  11753. radiance: vec3().toVar( 'radiance' ),
  11754. irradiance: vec3().toVar( 'irradiance' ),
  11755. iblIrradiance: vec3().toVar( 'iblIrradiance' ),
  11756. ambientOcclusion: float( 1 ).toVar( 'ambientOcclusion' ),
  11757. reflectedLight,
  11758. backdrop: backdropNode,
  11759. backdropAlpha: backdropAlphaNode
  11760. };
  11761. return context;
  11762. }
  11763. setup( builder ) {
  11764. this.value = this._value || ( this._value = this.getContext() );
  11765. this.value.lightingModel = this.lightingModel || builder.context.lightingModel;
  11766. return super.setup( builder );
  11767. }
  11768. }
  11769. const lightingContext = /*@__PURE__*/ nodeProxy( LightingContextNode );
  11770. /**
  11771. * A generic class that can be used by nodes which contribute
  11772. * irradiance to the scene. E.g. a light map node can be used
  11773. * as input for this module. Used in {@link NodeMaterial}.
  11774. *
  11775. * @augments LightingNode
  11776. */
  11777. class IrradianceNode extends LightingNode {
  11778. static get type() {
  11779. return 'IrradianceNode';
  11780. }
  11781. /**
  11782. * Constructs a new irradiance node.
  11783. *
  11784. * @param {Node<vec3>} node - A node contributing irradiance.
  11785. */
  11786. constructor( node ) {
  11787. super();
  11788. /**
  11789. * A node contributing irradiance.
  11790. *
  11791. * @type {Node<vec3>}
  11792. */
  11793. this.node = node;
  11794. }
  11795. setup( builder ) {
  11796. builder.context.irradiance.addAssign( this.node );
  11797. }
  11798. }
  11799. let screenSizeVec, viewportVec;
  11800. /**
  11801. * This node provides a collection of screen related metrics.
  11802. * Depending on {@link ScreenNode#scope}, the nodes can represent
  11803. * resolution or viewport data as well as fragment or uv coordinates.
  11804. *
  11805. * @augments Node
  11806. */
  11807. class ScreenNode extends Node {
  11808. static get type() {
  11809. return 'ScreenNode';
  11810. }
  11811. /**
  11812. * Constructs a new screen node.
  11813. *
  11814. * @param {('coordinate'|'viewport'|'size'|'uv')} scope - The node's scope.
  11815. */
  11816. constructor( scope ) {
  11817. super();
  11818. /**
  11819. * The node represents different metric depending on which scope is selected.
  11820. *
  11821. * - `ScreenNode.COORDINATE`: Window-relative coordinates of the current fragment according to WebGPU standards.
  11822. * - `ScreenNode.VIEWPORT`: The current viewport defined as a four-dimensional vector.
  11823. * - `ScreenNode.SIZE`: The dimensions of the current bound framebuffer.
  11824. * - `ScreenNode.UV`: Normalized coordinates.
  11825. *
  11826. * @type {('coordinate'|'viewport'|'size'|'uv')}
  11827. */
  11828. this.scope = scope;
  11829. /**
  11830. * This flag can be used for type testing.
  11831. *
  11832. * @type {boolean}
  11833. * @readonly
  11834. * @default true
  11835. */
  11836. this.isViewportNode = true;
  11837. }
  11838. /**
  11839. * This method is overwritten since the node type depends on the selected scope.
  11840. *
  11841. * @return {('vec2'|'vec4')} The node type.
  11842. */
  11843. getNodeType() {
  11844. if ( this.scope === ScreenNode.VIEWPORT ) return 'vec4';
  11845. else return 'vec2';
  11846. }
  11847. /**
  11848. * This method is overwritten since the node's update type depends on the selected scope.
  11849. *
  11850. * @return {NodeUpdateType} The update type.
  11851. */
  11852. getUpdateType() {
  11853. let updateType = NodeUpdateType.NONE;
  11854. if ( this.scope === ScreenNode.SIZE || this.scope === ScreenNode.VIEWPORT ) {
  11855. updateType = NodeUpdateType.RENDER;
  11856. }
  11857. this.updateType = updateType;
  11858. return updateType;
  11859. }
  11860. /**
  11861. * `ScreenNode` implements {@link Node#update} to retrieve viewport and size information
  11862. * from the current renderer.
  11863. *
  11864. * @param {NodeFrame} frame - A reference to the current node frame.
  11865. */
  11866. update( { renderer } ) {
  11867. const renderTarget = renderer.getRenderTarget();
  11868. if ( this.scope === ScreenNode.VIEWPORT ) {
  11869. if ( renderTarget !== null ) {
  11870. viewportVec.copy( renderTarget.viewport );
  11871. } else {
  11872. renderer.getViewport( viewportVec );
  11873. viewportVec.multiplyScalar( renderer.getPixelRatio() );
  11874. }
  11875. } else {
  11876. if ( renderTarget !== null ) {
  11877. screenSizeVec.width = renderTarget.width;
  11878. screenSizeVec.height = renderTarget.height;
  11879. } else {
  11880. renderer.getDrawingBufferSize( screenSizeVec );
  11881. }
  11882. }
  11883. }
  11884. setup( /*builder*/ ) {
  11885. const scope = this.scope;
  11886. let output = null;
  11887. if ( scope === ScreenNode.SIZE ) {
  11888. output = uniform( screenSizeVec || ( screenSizeVec = new Vector2() ) );
  11889. } else if ( scope === ScreenNode.VIEWPORT ) {
  11890. output = uniform( viewportVec || ( viewportVec = new Vector4() ) );
  11891. } else {
  11892. output = vec2( screenCoordinate.div( screenSize ) );
  11893. }
  11894. return output;
  11895. }
  11896. generate( builder ) {
  11897. if ( this.scope === ScreenNode.COORDINATE ) {
  11898. let coord = builder.getFragCoord();
  11899. if ( builder.isFlipY() ) {
  11900. // follow webgpu standards
  11901. const size = builder.getNodeProperties( screenSize ).outputNode.build( builder );
  11902. coord = `${ builder.getType( 'vec2' ) }( ${ coord }.x, ${ size }.y - ${ coord }.y )`;
  11903. }
  11904. return coord;
  11905. }
  11906. return super.generate( builder );
  11907. }
  11908. }
  11909. ScreenNode.COORDINATE = 'coordinate';
  11910. ScreenNode.VIEWPORT = 'viewport';
  11911. ScreenNode.SIZE = 'size';
  11912. ScreenNode.UV = 'uv';
  11913. // Screen
  11914. /**
  11915. * TSL object that represents normalized screen coordinates, unitless in `[0, 1]`.
  11916. *
  11917. * @tsl
  11918. * @type {ScreenNode<vec2>}
  11919. */
  11920. const screenUV = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.UV );
  11921. /**
  11922. * TSL object that represents the screen resolution in physical pixel units.
  11923. *
  11924. * @tsl
  11925. * @type {ScreenNode<vec2>}
  11926. */
  11927. const screenSize = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.SIZE );
  11928. /**
  11929. * TSL object that represents the current `x`/`y` pixel position on the screen in physical pixel units.
  11930. *
  11931. * @tsl
  11932. * @type {ScreenNode<vec2>}
  11933. */
  11934. const screenCoordinate = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.COORDINATE );
  11935. // Viewport
  11936. /**
  11937. * TSL object that represents the viewport rectangle as `x`, `y`, `width` and `height` in physical pixel units.
  11938. *
  11939. * @tsl
  11940. * @type {ScreenNode<vec4>}
  11941. */
  11942. const viewport = /*@__PURE__*/ nodeImmutable( ScreenNode, ScreenNode.VIEWPORT );
  11943. /**
  11944. * TSL object that represents the viewport resolution in physical pixel units.
  11945. *
  11946. * @tsl
  11947. * @type {ScreenNode<vec2>}
  11948. */
  11949. const viewportSize = viewport.zw;
  11950. /**
  11951. * TSL object that represents the current `x`/`y` pixel position on the viewport in physical pixel units.
  11952. *
  11953. * @tsl
  11954. * @type {ScreenNode<vec2>}
  11955. */
  11956. const viewportCoordinate = /*@__PURE__*/ screenCoordinate.sub( viewport.xy );
  11957. /**
  11958. * TSL object that represents normalized viewport coordinates, unitless in `[0, 1]`.
  11959. *
  11960. * @tsl
  11961. * @type {ScreenNode<vec2>}
  11962. */
  11963. const viewportUV = /*@__PURE__*/ viewportCoordinate.div( viewportSize );
  11964. // Deprecated
  11965. /**
  11966. * @deprecated since r169. Use {@link screenSize} instead.
  11967. */
  11968. const viewportResolution = /*@__PURE__*/ ( Fn( () => { // @deprecated, r169
  11969. console.warn( 'THREE.TSL: "viewportResolution" is deprecated. Use "screenSize" instead.' );
  11970. return screenSize;
  11971. }, 'vec2' ).once() )();
  11972. /**
  11973. * @tsl
  11974. * @deprecated since r168. Use {@link screenUV} instead.
  11975. * @type {Node<vec2>}
  11976. */
  11977. const viewportTopLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  11978. console.warn( 'THREE.TSL: "viewportTopLeft" is deprecated. Use "screenUV" instead.' );
  11979. return screenUV;
  11980. }, 'vec2' ).once() )();
  11981. /**
  11982. * @tsl
  11983. * @deprecated since r168. Use `screenUV.flipY()` instead.
  11984. * @type {Node<vec2>}
  11985. */
  11986. const viewportBottomLeft = /*@__PURE__*/ ( Fn( () => { // @deprecated, r168
  11987. console.warn( 'THREE.TSL: "viewportBottomLeft" is deprecated. Use "screenUV.flipY()" instead.' );
  11988. return screenUV.flipY();
  11989. }, 'vec2' ).once() )();
  11990. const _size$4 = /*@__PURE__*/ new Vector2();
  11991. /**
  11992. * A special type of texture node which represents the data of the current viewport
  11993. * as a texture. The module extracts data from the current bound framebuffer with
  11994. * a copy operation so no extra render pass is required to produce the texture data
  11995. * (which is good for performance). `ViewportTextureNode` can be used as an input for a
  11996. * variety of effects like refractive or transmissive materials.
  11997. *
  11998. * @augments TextureNode
  11999. */
  12000. class ViewportTextureNode extends TextureNode {
  12001. static get type() {
  12002. return 'ViewportTextureNode';
  12003. }
  12004. /**
  12005. * Constructs a new viewport texture node.
  12006. *
  12007. * @param {Node} [uvNode=screenUV] - The uv node.
  12008. * @param {?Node} [levelNode=null] - The level node.
  12009. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12010. */
  12011. constructor( uvNode = screenUV, levelNode = null, framebufferTexture = null ) {
  12012. if ( framebufferTexture === null ) {
  12013. framebufferTexture = new FramebufferTexture();
  12014. framebufferTexture.minFilter = LinearMipmapLinearFilter;
  12015. }
  12016. super( framebufferTexture, uvNode, levelNode );
  12017. /**
  12018. * Whether to generate mipmaps or not.
  12019. *
  12020. * @type {boolean}
  12021. * @default false
  12022. */
  12023. this.generateMipmaps = false;
  12024. /**
  12025. * This flag can be used for type testing.
  12026. *
  12027. * @type {boolean}
  12028. * @readonly
  12029. * @default true
  12030. */
  12031. this.isOutputTextureNode = true;
  12032. /**
  12033. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  12034. * scene once per frame in its {@link ViewportTextureNode#updateBefore} method.
  12035. *
  12036. * @type {string}
  12037. * @default 'frame'
  12038. */
  12039. this.updateBeforeType = NodeUpdateType.FRAME;
  12040. }
  12041. updateBefore( frame ) {
  12042. const renderer = frame.renderer;
  12043. renderer.getDrawingBufferSize( _size$4 );
  12044. //
  12045. const framebufferTexture = this.value;
  12046. if ( framebufferTexture.image.width !== _size$4.width || framebufferTexture.image.height !== _size$4.height ) {
  12047. framebufferTexture.image.width = _size$4.width;
  12048. framebufferTexture.image.height = _size$4.height;
  12049. framebufferTexture.needsUpdate = true;
  12050. }
  12051. //
  12052. const currentGenerateMipmaps = framebufferTexture.generateMipmaps;
  12053. framebufferTexture.generateMipmaps = this.generateMipmaps;
  12054. renderer.copyFramebufferToTexture( framebufferTexture );
  12055. framebufferTexture.generateMipmaps = currentGenerateMipmaps;
  12056. }
  12057. clone() {
  12058. const viewportTextureNode = new this.constructor( this.uvNode, this.levelNode, this.value );
  12059. viewportTextureNode.generateMipmaps = this.generateMipmaps;
  12060. return viewportTextureNode;
  12061. }
  12062. }
  12063. /**
  12064. * TSL function for creating a viewport texture node.
  12065. *
  12066. * @tsl
  12067. * @function
  12068. * @param {?Node} [uvNode=screenUV] - The uv node.
  12069. * @param {?Node} [levelNode=null] - The level node.
  12070. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12071. * @returns {ViewportTextureNode}
  12072. */
  12073. const viewportTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode ).setParameterLength( 0, 3 );
  12074. /**
  12075. * TSL function for creating a viewport texture node with enabled mipmap generation.
  12076. *
  12077. * @tsl
  12078. * @function
  12079. * @param {?Node} [uvNode=screenUV] - The uv node.
  12080. * @param {?Node} [levelNode=null] - The level node.
  12081. * @param {?Texture} [framebufferTexture=null] - A framebuffer texture holding the viewport data. If not provided, a framebuffer texture is created automatically.
  12082. * @returns {ViewportTextureNode}
  12083. */
  12084. const viewportMipTexture = /*@__PURE__*/ nodeProxy( ViewportTextureNode, null, null, { generateMipmaps: true } ).setParameterLength( 0, 3 );
  12085. let sharedDepthbuffer = null;
  12086. /**
  12087. * Represents the depth of the current viewport as a texture. This module
  12088. * can be used in combination with viewport texture to achieve effects
  12089. * that require depth evaluation.
  12090. *
  12091. * @augments ViewportTextureNode
  12092. */
  12093. class ViewportDepthTextureNode extends ViewportTextureNode {
  12094. static get type() {
  12095. return 'ViewportDepthTextureNode';
  12096. }
  12097. /**
  12098. * Constructs a new viewport depth texture node.
  12099. *
  12100. * @param {Node} [uvNode=screenUV] - The uv node.
  12101. * @param {?Node} [levelNode=null] - The level node.
  12102. */
  12103. constructor( uvNode = screenUV, levelNode = null ) {
  12104. if ( sharedDepthbuffer === null ) {
  12105. sharedDepthbuffer = new DepthTexture();
  12106. }
  12107. super( uvNode, levelNode, sharedDepthbuffer );
  12108. }
  12109. }
  12110. /**
  12111. * TSL function for a viewport depth texture node.
  12112. *
  12113. * @tsl
  12114. * @function
  12115. * @param {?Node} [uvNode=screenUV] - The uv node.
  12116. * @param {?Node} [levelNode=null] - The level node.
  12117. * @returns {ViewportDepthTextureNode}
  12118. */
  12119. const viewportDepthTexture = /*@__PURE__*/ nodeProxy( ViewportDepthTextureNode ).setParameterLength( 0, 2 );
  12120. /**
  12121. * This node offers a collection of features in context of the depth logic in the fragment shader.
  12122. * Depending on {@link ViewportDepthNode#scope}, it can be used to define a depth value for the current
  12123. * fragment or for depth evaluation purposes.
  12124. *
  12125. * @augments Node
  12126. */
  12127. class ViewportDepthNode extends Node {
  12128. static get type() {
  12129. return 'ViewportDepthNode';
  12130. }
  12131. /**
  12132. * Constructs a new viewport depth node.
  12133. *
  12134. * @param {('depth'|'depthBase'|'linearDepth')} scope - The node's scope.
  12135. * @param {?Node} [valueNode=null] - The value node.
  12136. */
  12137. constructor( scope, valueNode = null ) {
  12138. super( 'float' );
  12139. /**
  12140. * The node behaves differently depending on which scope is selected.
  12141. *
  12142. * - `ViewportDepthNode.DEPTH_BASE`: Allows to define a value for the current fragment's depth.
  12143. * - `ViewportDepthNode.DEPTH`: Represents the depth value for the current fragment (`valueNode` is ignored).
  12144. * - `ViewportDepthNode.LINEAR_DEPTH`: Represents the linear (orthographic) depth value of the current fragment.
  12145. * If a `valueNode` is set, the scope can be used to convert perspective depth data to linear data.
  12146. *
  12147. * @type {('depth'|'depthBase'|'linearDepth')}
  12148. */
  12149. this.scope = scope;
  12150. /**
  12151. * Can be used to define a custom depth value.
  12152. * The property is ignored in the `ViewportDepthNode.DEPTH` scope.
  12153. *
  12154. * @type {?Node}
  12155. * @default null
  12156. */
  12157. this.valueNode = valueNode;
  12158. /**
  12159. * This flag can be used for type testing.
  12160. *
  12161. * @type {boolean}
  12162. * @readonly
  12163. * @default true
  12164. */
  12165. this.isViewportDepthNode = true;
  12166. }
  12167. generate( builder ) {
  12168. const { scope } = this;
  12169. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12170. return builder.getFragDepth();
  12171. }
  12172. return super.generate( builder );
  12173. }
  12174. setup( { camera } ) {
  12175. const { scope } = this;
  12176. const value = this.valueNode;
  12177. let node = null;
  12178. if ( scope === ViewportDepthNode.DEPTH_BASE ) {
  12179. if ( value !== null ) {
  12180. node = depthBase().assign( value );
  12181. }
  12182. } else if ( scope === ViewportDepthNode.DEPTH ) {
  12183. if ( camera.isPerspectiveCamera ) {
  12184. node = viewZToPerspectiveDepth( positionView.z, cameraNear, cameraFar );
  12185. } else {
  12186. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12187. }
  12188. } else if ( scope === ViewportDepthNode.LINEAR_DEPTH ) {
  12189. if ( value !== null ) {
  12190. if ( camera.isPerspectiveCamera ) {
  12191. const viewZ = perspectiveDepthToViewZ( value, cameraNear, cameraFar );
  12192. node = viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  12193. } else {
  12194. node = value;
  12195. }
  12196. } else {
  12197. node = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  12198. }
  12199. }
  12200. return node;
  12201. }
  12202. }
  12203. ViewportDepthNode.DEPTH_BASE = 'depthBase';
  12204. ViewportDepthNode.DEPTH = 'depth';
  12205. ViewportDepthNode.LINEAR_DEPTH = 'linearDepth';
  12206. // NOTE: viewZ, the z-coordinate in camera space, is negative for points in front of the camera
  12207. /**
  12208. * TSL function for converting a viewZ value to an orthographic depth value.
  12209. *
  12210. * @tsl
  12211. * @function
  12212. * @param {Node<float>} viewZ - The viewZ node.
  12213. * @param {Node<float>} near - The camera's near value.
  12214. * @param {Node<float>} far - The camera's far value.
  12215. * @returns {Node<float>}
  12216. */
  12217. const viewZToOrthographicDepth = ( viewZ, near, far ) => viewZ.add( near ).div( near.sub( far ) );
  12218. /**
  12219. * TSL function for converting an orthographic depth value to a viewZ value.
  12220. *
  12221. * @tsl
  12222. * @function
  12223. * @param {Node<float>} depth - The orthographic depth.
  12224. * @param {Node<float>} near - The camera's near value.
  12225. * @param {Node<float>} far - The camera's far value.
  12226. * @returns {Node<float>}
  12227. */
  12228. const orthographicDepthToViewZ = ( depth, near, far ) => near.sub( far ).mul( depth ).sub( near );
  12229. /**
  12230. * TSL function for converting a viewZ value to a perspective depth value.
  12231. *
  12232. * Note: {link https://twitter.com/gonnavis/status/1377183786949959682}.
  12233. *
  12234. * @tsl
  12235. * @function
  12236. * @param {Node<float>} viewZ - The viewZ node.
  12237. * @param {Node<float>} near - The camera's near value.
  12238. * @param {Node<float>} far - The camera's far value.
  12239. * @returns {Node<float>}
  12240. */
  12241. const viewZToPerspectiveDepth = ( viewZ, near, far ) => near.add( viewZ ).mul( far ).div( far.sub( near ).mul( viewZ ) );
  12242. /**
  12243. * TSL function for converting a perspective depth value to a viewZ value.
  12244. *
  12245. * @tsl
  12246. * @function
  12247. * @param {Node<float>} depth - The perspective depth.
  12248. * @param {Node<float>} near - The camera's near value.
  12249. * @param {Node<float>} far - The camera's far value.
  12250. * @returns {Node<float>}
  12251. */
  12252. const perspectiveDepthToViewZ = ( depth, near, far ) => near.mul( far ).div( far.sub( near ).mul( depth ).sub( far ) );
  12253. /**
  12254. * TSL function for converting a viewZ value to a logarithmic depth value.
  12255. *
  12256. * @tsl
  12257. * @function
  12258. * @param {Node<float>} viewZ - The viewZ node.
  12259. * @param {Node<float>} near - The camera's near value.
  12260. * @param {Node<float>} far - The camera's far value.
  12261. * @returns {Node<float>}
  12262. */
  12263. const viewZToLogarithmicDepth = ( viewZ, near, far ) => {
  12264. // NOTE: viewZ must be negative--see explanation at the end of this comment block.
  12265. // The final logarithmic depth formula used here is adapted from one described in an
  12266. // article by Thatcher Ulrich (see http://tulrich.com/geekstuff/log_depth_buffer.txt),
  12267. // which was an improvement upon an earlier formula one described in an
  12268. // Outerra article (https://outerra.blogspot.com/2009/08/logarithmic-z-buffer.html).
  12269. // Ulrich's formula is the following:
  12270. // z = K * log( w / cameraNear ) / log( cameraFar / cameraNear )
  12271. // where K = 2^k - 1, and k is the number of bits in the depth buffer.
  12272. // The Outerra variant ignored the camera near plane (it assumed it was 0) and instead
  12273. // opted for a "C-constant" for resolution adjustment of objects near the camera.
  12274. // Outerra states: "Notice that the 'C' variant doesn’t use a near plane distance, it has it
  12275. // set at 0" (quote from https://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html).
  12276. // Ulrich's variant has the benefit of constant relative precision over the whole near-far range.
  12277. // It was debated here whether Outerra's "C-constant" or Ulrich's "near plane" variant should
  12278. // be used, and ultimately Ulrich's "near plane" version was chosen.
  12279. // Outerra eventually made another improvement to their original "C-constant" variant,
  12280. // but it still does not incorporate the camera near plane (for this version,
  12281. // see https://outerra.blogspot.com/2013/07/logarithmic-depth-buffer-optimizations.html).
  12282. // Here we make 4 changes to Ulrich's formula:
  12283. // 1. Clamp the camera near plane so we don't divide by 0.
  12284. // 2. Use log2 instead of log to avoid an extra multiply (shaders implement log using log2).
  12285. // 3. Assume K is 1 (K = maximum value in depth buffer; see Ulrich's formula above).
  12286. // 4. To maintain consistency with the functions "viewZToOrthographicDepth" and "viewZToPerspectiveDepth",
  12287. // we modify the formula here to use 'viewZ' instead of 'w'. The other functions expect a negative viewZ,
  12288. // so we do the same here, hence the 'viewZ.negate()' call.
  12289. // For visual representation of this depth curve, see https://www.desmos.com/calculator/uyqk0vex1u
  12290. near = near.max( 1e-6 ).toVar();
  12291. const numerator = log2( viewZ.negate().div( near ) );
  12292. const denominator = log2( far.div( near ) );
  12293. return numerator.div( denominator );
  12294. };
  12295. /**
  12296. * TSL function for converting a logarithmic depth value to a viewZ value.
  12297. *
  12298. * @tsl
  12299. * @function
  12300. * @param {Node<float>} depth - The logarithmic depth.
  12301. * @param {Node<float>} near - The camera's near value.
  12302. * @param {Node<float>} far - The camera's far value.
  12303. * @returns {Node<float>}
  12304. */
  12305. const logarithmicDepthToViewZ = ( depth, near, far ) => {
  12306. // NOTE: we add a 'negate()' call to the return value here to maintain consistency with
  12307. // the functions "orthographicDepthToViewZ" and "perspectiveDepthToViewZ" (they return
  12308. // a negative viewZ).
  12309. const exponent = depth.mul( log( far.div( near ) ) );
  12310. return float( Math.E ).pow( exponent ).mul( near ).negate();
  12311. };
  12312. /**
  12313. * TSL function for defining a value for the current fragment's depth.
  12314. *
  12315. * @tsl
  12316. * @function
  12317. * @param {Node<float>} value - The depth value to set.
  12318. * @returns {ViewportDepthNode<float>}
  12319. */
  12320. const depthBase = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.DEPTH_BASE );
  12321. /**
  12322. * TSL object that represents the depth value for the current fragment.
  12323. *
  12324. * @tsl
  12325. * @type {ViewportDepthNode}
  12326. */
  12327. const depth = /*@__PURE__*/ nodeImmutable( ViewportDepthNode, ViewportDepthNode.DEPTH );
  12328. /**
  12329. * TSL function for converting a perspective depth value to linear depth.
  12330. *
  12331. * @tsl
  12332. * @function
  12333. * @param {?Node<float>} [value=null] - The perspective depth. If `null` is provided, the current fragment's depth is used.
  12334. * @returns {ViewportDepthNode<float>}
  12335. */
  12336. const linearDepth = /*@__PURE__*/ nodeProxy( ViewportDepthNode, ViewportDepthNode.LINEAR_DEPTH ).setParameterLength( 0, 1 );
  12337. /**
  12338. * TSL object that represents the linear (orthographic) depth value of the current fragment
  12339. *
  12340. * @tsl
  12341. * @type {ViewportDepthNode}
  12342. */
  12343. const viewportLinearDepth = /*@__PURE__*/ linearDepth( viewportDepthTexture() );
  12344. depth.assign = ( value ) => depthBase( value );
  12345. /**
  12346. * This node is used in {@link NodeMaterial} to setup the clipping
  12347. * which can happen hardware-accelerated (if supported) and optionally
  12348. * use alpha-to-coverage for anti-aliasing clipped edges.
  12349. *
  12350. * @augments Node
  12351. */
  12352. class ClippingNode extends Node {
  12353. static get type() {
  12354. return 'ClippingNode';
  12355. }
  12356. /**
  12357. * Constructs a new clipping node.
  12358. *
  12359. * @param {('default'|'hardware'|'alphaToCoverage')} [scope='default'] - The node's scope. Similar to other nodes,
  12360. * the selected scope influences the behavior of the node and what type of code is generated.
  12361. */
  12362. constructor( scope = ClippingNode.DEFAULT ) {
  12363. super();
  12364. /**
  12365. * The node's scope. Similar to other nodes, the selected scope influences
  12366. * the behavior of the node and what type of code is generated.
  12367. *
  12368. * @type {('default'|'hardware'|'alphaToCoverage')}
  12369. */
  12370. this.scope = scope;
  12371. }
  12372. /**
  12373. * Setups the node depending on the selected scope.
  12374. *
  12375. * @param {NodeBuilder} builder - The current node builder.
  12376. * @return {Node} The result node.
  12377. */
  12378. setup( builder ) {
  12379. super.setup( builder );
  12380. const clippingContext = builder.clippingContext;
  12381. const { intersectionPlanes, unionPlanes } = clippingContext;
  12382. this.hardwareClipping = builder.material.hardwareClipping;
  12383. if ( this.scope === ClippingNode.ALPHA_TO_COVERAGE ) {
  12384. return this.setupAlphaToCoverage( intersectionPlanes, unionPlanes );
  12385. } else if ( this.scope === ClippingNode.HARDWARE ) {
  12386. return this.setupHardwareClipping( unionPlanes, builder );
  12387. } else {
  12388. return this.setupDefault( intersectionPlanes, unionPlanes );
  12389. }
  12390. }
  12391. /**
  12392. * Setups alpha to coverage.
  12393. *
  12394. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12395. * @param {Array<Vector4>} unionPlanes - The union planes.
  12396. * @return {Node} The result node.
  12397. */
  12398. setupAlphaToCoverage( intersectionPlanes, unionPlanes ) {
  12399. return Fn( () => {
  12400. const distanceToPlane = float().toVar( 'distanceToPlane' );
  12401. const distanceGradient = float().toVar( 'distanceToGradient' );
  12402. const clipOpacity = float( 1 ).toVar( 'clipOpacity' );
  12403. const numUnionPlanes = unionPlanes.length;
  12404. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  12405. const clippingPlanes = uniformArray( unionPlanes );
  12406. Loop( numUnionPlanes, ( { i } ) => {
  12407. const plane = clippingPlanes.element( i );
  12408. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  12409. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  12410. clipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ) );
  12411. } );
  12412. }
  12413. const numIntersectionPlanes = intersectionPlanes.length;
  12414. if ( numIntersectionPlanes > 0 ) {
  12415. const clippingPlanes = uniformArray( intersectionPlanes );
  12416. const intersectionClipOpacity = float( 1 ).toVar( 'intersectionClipOpacity' );
  12417. Loop( numIntersectionPlanes, ( { i } ) => {
  12418. const plane = clippingPlanes.element( i );
  12419. distanceToPlane.assign( positionView.dot( plane.xyz ).negate().add( plane.w ) );
  12420. distanceGradient.assign( distanceToPlane.fwidth().div( 2.0 ) );
  12421. intersectionClipOpacity.mulAssign( smoothstep( distanceGradient.negate(), distanceGradient, distanceToPlane ).oneMinus() );
  12422. } );
  12423. clipOpacity.mulAssign( intersectionClipOpacity.oneMinus() );
  12424. }
  12425. diffuseColor.a.mulAssign( clipOpacity );
  12426. diffuseColor.a.equal( 0.0 ).discard();
  12427. } )();
  12428. }
  12429. /**
  12430. * Setups the default clipping.
  12431. *
  12432. * @param {Array<Vector4>} intersectionPlanes - The intersection planes.
  12433. * @param {Array<Vector4>} unionPlanes - The union planes.
  12434. * @return {Node} The result node.
  12435. */
  12436. setupDefault( intersectionPlanes, unionPlanes ) {
  12437. return Fn( () => {
  12438. const numUnionPlanes = unionPlanes.length;
  12439. if ( this.hardwareClipping === false && numUnionPlanes > 0 ) {
  12440. const clippingPlanes = uniformArray( unionPlanes );
  12441. Loop( numUnionPlanes, ( { i } ) => {
  12442. const plane = clippingPlanes.element( i );
  12443. positionView.dot( plane.xyz ).greaterThan( plane.w ).discard();
  12444. } );
  12445. }
  12446. const numIntersectionPlanes = intersectionPlanes.length;
  12447. if ( numIntersectionPlanes > 0 ) {
  12448. const clippingPlanes = uniformArray( intersectionPlanes );
  12449. const clipped = bool( true ).toVar( 'clipped' );
  12450. Loop( numIntersectionPlanes, ( { i } ) => {
  12451. const plane = clippingPlanes.element( i );
  12452. clipped.assign( positionView.dot( plane.xyz ).greaterThan( plane.w ).and( clipped ) );
  12453. } );
  12454. clipped.discard();
  12455. }
  12456. } )();
  12457. }
  12458. /**
  12459. * Setups hardware clipping.
  12460. *
  12461. * @param {Array<Vector4>} unionPlanes - The union planes.
  12462. * @param {NodeBuilder} builder - The current node builder.
  12463. * @return {Node} The result node.
  12464. */
  12465. setupHardwareClipping( unionPlanes, builder ) {
  12466. const numUnionPlanes = unionPlanes.length;
  12467. builder.enableHardwareClipping( numUnionPlanes );
  12468. return Fn( () => {
  12469. const clippingPlanes = uniformArray( unionPlanes );
  12470. const hw_clip_distances = builtin( builder.getClipDistance() );
  12471. Loop( numUnionPlanes, ( { i } ) => {
  12472. const plane = clippingPlanes.element( i );
  12473. const distance = positionView.dot( plane.xyz ).sub( plane.w ).negate();
  12474. hw_clip_distances.element( i ).assign( distance );
  12475. } );
  12476. } )();
  12477. }
  12478. }
  12479. ClippingNode.ALPHA_TO_COVERAGE = 'alphaToCoverage';
  12480. ClippingNode.DEFAULT = 'default';
  12481. ClippingNode.HARDWARE = 'hardware';
  12482. /**
  12483. * TSL function for setting up the default clipping logic.
  12484. *
  12485. * @tsl
  12486. * @function
  12487. * @returns {ClippingNode}
  12488. */
  12489. const clipping = () => nodeObject( new ClippingNode() );
  12490. /**
  12491. * TSL function for setting up alpha to coverage.
  12492. *
  12493. * @tsl
  12494. * @function
  12495. * @returns {ClippingNode}
  12496. */
  12497. const clippingAlpha = () => nodeObject( new ClippingNode( ClippingNode.ALPHA_TO_COVERAGE ) );
  12498. /**
  12499. * TSL function for setting up hardware-based clipping.
  12500. *
  12501. * @tsl
  12502. * @function
  12503. * @returns {ClippingNode}
  12504. */
  12505. const hardwareClipping = () => nodeObject( new ClippingNode( ClippingNode.HARDWARE ) );
  12506. // See: https://casual-effects.com/research/Wyman2017Hashed/index.html
  12507. const ALPHA_HASH_SCALE = 0.05; // Derived from trials only, and may be changed.
  12508. const hash2D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  12509. 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 ) ) ) ) ) );
  12510. } );
  12511. const hash3D = /*@__PURE__*/ Fn( ( [ value ] ) => {
  12512. return hash2D( vec2( hash2D( value.xy ), value.z ) );
  12513. } );
  12514. const getAlphaHashThreshold = /*@__PURE__*/ Fn( ( [ position ] ) => {
  12515. // Find the discretized derivatives of our coordinates
  12516. const maxDeriv = max$1(
  12517. length( dFdx( position.xyz ) ),
  12518. length( dFdy( position.xyz ) )
  12519. );
  12520. const pixScale = float( 1 ).div( float( ALPHA_HASH_SCALE ).mul( maxDeriv ) ).toVar( 'pixScale' );
  12521. // Find two nearest log-discretized noise scales
  12522. const pixScales = vec2(
  12523. exp2( floor( log2( pixScale ) ) ),
  12524. exp2( ceil( log2( pixScale ) ) )
  12525. );
  12526. // Compute alpha thresholds at our two noise scales
  12527. const alpha = vec2(
  12528. hash3D( floor( pixScales.x.mul( position.xyz ) ) ),
  12529. hash3D( floor( pixScales.y.mul( position.xyz ) ) ),
  12530. );
  12531. // Factor to interpolate lerp with
  12532. const lerpFactor = fract( log2( pixScale ) );
  12533. // Interpolate alpha threshold from noise at two scales
  12534. const x = add( mul( lerpFactor.oneMinus(), alpha.x ), mul( lerpFactor, alpha.y ) );
  12535. // Pass into CDF to compute uniformly distrib threshold
  12536. const a = min$1( lerpFactor, lerpFactor.oneMinus() );
  12537. const cases = vec3(
  12538. x.mul( x ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ),
  12539. x.sub( mul( 0.5, a ) ).div( sub( 1.0, a ) ),
  12540. sub( 1.0, sub( 1.0, x ).mul( sub( 1.0, x ) ).div( mul( 2.0, a ).mul( sub( 1.0, a ) ) ) ) );
  12541. // Find our final, uniformly distributed alpha threshold (ατ)
  12542. const threshold = x.lessThan( a.oneMinus() ).select( x.lessThan( a ).select( cases.x, cases.y ), cases.z );
  12543. // Avoids ατ == 0. Could also do ατ =1-ατ
  12544. return clamp( threshold, 1.0e-6, 1.0 );
  12545. } ).setLayout( {
  12546. name: 'getAlphaHashThreshold',
  12547. type: 'float',
  12548. inputs: [
  12549. { name: 'position', type: 'vec3' }
  12550. ]
  12551. } );
  12552. /**
  12553. * An attribute node for representing vertex colors.
  12554. *
  12555. * @augments AttributeNode
  12556. */
  12557. class VertexColorNode extends AttributeNode {
  12558. static get type() {
  12559. return 'VertexColorNode';
  12560. }
  12561. /**
  12562. * Constructs a new vertex color node.
  12563. *
  12564. * @param {number} index - The attribute index.
  12565. */
  12566. constructor( index ) {
  12567. super( null, 'vec4' );
  12568. /**
  12569. * This flag can be used for type testing.
  12570. *
  12571. * @type {boolean}
  12572. * @readonly
  12573. * @default true
  12574. */
  12575. this.isVertexColorNode = true;
  12576. /**
  12577. * The attribute index to enable more than one sets of vertex colors.
  12578. *
  12579. * @type {number}
  12580. * @default 0
  12581. */
  12582. this.index = index;
  12583. }
  12584. /**
  12585. * Overwrites the default implementation by honoring the attribute index.
  12586. *
  12587. * @param {NodeBuilder} builder - The current node builder.
  12588. * @return {string} The attribute name.
  12589. */
  12590. getAttributeName( /*builder*/ ) {
  12591. const index = this.index;
  12592. return 'color' + ( index > 0 ? index : '' );
  12593. }
  12594. generate( builder ) {
  12595. const attributeName = this.getAttributeName( builder );
  12596. const geometryAttribute = builder.hasGeometryAttribute( attributeName );
  12597. let result;
  12598. if ( geometryAttribute === true ) {
  12599. result = super.generate( builder );
  12600. } else {
  12601. // Vertex color fallback should be white
  12602. result = builder.generateConst( this.nodeType, new Vector4( 1, 1, 1, 1 ) );
  12603. }
  12604. return result;
  12605. }
  12606. serialize( data ) {
  12607. super.serialize( data );
  12608. data.index = this.index;
  12609. }
  12610. deserialize( data ) {
  12611. super.deserialize( data );
  12612. this.index = data.index;
  12613. }
  12614. }
  12615. /**
  12616. * TSL function for creating a reference node.
  12617. *
  12618. * @tsl
  12619. * @function
  12620. * @param {number} [index=0] - The attribute index.
  12621. * @returns {VertexColorNode}
  12622. */
  12623. const vertexColor = ( index = 0 ) => nodeObject( new VertexColorNode( index ) );
  12624. /**
  12625. * Represents a "Color Burn" blend mode.
  12626. *
  12627. * It's designed to darken the base layer's colors based on the color of the blend layer.
  12628. * It significantly increases the contrast of the base layer, making the colors more vibrant and saturated.
  12629. * The darker the color in the blend layer, the stronger the darkening and contrast effect on the base layer.
  12630. *
  12631. * @tsl
  12632. * @function
  12633. * @param {Node<vec3>} base - The base color.
  12634. * @param {Node<vec3>} blend - The blend color. A white (#ffffff) blend color does not alter the base color.
  12635. * @return {Node<vec3>} The result.
  12636. */
  12637. const blendBurn = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  12638. return min$1( 1.0, base.oneMinus().div( blend ) ).oneMinus();
  12639. } ).setLayout( {
  12640. name: 'blendBurn',
  12641. type: 'vec3',
  12642. inputs: [
  12643. { name: 'base', type: 'vec3' },
  12644. { name: 'blend', type: 'vec3' }
  12645. ]
  12646. } );
  12647. /**
  12648. * Represents a "Color Dodge" blend mode.
  12649. *
  12650. * It's designed to lighten the base layer's colors based on the color of the blend layer.
  12651. * It significantly increases the brightness of the base layer, making the colors lighter and more vibrant.
  12652. * The brighter the color in the blend layer, the stronger the lightening and contrast effect on the base layer.
  12653. *
  12654. * @tsl
  12655. * @function
  12656. * @param {Node<vec3>} base - The base color.
  12657. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  12658. * @return {Node<vec3>} The result.
  12659. */
  12660. const blendDodge = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  12661. return min$1( base.div( blend.oneMinus() ), 1.0 );
  12662. } ).setLayout( {
  12663. name: 'blendDodge',
  12664. type: 'vec3',
  12665. inputs: [
  12666. { name: 'base', type: 'vec3' },
  12667. { name: 'blend', type: 'vec3' }
  12668. ]
  12669. } );
  12670. /**
  12671. * Represents a "Screen" blend mode.
  12672. *
  12673. * Similar to `blendDodge()`, this mode also lightens the base layer's colors based on the color of the blend layer.
  12674. * The "Screen" blend mode is better for general brightening whereas the "Dodge" results in more subtle and nuanced
  12675. * effects.
  12676. *
  12677. * @tsl
  12678. * @function
  12679. * @param {Node<vec3>} base - The base color.
  12680. * @param {Node<vec3>} blend - The blend color. A black (#000000) blend color does not alter the base color.
  12681. * @return {Node<vec3>} The result.
  12682. */
  12683. const blendScreen = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  12684. return base.oneMinus().mul( blend.oneMinus() ).oneMinus();
  12685. } ).setLayout( {
  12686. name: 'blendScreen',
  12687. type: 'vec3',
  12688. inputs: [
  12689. { name: 'base', type: 'vec3' },
  12690. { name: 'blend', type: 'vec3' }
  12691. ]
  12692. } );
  12693. /**
  12694. * Represents a "Overlay" blend mode.
  12695. *
  12696. * It's designed to increase the contrast of the base layer based on the color of the blend layer.
  12697. * It amplifies the existing colors and contrast in the base layer, making lighter areas lighter and darker areas darker.
  12698. * The color of the blend layer significantly influences the resulting contrast and color shift in the base layer.
  12699. *
  12700. * @tsl
  12701. * @function
  12702. * @param {Node<vec3>} base - The base color.
  12703. * @param {Node<vec3>} blend - The blend color
  12704. * @return {Node<vec3>} The result.
  12705. */
  12706. const blendOverlay = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  12707. return mix( base.mul( 2.0 ).mul( blend ), base.oneMinus().mul( 2.0 ).mul( blend.oneMinus() ).oneMinus(), step( 0.5, base ) );
  12708. } ).setLayout( {
  12709. name: 'blendOverlay',
  12710. type: 'vec3',
  12711. inputs: [
  12712. { name: 'base', type: 'vec3' },
  12713. { name: 'blend', type: 'vec3' }
  12714. ]
  12715. } );
  12716. /**
  12717. * This function blends two color based on their alpha values by replicating the behavior of `THREE.NormalBlending`.
  12718. * It assumes both input colors have non-premultiplied alpha.
  12719. *
  12720. * @tsl
  12721. * @function
  12722. * @param {Node<vec4>} base - The base color.
  12723. * @param {Node<vec4>} blend - The blend color
  12724. * @return {Node<vec4>} The result.
  12725. */
  12726. const blendColor = /*@__PURE__*/ Fn( ( [ base, blend ] ) => {
  12727. const outAlpha = blend.a.add( base.a.mul( blend.a.oneMinus() ) );
  12728. return vec4( blend.rgb.mul( blend.a ).add( base.rgb.mul( base.a ).mul( blend.a.oneMinus() ) ).div( outAlpha ), outAlpha );
  12729. } ).setLayout( {
  12730. name: 'blendColor',
  12731. type: 'vec4',
  12732. inputs: [
  12733. { name: 'base', type: 'vec4' },
  12734. { name: 'blend', type: 'vec4' }
  12735. ]
  12736. } );
  12737. /**
  12738. * Premultiplies the RGB channels of a color by its alpha channel.
  12739. *
  12740. * This function is useful for converting a non-premultiplied alpha color
  12741. * into a premultiplied alpha format, where the RGB values are scaled
  12742. * by the alpha value. Premultiplied alpha is often used in graphics
  12743. * rendering for certain operations, such as compositing and image processing.
  12744. *
  12745. * @tsl
  12746. * @function
  12747. * @param {Node<vec4>} color - The input color with non-premultiplied alpha.
  12748. * @return {Node<vec4>} The color with premultiplied alpha.
  12749. */
  12750. const premultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  12751. return vec4( color.rgb.mul( color.a ), color.a );
  12752. }, { color: 'vec4', return: 'vec4' } );
  12753. /**
  12754. * Unpremultiplies the RGB channels of a color by its alpha channel.
  12755. *
  12756. * This function is useful for converting a premultiplied alpha color
  12757. * back into a non-premultiplied alpha format, where the RGB values are
  12758. * divided by the alpha value. Unpremultiplied alpha is often used in graphics
  12759. * rendering for certain operations, such as compositing and image processing.
  12760. *
  12761. * @tsl
  12762. * @function
  12763. * @param {Node<vec4>} color - The input color with premultiplied alpha.
  12764. * @return {Node<vec4>} The color with non-premultiplied alpha.
  12765. */
  12766. const unpremultiplyAlpha = /*@__PURE__*/ Fn( ( [ color ] ) => {
  12767. If( color.a.equal( 0.0 ), () => vec4( 0.0 ) );
  12768. return vec4( color.rgb.div( color.a ), color.a );
  12769. }, { color: 'vec4', return: 'vec4' } );
  12770. // Deprecated
  12771. /**
  12772. * @tsl
  12773. * @function
  12774. * @deprecated since r171. Use {@link blendBurn} instead.
  12775. *
  12776. * @param {...any} params
  12777. * @returns {Function}
  12778. */
  12779. const burn = ( ...params ) => { // @deprecated, r171
  12780. console.warn( 'THREE.TSL: "burn" has been renamed. Use "blendBurn" instead.' );
  12781. return blendBurn( params );
  12782. };
  12783. /**
  12784. * @tsl
  12785. * @function
  12786. * @deprecated since r171. Use {@link blendDodge} instead.
  12787. *
  12788. * @param {...any} params
  12789. * @returns {Function}
  12790. */
  12791. const dodge = ( ...params ) => { // @deprecated, r171
  12792. console.warn( 'THREE.TSL: "dodge" has been renamed. Use "blendDodge" instead.' );
  12793. return blendDodge( params );
  12794. };
  12795. /**
  12796. * @tsl
  12797. * @function
  12798. * @deprecated since r171. Use {@link blendScreen} instead.
  12799. *
  12800. * @param {...any} params
  12801. * @returns {Function}
  12802. */
  12803. const screen = ( ...params ) => { // @deprecated, r171
  12804. console.warn( 'THREE.TSL: "screen" has been renamed. Use "blendScreen" instead.' );
  12805. return blendScreen( params );
  12806. };
  12807. /**
  12808. * @tsl
  12809. * @function
  12810. * @deprecated since r171. Use {@link blendOverlay} instead.
  12811. *
  12812. * @param {...any} params
  12813. * @returns {Function}
  12814. */
  12815. const overlay = ( ...params ) => { // @deprecated, r171
  12816. console.warn( 'THREE.TSL: "overlay" has been renamed. Use "blendOverlay" instead.' );
  12817. return blendOverlay( params );
  12818. };
  12819. /**
  12820. * Base class for all node materials.
  12821. *
  12822. * @augments Material
  12823. */
  12824. class NodeMaterial extends Material {
  12825. static get type() {
  12826. return 'NodeMaterial';
  12827. }
  12828. /**
  12829. * Represents the type of the node material.
  12830. *
  12831. * @type {string}
  12832. */
  12833. get type() {
  12834. return this.constructor.type;
  12835. }
  12836. set type( _value ) { /* */ }
  12837. /**
  12838. * Constructs a new node material.
  12839. */
  12840. constructor() {
  12841. super();
  12842. /**
  12843. * This flag can be used for type testing.
  12844. *
  12845. * @type {boolean}
  12846. * @readonly
  12847. * @default true
  12848. */
  12849. this.isNodeMaterial = true;
  12850. /**
  12851. * Whether this material is affected by fog or not.
  12852. *
  12853. * @type {boolean}
  12854. * @default true
  12855. */
  12856. this.fog = true;
  12857. /**
  12858. * Whether this material is affected by lights or not.
  12859. *
  12860. * @type {boolean}
  12861. * @default false
  12862. */
  12863. this.lights = false;
  12864. /**
  12865. * Whether this material uses hardware clipping or not.
  12866. * This property is managed by the engine and should not be
  12867. * modified by apps.
  12868. *
  12869. * @type {boolean}
  12870. * @default false
  12871. */
  12872. this.hardwareClipping = false;
  12873. /**
  12874. * Node materials which set their `lights` property to `true`
  12875. * are affected by all lights of the scene. Sometimes selective
  12876. * lighting is wanted which means only _some_ lights in the scene
  12877. * affect a material. This can be achieved by creating an instance
  12878. * of {@link LightsNode} with a list of selective
  12879. * lights and assign the node to this property.
  12880. *
  12881. * ```js
  12882. * const customLightsNode = lights( [ light1, light2 ] );
  12883. * material.lightsNode = customLightsNode;
  12884. * ```
  12885. *
  12886. * @type {?LightsNode}
  12887. * @default null
  12888. */
  12889. this.lightsNode = null;
  12890. /**
  12891. * The environment of node materials can be defined by an environment
  12892. * map assigned to the `envMap` property or by `Scene.environment`
  12893. * if the node material is a PBR material. This node property allows to overwrite
  12894. * the default behavior and define the environment with a custom node.
  12895. *
  12896. * ```js
  12897. * material.envNode = pmremTexture( renderTarget.texture );
  12898. * ```
  12899. *
  12900. * @type {?Node<vec3>}
  12901. * @default null
  12902. */
  12903. this.envNode = null;
  12904. /**
  12905. * The lighting of node materials might be influenced by ambient occlusion.
  12906. * The default AO is inferred from an ambient occlusion map assigned to `aoMap`
  12907. * and the respective `aoMapIntensity`. This node property allows to overwrite
  12908. * the default and define the ambient occlusion with a custom node instead.
  12909. *
  12910. * If you don't want to overwrite the diffuse color but modify the existing
  12911. * values instead, use {@link materialAO}.
  12912. *
  12913. * @type {?Node<float>}
  12914. * @default null
  12915. */
  12916. this.aoNode = null;
  12917. /**
  12918. * The diffuse color of node materials is by default inferred from the
  12919. * `color` and `map` properties. This node property allows to overwrite the default
  12920. * and define the diffuse color with a node instead.
  12921. *
  12922. * ```js
  12923. * material.colorNode = color( 0xff0000 ); // define red color
  12924. * ```
  12925. *
  12926. * If you don't want to overwrite the diffuse color but modify the existing
  12927. * values instead, use {@link materialColor}.
  12928. *
  12929. * ```js
  12930. * material.colorNode = materialColor.mul( color( 0xff0000 ) ); // give diffuse colors a red tint
  12931. * ```
  12932. *
  12933. * @type {?Node<vec3>}
  12934. * @default null
  12935. */
  12936. this.colorNode = null;
  12937. /**
  12938. * The normals of node materials are by default inferred from the `normalMap`/`normalScale`
  12939. * or `bumpMap`/`bumpScale` properties. This node property allows to overwrite the default
  12940. * and define the normals with a node instead.
  12941. *
  12942. * If you don't want to overwrite the normals but modify the existing values instead,
  12943. * use {@link materialNormal}.
  12944. *
  12945. * @type {?Node<vec3>}
  12946. * @default null
  12947. */
  12948. this.normalNode = null;
  12949. /**
  12950. * The opacity of node materials is by default inferred from the `opacity`
  12951. * and `alphaMap` properties. This node property allows to overwrite the default
  12952. * and define the opacity with a node instead.
  12953. *
  12954. * If you don't want to overwrite the normals but modify the existing
  12955. * value instead, use {@link materialOpacity}.
  12956. *
  12957. * @type {?Node<float>}
  12958. * @default null
  12959. */
  12960. this.opacityNode = null;
  12961. /**
  12962. * This node can be used to implement a variety of filter-like effects. The idea is
  12963. * to store the current rendering into a texture e.g. via `viewportSharedTexture()`, use it
  12964. * to create an arbitrary effect and then assign the node composition to this property.
  12965. * Everything behind the object using this material will now be affected by a filter.
  12966. *
  12967. * ```js
  12968. * const material = new NodeMaterial()
  12969. * material.transparent = true;
  12970. *
  12971. * // everything behind the object will be monochromatic
  12972. * material.backdropNode = saturation( viewportSharedTexture().rgb, 0 );
  12973. * ```
  12974. *
  12975. * Backdrop computations are part of the lighting so only lit materials can use this property.
  12976. *
  12977. * @type {?Node<vec3>}
  12978. * @default null
  12979. */
  12980. this.backdropNode = null;
  12981. /**
  12982. * This node allows to modulate the influence of `backdropNode` to the outgoing light.
  12983. *
  12984. * @type {?Node<float>}
  12985. * @default null
  12986. */
  12987. this.backdropAlphaNode = null;
  12988. /**
  12989. * The alpha test of node materials is by default inferred from the `alphaTest`
  12990. * property. This node property allows to overwrite the default and define the
  12991. * alpha test with a node instead.
  12992. *
  12993. * If you don't want to overwrite the alpha test but modify the existing
  12994. * value instead, use {@link materialAlphaTest}.
  12995. *
  12996. * @type {?Node<float>}
  12997. * @default null
  12998. */
  12999. this.alphaTestNode = null;
  13000. /**
  13001. * Discards the fragment if the mask value is `false`.
  13002. *
  13003. * @type {?Node<bool>}
  13004. * @default null
  13005. */
  13006. this.maskNode = null;
  13007. /**
  13008. * The local vertex positions are computed based on multiple factors like the
  13009. * attribute data, morphing or skinning. This node property allows to overwrite
  13010. * the default and define local vertex positions with nodes instead.
  13011. *
  13012. * If you don't want to overwrite the vertex positions but modify the existing
  13013. * values instead, use {@link positionLocal}.
  13014. *
  13015. *```js
  13016. * material.positionNode = positionLocal.add( displace );
  13017. * ```
  13018. *
  13019. * @type {?Node<vec3>}
  13020. * @default null
  13021. */
  13022. this.positionNode = null;
  13023. /**
  13024. * This node property is intended for logic which modifies geometry data once or per animation step.
  13025. * Apps usually place such logic randomly in initialization routines or in the animation loop.
  13026. * `geometryNode` is intended as a dedicated API so there is an intended spot where geometry modifications
  13027. * can be implemented.
  13028. *
  13029. * The idea is to assign a `Fn` definition that holds the geometry modification logic. A typical example
  13030. * would be a GPU based particle system that provides a node material for usage on app level. The particle
  13031. * simulation would be implemented as compute shaders and managed inside a `Fn` function. This function is
  13032. * eventually assigned to `geometryNode`.
  13033. *
  13034. * @type {?Function}
  13035. * @default null
  13036. */
  13037. this.geometryNode = null;
  13038. /**
  13039. * Allows to overwrite depth values in the fragment shader.
  13040. *
  13041. * @type {?Node<float>}
  13042. * @default null
  13043. */
  13044. this.depthNode = null;
  13045. /**
  13046. * Allows to overwrite the position used for shadow map rendering which
  13047. * is by default {@link positionWorld}, the vertex position
  13048. * in world space.
  13049. *
  13050. * @type {?Node<float>}
  13051. * @default null
  13052. */
  13053. this.receivedShadowPositionNode = null;
  13054. /**
  13055. * Allows to overwrite the geometry position used for shadow map projection which
  13056. * is by default {@link positionLocal}, the vertex position in local space.
  13057. *
  13058. * @type {?Node<float>}
  13059. * @default null
  13060. */
  13061. this.castShadowPositionNode = null;
  13062. /**
  13063. * This node can be used to influence how an object using this node material
  13064. * receive shadows.
  13065. *
  13066. * ```js
  13067. * const totalShadows = float( 1 ).toVar();
  13068. * material.receivedShadowNode = Fn( ( [ shadow ] ) => {
  13069. * totalShadows.mulAssign( shadow );
  13070. * //return float( 1 ); // bypass received shadows
  13071. * return shadow.mix( color( 0xff0000 ), 1 ); // modify shadow color
  13072. * } );
  13073. *
  13074. * @type {?(Function|FunctionNode<vec4>)}
  13075. * @default null
  13076. */
  13077. this.receivedShadowNode = null;
  13078. /**
  13079. * This node can be used to influence how an object using this node material
  13080. * casts shadows. To apply a color to shadows, you can simply do:
  13081. *
  13082. * ```js
  13083. * material.castShadowNode = vec4( 1, 0, 0, 1 );
  13084. * ```
  13085. *
  13086. * Which can be nice to fake colored shadows of semi-transparent objects. It
  13087. * is also common to use the property with `Fn` function so checks are performed
  13088. * per fragment.
  13089. *
  13090. * ```js
  13091. * materialCustomShadow.castShadowNode = Fn( () => {
  13092. * hash( vertexIndex ).greaterThan( 0.5 ).discard();
  13093. * return materialColor;
  13094. * } )();
  13095. * ```
  13096. *
  13097. * @type {?Node<vec4>}
  13098. * @default null
  13099. */
  13100. this.castShadowNode = null;
  13101. /**
  13102. * This node can be used to define the final output of the material.
  13103. *
  13104. * TODO: Explain the differences to `fragmentNode`.
  13105. *
  13106. * @type {?Node<vec4>}
  13107. * @default null
  13108. */
  13109. this.outputNode = null;
  13110. /**
  13111. * MRT configuration is done on renderer or pass level. This node allows to
  13112. * overwrite what values are written into MRT targets on material level. This
  13113. * can be useful for implementing selective FX features that should only affect
  13114. * specific objects.
  13115. *
  13116. * @type {?MRTNode}
  13117. * @default null
  13118. */
  13119. this.mrtNode = null;
  13120. /**
  13121. * This node property can be used if you need complete freedom in implementing
  13122. * the fragment shader. Assigning a node will replace the built-in material
  13123. * logic used in the fragment stage.
  13124. *
  13125. * @type {?Node<vec4>}
  13126. * @default null
  13127. */
  13128. this.fragmentNode = null;
  13129. /**
  13130. * This node property can be used if you need complete freedom in implementing
  13131. * the vertex shader. Assigning a node will replace the built-in material logic
  13132. * used in the vertex stage.
  13133. *
  13134. * @type {?Node<vec4>}
  13135. * @default null
  13136. */
  13137. this.vertexNode = null;
  13138. // Deprecated properties
  13139. Object.defineProperty( this, 'shadowPositionNode', { // @deprecated, r176
  13140. get: () => {
  13141. return this.receivedShadowPositionNode;
  13142. },
  13143. set: ( value ) => {
  13144. console.warn( 'THREE.NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".' );
  13145. this.receivedShadowPositionNode = value;
  13146. }
  13147. } );
  13148. }
  13149. /**
  13150. * Allows to define a custom cache key that influence the material key computation
  13151. * for render objects.
  13152. *
  13153. * @return {string} The custom cache key.
  13154. */
  13155. customProgramCacheKey() {
  13156. return this.type + getCacheKey$1( this );
  13157. }
  13158. /**
  13159. * Builds this material with the given node builder.
  13160. *
  13161. * @param {NodeBuilder} builder - The current node builder.
  13162. */
  13163. build( builder ) {
  13164. this.setup( builder );
  13165. }
  13166. /**
  13167. * Setups a node material observer with the given builder.
  13168. *
  13169. * @param {NodeBuilder} builder - The current node builder.
  13170. * @return {NodeMaterialObserver} The node material observer.
  13171. */
  13172. setupObserver( builder ) {
  13173. return new NodeMaterialObserver( builder );
  13174. }
  13175. /**
  13176. * Setups the vertex and fragment stage of this node material.
  13177. *
  13178. * @param {NodeBuilder} builder - The current node builder.
  13179. */
  13180. setup( builder ) {
  13181. builder.context.setupNormal = () => this.setupNormal( builder );
  13182. builder.context.setupPositionView = () => this.setupPositionView( builder );
  13183. builder.context.setupModelViewProjection = () => this.setupModelViewProjection( builder );
  13184. const renderer = builder.renderer;
  13185. const renderTarget = renderer.getRenderTarget();
  13186. // < VERTEX STAGE >
  13187. builder.addStack();
  13188. const mvp = this.setupVertex( builder );
  13189. const vertexNode = this.vertexNode || mvp;
  13190. builder.stack.outputNode = vertexNode;
  13191. this.setupHardwareClipping( builder );
  13192. if ( this.geometryNode !== null ) {
  13193. builder.stack.outputNode = builder.stack.outputNode.bypass( this.geometryNode );
  13194. }
  13195. builder.addFlow( 'vertex', builder.removeStack() );
  13196. // < FRAGMENT STAGE >
  13197. builder.addStack();
  13198. let resultNode;
  13199. const clippingNode = this.setupClipping( builder );
  13200. if ( this.depthWrite === true || this.depthTest === true ) {
  13201. // only write depth if depth buffer is configured
  13202. if ( renderTarget !== null ) {
  13203. if ( renderTarget.depthBuffer === true ) this.setupDepth( builder );
  13204. } else {
  13205. if ( renderer.depth === true ) this.setupDepth( builder );
  13206. }
  13207. }
  13208. if ( this.fragmentNode === null ) {
  13209. this.setupDiffuseColor( builder );
  13210. this.setupVariants( builder );
  13211. const outgoingLightNode = this.setupLighting( builder );
  13212. if ( clippingNode !== null ) builder.stack.add( clippingNode );
  13213. // force unsigned floats - useful for RenderTargets
  13214. const basicOutput = vec4( outgoingLightNode, diffuseColor.a ).max( 0 );
  13215. resultNode = this.setupOutput( builder, basicOutput );
  13216. // OUTPUT NODE
  13217. output.assign( resultNode );
  13218. //
  13219. const isCustomOutput = this.outputNode !== null;
  13220. if ( isCustomOutput ) resultNode = this.outputNode;
  13221. // MRT
  13222. if ( renderTarget !== null ) {
  13223. const mrt = renderer.getMRT();
  13224. const materialMRT = this.mrtNode;
  13225. if ( mrt !== null ) {
  13226. if ( isCustomOutput ) output.assign( resultNode );
  13227. resultNode = mrt;
  13228. if ( materialMRT !== null ) {
  13229. resultNode = mrt.merge( materialMRT );
  13230. }
  13231. } else if ( materialMRT !== null ) {
  13232. resultNode = materialMRT;
  13233. }
  13234. }
  13235. } else {
  13236. let fragmentNode = this.fragmentNode;
  13237. if ( fragmentNode.isOutputStructNode !== true ) {
  13238. fragmentNode = vec4( fragmentNode );
  13239. }
  13240. resultNode = this.setupOutput( builder, fragmentNode );
  13241. }
  13242. builder.stack.outputNode = resultNode;
  13243. builder.addFlow( 'fragment', builder.removeStack() );
  13244. // < OBSERVER >
  13245. builder.observer = this.setupObserver( builder );
  13246. }
  13247. /**
  13248. * Setups the clipping node.
  13249. *
  13250. * @param {NodeBuilder} builder - The current node builder.
  13251. * @return {ClippingNode} The clipping node.
  13252. */
  13253. setupClipping( builder ) {
  13254. if ( builder.clippingContext === null ) return null;
  13255. const { unionPlanes, intersectionPlanes } = builder.clippingContext;
  13256. let result = null;
  13257. if ( unionPlanes.length > 0 || intersectionPlanes.length > 0 ) {
  13258. const samples = builder.renderer.samples;
  13259. if ( this.alphaToCoverage && samples > 1 ) {
  13260. // to be added to flow when the color/alpha value has been determined
  13261. result = clippingAlpha();
  13262. } else {
  13263. builder.stack.add( clipping() );
  13264. }
  13265. }
  13266. return result;
  13267. }
  13268. /**
  13269. * Setups the hardware clipping if available on the current device.
  13270. *
  13271. * @param {NodeBuilder} builder - The current node builder.
  13272. */
  13273. setupHardwareClipping( builder ) {
  13274. this.hardwareClipping = false;
  13275. if ( builder.clippingContext === null ) return;
  13276. const candidateCount = builder.clippingContext.unionPlanes.length;
  13277. // 8 planes supported by WebGL ANGLE_clip_cull_distance and WebGPU clip-distances
  13278. if ( candidateCount > 0 && candidateCount <= 8 && builder.isAvailable( 'clipDistance' ) ) {
  13279. builder.stack.add( hardwareClipping() );
  13280. this.hardwareClipping = true;
  13281. }
  13282. return;
  13283. }
  13284. /**
  13285. * Setups the depth of this material.
  13286. *
  13287. * @param {NodeBuilder} builder - The current node builder.
  13288. */
  13289. setupDepth( builder ) {
  13290. const { renderer, camera } = builder;
  13291. // Depth
  13292. let depthNode = this.depthNode;
  13293. if ( depthNode === null ) {
  13294. const mrt = renderer.getMRT();
  13295. if ( mrt && mrt.has( 'depth' ) ) {
  13296. depthNode = mrt.get( 'depth' );
  13297. } else if ( renderer.logarithmicDepthBuffer === true ) {
  13298. if ( camera.isPerspectiveCamera ) {
  13299. depthNode = viewZToLogarithmicDepth( positionView.z, cameraNear, cameraFar );
  13300. } else {
  13301. depthNode = viewZToOrthographicDepth( positionView.z, cameraNear, cameraFar );
  13302. }
  13303. }
  13304. }
  13305. if ( depthNode !== null ) {
  13306. depth.assign( depthNode ).toStack();
  13307. }
  13308. }
  13309. /**
  13310. * Setups the position node in view space. This method exists
  13311. * so derived node materials can modify the implementation e.g. sprite materials.
  13312. *
  13313. * @param {NodeBuilder} builder - The current node builder.
  13314. * @return {Node<vec3>} The position in view space.
  13315. */
  13316. setupPositionView( /*builder*/ ) {
  13317. return modelViewMatrix.mul( positionLocal ).xyz;
  13318. }
  13319. /**
  13320. * Setups the position in clip space.
  13321. *
  13322. * @param {NodeBuilder} builder - The current node builder.
  13323. * @return {Node<vec4>} The position in view space.
  13324. */
  13325. setupModelViewProjection( /*builder*/ ) {
  13326. return cameraProjectionMatrix.mul( positionView );
  13327. }
  13328. /**
  13329. * Setups the logic for the vertex stage.
  13330. *
  13331. * @param {NodeBuilder} builder - The current node builder.
  13332. * @return {Node<vec4>} The position in clip space.
  13333. */
  13334. setupVertex( builder ) {
  13335. builder.addStack();
  13336. this.setupPosition( builder );
  13337. builder.context.vertex = builder.removeStack();
  13338. return modelViewProjection;
  13339. }
  13340. /**
  13341. * Setups the computation of the position in local space.
  13342. *
  13343. * @param {NodeBuilder} builder - The current node builder.
  13344. * @return {Node<vec3>} The position in local space.
  13345. */
  13346. setupPosition( builder ) {
  13347. const { object, geometry } = builder;
  13348. if ( geometry.morphAttributes.position || geometry.morphAttributes.normal || geometry.morphAttributes.color ) {
  13349. morphReference( object ).toStack();
  13350. }
  13351. if ( object.isSkinnedMesh === true ) {
  13352. skinning( object ).toStack();
  13353. }
  13354. if ( this.displacementMap ) {
  13355. const displacementMap = materialReference( 'displacementMap', 'texture' );
  13356. const displacementScale = materialReference( 'displacementScale', 'float' );
  13357. const displacementBias = materialReference( 'displacementBias', 'float' );
  13358. positionLocal.addAssign( normalLocal.normalize().mul( ( displacementMap.x.mul( displacementScale ).add( displacementBias ) ) ) );
  13359. }
  13360. if ( object.isBatchedMesh ) {
  13361. batch( object ).toStack();
  13362. }
  13363. if ( ( object.isInstancedMesh && object.instanceMatrix && object.instanceMatrix.isInstancedBufferAttribute === true ) ) {
  13364. instancedMesh( object ).toStack();
  13365. }
  13366. if ( this.positionNode !== null ) {
  13367. positionLocal.assign( namespace( this.positionNode, 'POSITION' ) );
  13368. }
  13369. return positionLocal;
  13370. }
  13371. /**
  13372. * Setups the computation of the material's diffuse color.
  13373. *
  13374. * @param {NodeBuilder} builder - The current node builder.
  13375. * @param {BufferGeometry} geometry - The geometry.
  13376. */
  13377. setupDiffuseColor( { object, geometry } ) {
  13378. // MASK
  13379. if ( this.maskNode !== null ) {
  13380. // Discard if the mask is `false`
  13381. bool( this.maskNode ).not().discard();
  13382. }
  13383. // COLOR
  13384. let colorNode = this.colorNode ? vec4( this.colorNode ) : materialColor;
  13385. // VERTEX COLORS
  13386. if ( this.vertexColors === true && geometry.hasAttribute( 'color' ) ) {
  13387. colorNode = colorNode.mul( vertexColor() );
  13388. }
  13389. // INSTANCED COLORS
  13390. if ( object.instanceColor ) {
  13391. const instanceColor = varyingProperty( 'vec3', 'vInstanceColor' );
  13392. colorNode = instanceColor.mul( colorNode );
  13393. }
  13394. if ( object.isBatchedMesh && object._colorsTexture ) {
  13395. const batchColor = varyingProperty( 'vec3', 'vBatchColor' );
  13396. colorNode = batchColor.mul( colorNode );
  13397. }
  13398. // DIFFUSE COLOR
  13399. diffuseColor.assign( colorNode );
  13400. // OPACITY
  13401. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  13402. diffuseColor.a.assign( diffuseColor.a.mul( opacityNode ) );
  13403. // ALPHA TEST
  13404. let alphaTestNode = null;
  13405. if ( this.alphaTestNode !== null || this.alphaTest > 0 ) {
  13406. alphaTestNode = this.alphaTestNode !== null ? float( this.alphaTestNode ) : materialAlphaTest;
  13407. diffuseColor.a.lessThanEqual( alphaTestNode ).discard();
  13408. }
  13409. // ALPHA HASH
  13410. if ( this.alphaHash === true ) {
  13411. diffuseColor.a.lessThan( getAlphaHashThreshold( positionLocal ) ).discard();
  13412. }
  13413. // OPAQUE
  13414. const isOpaque = this.transparent === false && this.blending === NormalBlending && this.alphaToCoverage === false;
  13415. if ( isOpaque ) {
  13416. diffuseColor.a.assign( 1.0 );
  13417. } else if ( alphaTestNode === null ) {
  13418. diffuseColor.a.lessThanEqual( 0 ).discard();
  13419. }
  13420. }
  13421. /**
  13422. * Abstract interface method that can be implemented by derived materials
  13423. * to setup material-specific node variables.
  13424. *
  13425. * @abstract
  13426. * @param {NodeBuilder} builder - The current node builder.
  13427. */
  13428. setupVariants( /*builder*/ ) {
  13429. // Interface function.
  13430. }
  13431. /**
  13432. * Setups the outgoing light node variable
  13433. *
  13434. * @return {Node<vec3>} The outgoing light node.
  13435. */
  13436. setupOutgoingLight() {
  13437. return ( this.lights === true ) ? vec3( 0 ) : diffuseColor.rgb;
  13438. }
  13439. /**
  13440. * Setups the normal node from the material.
  13441. *
  13442. * @return {Node<vec3>} The normal node.
  13443. */
  13444. setupNormal() {
  13445. return this.normalNode ? vec3( this.normalNode ) : materialNormal;
  13446. }
  13447. /**
  13448. * Setups the environment node from the material.
  13449. *
  13450. * @param {NodeBuilder} builder - The current node builder.
  13451. * @return {Node<vec4>} The environment node.
  13452. */
  13453. setupEnvironment( /*builder*/ ) {
  13454. let node = null;
  13455. if ( this.envNode ) {
  13456. node = this.envNode;
  13457. } else if ( this.envMap ) {
  13458. node = this.envMap.isCubeTexture ? materialReference( 'envMap', 'cubeTexture' ) : materialReference( 'envMap', 'texture' );
  13459. }
  13460. return node;
  13461. }
  13462. /**
  13463. * Setups the light map node from the material.
  13464. *
  13465. * @param {NodeBuilder} builder - The current node builder.
  13466. * @return {Node<vec3>} The light map node.
  13467. */
  13468. setupLightMap( builder ) {
  13469. let node = null;
  13470. if ( builder.material.lightMap ) {
  13471. node = new IrradianceNode( materialLightMap );
  13472. }
  13473. return node;
  13474. }
  13475. /**
  13476. * Setups the lights node based on the scene, environment and material.
  13477. *
  13478. * @param {NodeBuilder} builder - The current node builder.
  13479. * @return {LightsNode} The lights node.
  13480. */
  13481. setupLights( builder ) {
  13482. const materialLightsNode = [];
  13483. //
  13484. const envNode = this.setupEnvironment( builder );
  13485. if ( envNode && envNode.isLightingNode ) {
  13486. materialLightsNode.push( envNode );
  13487. }
  13488. const lightMapNode = this.setupLightMap( builder );
  13489. if ( lightMapNode && lightMapNode.isLightingNode ) {
  13490. materialLightsNode.push( lightMapNode );
  13491. }
  13492. if ( this.aoNode !== null || builder.material.aoMap ) {
  13493. const aoNode = this.aoNode !== null ? this.aoNode : materialAO;
  13494. materialLightsNode.push( new AONode( aoNode ) );
  13495. }
  13496. let lightsN = this.lightsNode || builder.lightsNode;
  13497. if ( materialLightsNode.length > 0 ) {
  13498. lightsN = builder.renderer.lighting.createNode( [ ...lightsN.getLights(), ...materialLightsNode ] );
  13499. }
  13500. return lightsN;
  13501. }
  13502. /**
  13503. * This method should be implemented by most derived materials
  13504. * since it defines the material's lighting model.
  13505. *
  13506. * @abstract
  13507. * @param {NodeBuilder} builder - The current node builder.
  13508. * @return {LightingModel} The lighting model.
  13509. */
  13510. setupLightingModel( /*builder*/ ) {
  13511. // Interface function.
  13512. }
  13513. /**
  13514. * Setups the outgoing light node.
  13515. *
  13516. * @param {NodeBuilder} builder - The current node builder.
  13517. * @return {Node<vec3>} The outgoing light node.
  13518. */
  13519. setupLighting( builder ) {
  13520. const { material } = builder;
  13521. const { backdropNode, backdropAlphaNode, emissiveNode } = this;
  13522. // OUTGOING LIGHT
  13523. const lights = this.lights === true || this.lightsNode !== null;
  13524. const lightsNode = lights ? this.setupLights( builder ) : null;
  13525. let outgoingLightNode = this.setupOutgoingLight( builder );
  13526. if ( lightsNode && lightsNode.getScope().hasLights ) {
  13527. const lightingModel = this.setupLightingModel( builder ) || null;
  13528. outgoingLightNode = lightingContext( lightsNode, lightingModel, backdropNode, backdropAlphaNode );
  13529. } else if ( backdropNode !== null ) {
  13530. outgoingLightNode = vec3( backdropAlphaNode !== null ? mix( outgoingLightNode, backdropNode, backdropAlphaNode ) : backdropNode );
  13531. }
  13532. // EMISSIVE
  13533. if ( ( emissiveNode && emissiveNode.isNode === true ) || ( material.emissive && material.emissive.isColor === true ) ) {
  13534. emissive.assign( vec3( emissiveNode ? emissiveNode : materialEmissive ) );
  13535. outgoingLightNode = outgoingLightNode.add( emissive );
  13536. }
  13537. return outgoingLightNode;
  13538. }
  13539. /**
  13540. * Setup the fog.
  13541. *
  13542. * @param {NodeBuilder} builder - The current node builder.
  13543. * @param {Node<vec4>} outputNode - The existing output node.
  13544. * @return {Node<vec4>} The output node.
  13545. */
  13546. setupFog( builder, outputNode ) {
  13547. const fogNode = builder.fogNode;
  13548. if ( fogNode ) {
  13549. output.assign( outputNode );
  13550. outputNode = vec4( fogNode );
  13551. }
  13552. return outputNode;
  13553. }
  13554. /**
  13555. * Setups premultiplied alpha.
  13556. *
  13557. * @param {NodeBuilder} builder - The current node builder.
  13558. * @param {Node<vec4>} outputNode - The existing output node.
  13559. * @return {Node<vec4>} The output node.
  13560. */
  13561. setupPremultipliedAlpha( builder, outputNode ) {
  13562. return premultiplyAlpha( outputNode );
  13563. }
  13564. /**
  13565. * Setups the output node.
  13566. *
  13567. * @param {NodeBuilder} builder - The current node builder.
  13568. * @param {Node<vec4>} outputNode - The existing output node.
  13569. * @return {Node<vec4>} The output node.
  13570. */
  13571. setupOutput( builder, outputNode ) {
  13572. // FOG
  13573. if ( this.fog === true ) {
  13574. outputNode = this.setupFog( builder, outputNode );
  13575. }
  13576. // PREMULTIPLIED ALPHA
  13577. if ( this.premultipliedAlpha === true ) {
  13578. outputNode = this.setupPremultipliedAlpha( builder, outputNode );
  13579. }
  13580. return outputNode;
  13581. }
  13582. /**
  13583. * Most classic material types have a node pendant e.g. for `MeshBasicMaterial`
  13584. * there is `MeshBasicNodeMaterial`. This utility method is intended for
  13585. * defining all material properties of the classic type in the node type.
  13586. *
  13587. * @param {Material} material - The material to copy properties with their values to this node material.
  13588. */
  13589. setDefaultValues( material ) {
  13590. // This approach is to reuse the native refreshUniforms*
  13591. // and turn available the use of features like transmission and environment in core
  13592. for ( const property in material ) {
  13593. const value = material[ property ];
  13594. if ( this[ property ] === undefined ) {
  13595. this[ property ] = value;
  13596. if ( value && value.clone ) this[ property ] = value.clone();
  13597. }
  13598. }
  13599. const descriptors = Object.getOwnPropertyDescriptors( material.constructor.prototype );
  13600. for ( const key in descriptors ) {
  13601. if ( Object.getOwnPropertyDescriptor( this.constructor.prototype, key ) === undefined &&
  13602. descriptors[ key ].get !== undefined ) {
  13603. Object.defineProperty( this.constructor.prototype, key, descriptors[ key ] );
  13604. }
  13605. }
  13606. }
  13607. /**
  13608. * Serializes this material to JSON.
  13609. *
  13610. * @param {?(Object|string)} meta - The meta information for serialization.
  13611. * @return {Object} The serialized node.
  13612. */
  13613. toJSON( meta ) {
  13614. const isRoot = ( meta === undefined || typeof meta === 'string' );
  13615. if ( isRoot ) {
  13616. meta = {
  13617. textures: {},
  13618. images: {},
  13619. nodes: {}
  13620. };
  13621. }
  13622. const data = Material.prototype.toJSON.call( this, meta );
  13623. const nodeChildren = getNodeChildren( this );
  13624. data.inputNodes = {};
  13625. for ( const { property, childNode } of nodeChildren ) {
  13626. data.inputNodes[ property ] = childNode.toJSON( meta ).uuid;
  13627. }
  13628. // TODO: Copied from Object3D.toJSON
  13629. function extractFromCache( cache ) {
  13630. const values = [];
  13631. for ( const key in cache ) {
  13632. const data = cache[ key ];
  13633. delete data.metadata;
  13634. values.push( data );
  13635. }
  13636. return values;
  13637. }
  13638. if ( isRoot ) {
  13639. const textures = extractFromCache( meta.textures );
  13640. const images = extractFromCache( meta.images );
  13641. const nodes = extractFromCache( meta.nodes );
  13642. if ( textures.length > 0 ) data.textures = textures;
  13643. if ( images.length > 0 ) data.images = images;
  13644. if ( nodes.length > 0 ) data.nodes = nodes;
  13645. }
  13646. return data;
  13647. }
  13648. /**
  13649. * Copies the properties of the given node material to this instance.
  13650. *
  13651. * @param {NodeMaterial} source - The material to copy.
  13652. * @return {NodeMaterial} A reference to this node material.
  13653. */
  13654. copy( source ) {
  13655. this.lightsNode = source.lightsNode;
  13656. this.envNode = source.envNode;
  13657. this.colorNode = source.colorNode;
  13658. this.normalNode = source.normalNode;
  13659. this.opacityNode = source.opacityNode;
  13660. this.backdropNode = source.backdropNode;
  13661. this.backdropAlphaNode = source.backdropAlphaNode;
  13662. this.alphaTestNode = source.alphaTestNode;
  13663. this.maskNode = source.maskNode;
  13664. this.positionNode = source.positionNode;
  13665. this.geometryNode = source.geometryNode;
  13666. this.depthNode = source.depthNode;
  13667. this.receivedShadowPositionNode = source.receivedShadowPositionNode;
  13668. this.castShadowPositionNode = source.castShadowPositionNode;
  13669. this.receivedShadowNode = source.receivedShadowNode;
  13670. this.castShadowNode = source.castShadowNode;
  13671. this.outputNode = source.outputNode;
  13672. this.mrtNode = source.mrtNode;
  13673. this.fragmentNode = source.fragmentNode;
  13674. this.vertexNode = source.vertexNode;
  13675. return super.copy( source );
  13676. }
  13677. }
  13678. const _defaultValues$d = /*@__PURE__*/ new LineBasicMaterial();
  13679. /**
  13680. * Node material version of {@link LineBasicMaterial}.
  13681. *
  13682. * @augments NodeMaterial
  13683. */
  13684. class LineBasicNodeMaterial extends NodeMaterial {
  13685. static get type() {
  13686. return 'LineBasicNodeMaterial';
  13687. }
  13688. /**
  13689. * Constructs a new line basic node material.
  13690. *
  13691. * @param {Object} [parameters] - The configuration parameter.
  13692. */
  13693. constructor( parameters ) {
  13694. super();
  13695. /**
  13696. * This flag can be used for type testing.
  13697. *
  13698. * @type {boolean}
  13699. * @readonly
  13700. * @default true
  13701. */
  13702. this.isLineBasicNodeMaterial = true;
  13703. this.setDefaultValues( _defaultValues$d );
  13704. this.setValues( parameters );
  13705. }
  13706. }
  13707. const _defaultValues$c = /*@__PURE__*/ new LineDashedMaterial();
  13708. /**
  13709. * Node material version of {@link LineDashedMaterial}.
  13710. *
  13711. * @augments NodeMaterial
  13712. */
  13713. class LineDashedNodeMaterial extends NodeMaterial {
  13714. static get type() {
  13715. return 'LineDashedNodeMaterial';
  13716. }
  13717. /**
  13718. * Constructs a new line dashed node material.
  13719. *
  13720. * @param {Object} [parameters] - The configuration parameter.
  13721. */
  13722. constructor( parameters ) {
  13723. super();
  13724. /**
  13725. * This flag can be used for type testing.
  13726. *
  13727. * @type {boolean}
  13728. * @readonly
  13729. * @default true
  13730. */
  13731. this.isLineDashedNodeMaterial = true;
  13732. this.setDefaultValues( _defaultValues$c );
  13733. /**
  13734. * The dash offset.
  13735. *
  13736. * @type {number}
  13737. * @default 0
  13738. */
  13739. this.dashOffset = 0;
  13740. /**
  13741. * The offset of dash materials is by default inferred from the `dashOffset`
  13742. * property. This node property allows to overwrite the default
  13743. * and define the offset with a node instead.
  13744. *
  13745. * If you don't want to overwrite the offset but modify the existing
  13746. * value instead, use {@link materialLineDashOffset}.
  13747. *
  13748. * @type {?Node<float>}
  13749. * @default null
  13750. */
  13751. this.offsetNode = null;
  13752. /**
  13753. * The scale of dash materials is by default inferred from the `scale`
  13754. * property. This node property allows to overwrite the default
  13755. * and define the scale with a node instead.
  13756. *
  13757. * If you don't want to overwrite the scale but modify the existing
  13758. * value instead, use {@link materialLineScale}.
  13759. *
  13760. * @type {?Node<float>}
  13761. * @default null
  13762. */
  13763. this.dashScaleNode = null;
  13764. /**
  13765. * The dash size of dash materials is by default inferred from the `dashSize`
  13766. * property. This node property allows to overwrite the default
  13767. * and define the dash size with a node instead.
  13768. *
  13769. * If you don't want to overwrite the dash size but modify the existing
  13770. * value instead, use {@link materialLineDashSize}.
  13771. *
  13772. * @type {?Node<float>}
  13773. * @default null
  13774. */
  13775. this.dashSizeNode = null;
  13776. /**
  13777. * The gap size of dash materials is by default inferred from the `gapSize`
  13778. * property. This node property allows to overwrite the default
  13779. * and define the gap size with a node instead.
  13780. *
  13781. * If you don't want to overwrite the gap size but modify the existing
  13782. * value instead, use {@link materialLineGapSize}.
  13783. *
  13784. * @type {?Node<float>}
  13785. * @default null
  13786. */
  13787. this.gapSizeNode = null;
  13788. this.setValues( parameters );
  13789. }
  13790. /**
  13791. * Setups the dash specific node variables.
  13792. *
  13793. * @param {NodeBuilder} builder - The current node builder.
  13794. */
  13795. setupVariants( /* builder */ ) {
  13796. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  13797. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  13798. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  13799. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  13800. dashSize.assign( dashSizeNode );
  13801. gapSize.assign( gapSizeNode );
  13802. const vLineDistance = varying( attribute( 'lineDistance' ).mul( dashScaleNode ) );
  13803. const vLineDistanceOffset = offsetNode ? vLineDistance.add( offsetNode ) : vLineDistance;
  13804. vLineDistanceOffset.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard();
  13805. }
  13806. }
  13807. let _sharedFramebuffer = null;
  13808. /**
  13809. * `ViewportTextureNode` creates an internal texture for each node instance. This module
  13810. * shares a texture across all instances of `ViewportSharedTextureNode`. It should
  13811. * be the first choice when using data of the default/screen framebuffer for performance reasons.
  13812. *
  13813. * @augments ViewportTextureNode
  13814. */
  13815. class ViewportSharedTextureNode extends ViewportTextureNode {
  13816. static get type() {
  13817. return 'ViewportSharedTextureNode';
  13818. }
  13819. /**
  13820. * Constructs a new viewport shared texture node.
  13821. *
  13822. * @param {Node} [uvNode=screenUV] - The uv node.
  13823. * @param {?Node} [levelNode=null] - The level node.
  13824. */
  13825. constructor( uvNode = screenUV, levelNode = null ) {
  13826. if ( _sharedFramebuffer === null ) {
  13827. _sharedFramebuffer = new FramebufferTexture();
  13828. }
  13829. super( uvNode, levelNode, _sharedFramebuffer );
  13830. }
  13831. updateReference() {
  13832. return this;
  13833. }
  13834. }
  13835. /**
  13836. * TSL function for creating a shared viewport texture node.
  13837. *
  13838. * @tsl
  13839. * @function
  13840. * @param {?Node} [uvNode=screenUV] - The uv node.
  13841. * @param {?Node} [levelNode=null] - The level node.
  13842. * @returns {ViewportSharedTextureNode}
  13843. */
  13844. const viewportSharedTexture = /*@__PURE__*/ nodeProxy( ViewportSharedTextureNode ).setParameterLength( 0, 2 );
  13845. const _defaultValues$b = /*@__PURE__*/ new LineDashedMaterial();
  13846. /**
  13847. * This node material can be used to render lines with a size larger than one
  13848. * by representing them as instanced meshes.
  13849. *
  13850. * @augments NodeMaterial
  13851. */
  13852. class Line2NodeMaterial extends NodeMaterial {
  13853. static get type() {
  13854. return 'Line2NodeMaterial';
  13855. }
  13856. /**
  13857. * Constructs a new node material for wide line rendering.
  13858. *
  13859. * @param {Object} [parameters={}] - The configuration parameter.
  13860. */
  13861. constructor( parameters = {} ) {
  13862. super();
  13863. /**
  13864. * This flag can be used for type testing.
  13865. *
  13866. * @type {boolean}
  13867. * @readonly
  13868. * @default true
  13869. */
  13870. this.isLine2NodeMaterial = true;
  13871. this.setDefaultValues( _defaultValues$b );
  13872. /**
  13873. * Whether vertex colors should be used or not.
  13874. *
  13875. * @type {boolean}
  13876. * @default false
  13877. */
  13878. this.useColor = parameters.vertexColors;
  13879. /**
  13880. * The dash offset.
  13881. *
  13882. * @type {number}
  13883. * @default 0
  13884. */
  13885. this.dashOffset = 0;
  13886. /**
  13887. * The line width.
  13888. *
  13889. * @type {number}
  13890. * @default 0
  13891. */
  13892. this.lineWidth = 1;
  13893. /**
  13894. * Defines the lines color.
  13895. *
  13896. * @type {?Node<vec3>}
  13897. * @default null
  13898. */
  13899. this.lineColorNode = null;
  13900. /**
  13901. * Defines the offset.
  13902. *
  13903. * @type {?Node<float>}
  13904. * @default null
  13905. */
  13906. this.offsetNode = null;
  13907. /**
  13908. * Defines the dash scale.
  13909. *
  13910. * @type {?Node<float>}
  13911. * @default null
  13912. */
  13913. this.dashScaleNode = null;
  13914. /**
  13915. * Defines the dash size.
  13916. *
  13917. * @type {?Node<float>}
  13918. * @default null
  13919. */
  13920. this.dashSizeNode = null;
  13921. /**
  13922. * Defines the gap size.
  13923. *
  13924. * @type {?Node<float>}
  13925. * @default null
  13926. */
  13927. this.gapSizeNode = null;
  13928. /**
  13929. * Blending is set to `NoBlending` since transparency
  13930. * is not supported, yet.
  13931. *
  13932. * @type {number}
  13933. * @default 0
  13934. */
  13935. this.blending = NoBlending;
  13936. this._useDash = parameters.dashed;
  13937. this._useAlphaToCoverage = true;
  13938. this._useWorldUnits = false;
  13939. this.setValues( parameters );
  13940. }
  13941. /**
  13942. * Setups the vertex and fragment stage of this node material.
  13943. *
  13944. * @param {NodeBuilder} builder - The current node builder.
  13945. */
  13946. setup( builder ) {
  13947. const { renderer } = builder;
  13948. const useAlphaToCoverage = this._useAlphaToCoverage;
  13949. const useColor = this.useColor;
  13950. const useDash = this._useDash;
  13951. const useWorldUnits = this._useWorldUnits;
  13952. const trimSegment = Fn( ( { start, end } ) => {
  13953. const a = cameraProjectionMatrix.element( 2 ).element( 2 ); // 3nd entry in 3th column
  13954. const b = cameraProjectionMatrix.element( 3 ).element( 2 ); // 3nd entry in 4th column
  13955. const nearEstimate = b.mul( -0.5 ).div( a );
  13956. const alpha = nearEstimate.sub( start.z ).div( end.z.sub( start.z ) );
  13957. return vec4( mix( start.xyz, end.xyz, alpha ), end.w );
  13958. } ).setLayout( {
  13959. name: 'trimSegment',
  13960. type: 'vec4',
  13961. inputs: [
  13962. { name: 'start', type: 'vec4' },
  13963. { name: 'end', type: 'vec4' }
  13964. ]
  13965. } );
  13966. this.vertexNode = Fn( () => {
  13967. const instanceStart = attribute( 'instanceStart' );
  13968. const instanceEnd = attribute( 'instanceEnd' );
  13969. // camera space
  13970. const start = vec4( modelViewMatrix.mul( vec4( instanceStart, 1.0 ) ) ).toVar( 'start' );
  13971. const end = vec4( modelViewMatrix.mul( vec4( instanceEnd, 1.0 ) ) ).toVar( 'end' );
  13972. if ( useDash ) {
  13973. const dashScaleNode = this.dashScaleNode ? float( this.dashScaleNode ) : materialLineScale;
  13974. const offsetNode = this.offsetNode ? float( this.offsetNode ) : materialLineDashOffset;
  13975. const instanceDistanceStart = attribute( 'instanceDistanceStart' );
  13976. const instanceDistanceEnd = attribute( 'instanceDistanceEnd' );
  13977. let lineDistance = positionGeometry.y.lessThan( 0.5 ).select( dashScaleNode.mul( instanceDistanceStart ), dashScaleNode.mul( instanceDistanceEnd ) );
  13978. lineDistance = lineDistance.add( offsetNode );
  13979. varyingProperty( 'float', 'lineDistance' ).assign( lineDistance );
  13980. }
  13981. if ( useWorldUnits ) {
  13982. varyingProperty( 'vec3', 'worldStart' ).assign( start.xyz );
  13983. varyingProperty( 'vec3', 'worldEnd' ).assign( end.xyz );
  13984. }
  13985. const aspect = viewport.z.div( viewport.w );
  13986. // special case for perspective projection, and segments that terminate either in, or behind, the camera plane
  13987. // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space
  13988. // but we need to perform ndc-space calculations in the shader, so we must address this issue directly
  13989. // perhaps there is a more elegant solution -- WestLangley
  13990. const perspective = cameraProjectionMatrix.element( 2 ).element( 3 ).equal( -1 ); // 4th entry in the 3rd column
  13991. If( perspective, () => {
  13992. If( start.z.lessThan( 0.0 ).and( end.z.greaterThan( 0.0 ) ), () => {
  13993. end.assign( trimSegment( { start: start, end: end } ) );
  13994. } ).ElseIf( end.z.lessThan( 0.0 ).and( start.z.greaterThanEqual( 0.0 ) ), () => {
  13995. start.assign( trimSegment( { start: end, end: start } ) );
  13996. } );
  13997. } );
  13998. // clip space
  13999. const clipStart = cameraProjectionMatrix.mul( start );
  14000. const clipEnd = cameraProjectionMatrix.mul( end );
  14001. // ndc space
  14002. const ndcStart = clipStart.xyz.div( clipStart.w );
  14003. const ndcEnd = clipEnd.xyz.div( clipEnd.w );
  14004. // direction
  14005. const dir = ndcEnd.xy.sub( ndcStart.xy ).toVar();
  14006. // account for clip-space aspect ratio
  14007. dir.x.assign( dir.x.mul( aspect ) );
  14008. dir.assign( dir.normalize() );
  14009. const clip = vec4().toVar();
  14010. if ( useWorldUnits ) {
  14011. // get the offset direction as perpendicular to the view vector
  14012. const worldDir = end.xyz.sub( start.xyz ).normalize();
  14013. const tmpFwd = mix( start.xyz, end.xyz, 0.5 ).normalize();
  14014. const worldUp = worldDir.cross( tmpFwd ).normalize();
  14015. const worldFwd = worldDir.cross( worldUp );
  14016. const worldPos = varyingProperty( 'vec4', 'worldPos' );
  14017. worldPos.assign( positionGeometry.y.lessThan( 0.5 ).select( start, end ) );
  14018. // height offset
  14019. const hw = materialLineWidth.mul( 0.5 );
  14020. worldPos.addAssign( vec4( positionGeometry.x.lessThan( 0.0 ).select( worldUp.mul( hw ), worldUp.mul( hw ).negate() ), 0 ) );
  14021. // don't extend the line if we're rendering dashes because we
  14022. // won't be rendering the endcaps
  14023. if ( ! useDash ) {
  14024. // cap extension
  14025. worldPos.addAssign( vec4( positionGeometry.y.lessThan( 0.5 ).select( worldDir.mul( hw ).negate(), worldDir.mul( hw ) ), 0 ) );
  14026. // add width to the box
  14027. worldPos.addAssign( vec4( worldFwd.mul( hw ), 0 ) );
  14028. // endcaps
  14029. If( positionGeometry.y.greaterThan( 1.0 ).or( positionGeometry.y.lessThan( 0.0 ) ), () => {
  14030. worldPos.subAssign( vec4( worldFwd.mul( 2.0 ).mul( hw ), 0 ) );
  14031. } );
  14032. }
  14033. // project the worldpos
  14034. clip.assign( cameraProjectionMatrix.mul( worldPos ) );
  14035. // shift the depth of the projected points so the line
  14036. // segments overlap neatly
  14037. const clipPose = vec3().toVar();
  14038. clipPose.assign( positionGeometry.y.lessThan( 0.5 ).select( ndcStart, ndcEnd ) );
  14039. clip.z.assign( clipPose.z.mul( clip.w ) );
  14040. } else {
  14041. const offset = vec2( dir.y, dir.x.negate() ).toVar( 'offset' );
  14042. // undo aspect ratio adjustment
  14043. dir.x.assign( dir.x.div( aspect ) );
  14044. offset.x.assign( offset.x.div( aspect ) );
  14045. // sign flip
  14046. offset.assign( positionGeometry.x.lessThan( 0.0 ).select( offset.negate(), offset ) );
  14047. // endcaps
  14048. If( positionGeometry.y.lessThan( 0.0 ), () => {
  14049. offset.assign( offset.sub( dir ) );
  14050. } ).ElseIf( positionGeometry.y.greaterThan( 1.0 ), () => {
  14051. offset.assign( offset.add( dir ) );
  14052. } );
  14053. // adjust for linewidth
  14054. offset.assign( offset.mul( materialLineWidth ) );
  14055. // adjust for clip-space to screen-space conversion // maybe resolution should be based on viewport ...
  14056. offset.assign( offset.div( viewport.w ) );
  14057. // select end
  14058. clip.assign( positionGeometry.y.lessThan( 0.5 ).select( clipStart, clipEnd ) );
  14059. // back to clip space
  14060. offset.assign( offset.mul( clip.w ) );
  14061. clip.assign( clip.add( vec4( offset, 0, 0 ) ) );
  14062. }
  14063. return clip;
  14064. } )();
  14065. const closestLineToLine = Fn( ( { p1, p2, p3, p4 } ) => {
  14066. const p13 = p1.sub( p3 );
  14067. const p43 = p4.sub( p3 );
  14068. const p21 = p2.sub( p1 );
  14069. const d1343 = p13.dot( p43 );
  14070. const d4321 = p43.dot( p21 );
  14071. const d1321 = p13.dot( p21 );
  14072. const d4343 = p43.dot( p43 );
  14073. const d2121 = p21.dot( p21 );
  14074. const denom = d2121.mul( d4343 ).sub( d4321.mul( d4321 ) );
  14075. const numer = d1343.mul( d4321 ).sub( d1321.mul( d4343 ) );
  14076. const mua = numer.div( denom ).clamp();
  14077. const mub = d1343.add( d4321.mul( mua ) ).div( d4343 ).clamp();
  14078. return vec2( mua, mub );
  14079. } );
  14080. this.colorNode = Fn( () => {
  14081. const vUv = uv();
  14082. if ( useDash ) {
  14083. const dashSizeNode = this.dashSizeNode ? float( this.dashSizeNode ) : materialLineDashSize;
  14084. const gapSizeNode = this.gapSizeNode ? float( this.gapSizeNode ) : materialLineGapSize;
  14085. dashSize.assign( dashSizeNode );
  14086. gapSize.assign( gapSizeNode );
  14087. const vLineDistance = varyingProperty( 'float', 'lineDistance' );
  14088. vUv.y.lessThan( -1 ).or( vUv.y.greaterThan( 1.0 ) ).discard(); // discard endcaps
  14089. vLineDistance.mod( dashSize.add( gapSize ) ).greaterThan( dashSize ).discard(); // todo - FIX
  14090. }
  14091. const alpha = float( 1 ).toVar( 'alpha' );
  14092. if ( useWorldUnits ) {
  14093. const worldStart = varyingProperty( 'vec3', 'worldStart' );
  14094. const worldEnd = varyingProperty( 'vec3', 'worldEnd' );
  14095. // Find the closest points on the view ray and the line segment
  14096. const rayEnd = varyingProperty( 'vec4', 'worldPos' ).xyz.normalize().mul( 1e5 );
  14097. const lineDir = worldEnd.sub( worldStart );
  14098. const params = closestLineToLine( { p1: worldStart, p2: worldEnd, p3: vec3( 0.0, 0.0, 0.0 ), p4: rayEnd } );
  14099. const p1 = worldStart.add( lineDir.mul( params.x ) );
  14100. const p2 = rayEnd.mul( params.y );
  14101. const delta = p1.sub( p2 );
  14102. const len = delta.length();
  14103. const norm = len.div( materialLineWidth );
  14104. if ( ! useDash ) {
  14105. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  14106. const dnorm = norm.fwidth();
  14107. alpha.assign( smoothstep( dnorm.negate().add( 0.5 ), dnorm.add( 0.5 ), norm ).oneMinus() );
  14108. } else {
  14109. norm.greaterThan( 0.5 ).discard();
  14110. }
  14111. }
  14112. } else {
  14113. // round endcaps
  14114. if ( useAlphaToCoverage && renderer.samples > 1 ) {
  14115. const a = vUv.x;
  14116. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  14117. const len2 = a.mul( a ).add( b.mul( b ) );
  14118. const dlen = float( len2.fwidth() ).toVar( 'dlen' );
  14119. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  14120. alpha.assign( smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus() );
  14121. } );
  14122. } else {
  14123. If( vUv.y.abs().greaterThan( 1.0 ), () => {
  14124. const a = vUv.x;
  14125. const b = vUv.y.greaterThan( 0.0 ).select( vUv.y.sub( 1.0 ), vUv.y.add( 1.0 ) );
  14126. const len2 = a.mul( a ).add( b.mul( b ) );
  14127. len2.greaterThan( 1.0 ).discard();
  14128. } );
  14129. }
  14130. }
  14131. let lineColorNode;
  14132. if ( this.lineColorNode ) {
  14133. lineColorNode = this.lineColorNode;
  14134. } else {
  14135. if ( useColor ) {
  14136. const instanceColorStart = attribute( 'instanceColorStart' );
  14137. const instanceColorEnd = attribute( 'instanceColorEnd' );
  14138. const instanceColor = positionGeometry.y.lessThan( 0.5 ).select( instanceColorStart, instanceColorEnd );
  14139. lineColorNode = instanceColor.mul( materialColor );
  14140. } else {
  14141. lineColorNode = materialColor;
  14142. }
  14143. }
  14144. return vec4( lineColorNode, alpha );
  14145. } )();
  14146. if ( this.transparent ) {
  14147. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14148. this.outputNode = vec4( this.colorNode.rgb.mul( opacityNode ).add( viewportSharedTexture().rgb.mul( opacityNode.oneMinus() ) ), this.colorNode.a );
  14149. }
  14150. super.setup( builder );
  14151. }
  14152. /**
  14153. * Whether the lines should sized in world units or not.
  14154. * When set to `false` the unit is pixel.
  14155. *
  14156. * @type {boolean}
  14157. * @default false
  14158. */
  14159. get worldUnits() {
  14160. return this._useWorldUnits;
  14161. }
  14162. set worldUnits( value ) {
  14163. if ( this._useWorldUnits !== value ) {
  14164. this._useWorldUnits = value;
  14165. this.needsUpdate = true;
  14166. }
  14167. }
  14168. /**
  14169. * Whether the lines should be dashed or not.
  14170. *
  14171. * @type {boolean}
  14172. * @default false
  14173. */
  14174. get dashed() {
  14175. return this._useDash;
  14176. }
  14177. set dashed( value ) {
  14178. if ( this._useDash !== value ) {
  14179. this._useDash = value;
  14180. this.needsUpdate = true;
  14181. }
  14182. }
  14183. /**
  14184. * Whether alpha to coverage should be used or not.
  14185. *
  14186. * @type {boolean}
  14187. * @default true
  14188. */
  14189. get alphaToCoverage() {
  14190. return this._useAlphaToCoverage;
  14191. }
  14192. set alphaToCoverage( value ) {
  14193. if ( this._useAlphaToCoverage !== value ) {
  14194. this._useAlphaToCoverage = value;
  14195. this.needsUpdate = true;
  14196. }
  14197. }
  14198. }
  14199. /**
  14200. * Packs a direction vector into a color value.
  14201. *
  14202. * @tsl
  14203. * @function
  14204. * @param {Node<vec3>} node - The direction to pack.
  14205. * @return {Node<vec3>} The color.
  14206. */
  14207. const directionToColor = ( node ) => nodeObject( node ).mul( 0.5 ).add( 0.5 );
  14208. /**
  14209. * Unpacks a color value into a direction vector.
  14210. *
  14211. * @tsl
  14212. * @function
  14213. * @param {Node<vec3>} node - The color to unpack.
  14214. * @return {Node<vec3>} The direction.
  14215. */
  14216. const colorToDirection = ( node ) => nodeObject( node ).mul( 2.0 ).sub( 1 );
  14217. const _defaultValues$a = /*@__PURE__*/ new MeshNormalMaterial();
  14218. /**
  14219. * Node material version of {@link MeshNormalMaterial}.
  14220. *
  14221. * @augments NodeMaterial
  14222. */
  14223. class MeshNormalNodeMaterial extends NodeMaterial {
  14224. static get type() {
  14225. return 'MeshNormalNodeMaterial';
  14226. }
  14227. /**
  14228. * Constructs a new mesh normal node material.
  14229. *
  14230. * @param {Object} [parameters] - The configuration parameter.
  14231. */
  14232. constructor( parameters ) {
  14233. super();
  14234. /**
  14235. * This flag can be used for type testing.
  14236. *
  14237. * @type {boolean}
  14238. * @readonly
  14239. * @default true
  14240. */
  14241. this.isMeshNormalNodeMaterial = true;
  14242. this.setDefaultValues( _defaultValues$a );
  14243. this.setValues( parameters );
  14244. }
  14245. /**
  14246. * Overwrites the default implementation by computing the diffuse color
  14247. * based on the normal data.
  14248. */
  14249. setupDiffuseColor() {
  14250. const opacityNode = this.opacityNode ? float( this.opacityNode ) : materialOpacity;
  14251. // By convention, a normal packed to RGB is in sRGB color space. Convert it to working color space.
  14252. diffuseColor.assign( colorSpaceToWorking( vec4( directionToColor( transformedNormalView ), opacityNode ), SRGBColorSpace ) );
  14253. }
  14254. }
  14255. /**
  14256. * Can be used to compute texture coordinates for projecting an
  14257. * equirectangular texture onto a mesh for using it as the scene's
  14258. * background.
  14259. *
  14260. * ```js
  14261. * scene.backgroundNode = texture( equirectTexture, equirectUV() );
  14262. * ```
  14263. *
  14264. * @augments TempNode
  14265. */
  14266. class EquirectUVNode extends TempNode {
  14267. static get type() {
  14268. return 'EquirectUVNode';
  14269. }
  14270. /**
  14271. * Constructs a new equirect uv node.
  14272. *
  14273. * @param {Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  14274. */
  14275. constructor( dirNode = positionWorldDirection ) {
  14276. super( 'vec2' );
  14277. /**
  14278. * A direction vector for sampling why is by default `positionWorldDirection`.
  14279. *
  14280. * @type {Node<vec3>}
  14281. */
  14282. this.dirNode = dirNode;
  14283. }
  14284. setup() {
  14285. const dir = this.dirNode;
  14286. const u = dir.z.atan( dir.x ).mul( 1 / ( Math.PI * 2 ) ).add( 0.5 );
  14287. const v = dir.y.clamp( -1, 1.0 ).asin().mul( 1 / Math.PI ).add( 0.5 );
  14288. return vec2( u, v );
  14289. }
  14290. }
  14291. /**
  14292. * TSL function for creating an equirect uv node.
  14293. *
  14294. * @tsl
  14295. * @function
  14296. * @param {?Node<vec3>} [dirNode=positionWorldDirection] - A direction vector for sampling which is by default `positionWorldDirection`.
  14297. * @returns {EquirectUVNode}
  14298. */
  14299. const equirectUV = /*@__PURE__*/ nodeProxy( EquirectUVNode ).setParameterLength( 0, 1 );
  14300. // @TODO: Consider rename WebGLCubeRenderTarget to just CubeRenderTarget
  14301. /**
  14302. * This class represents a cube render target. It is a special version
  14303. * of `WebGLCubeRenderTarget` which is compatible with `WebGPURenderer`.
  14304. *
  14305. * @augments WebGLCubeRenderTarget
  14306. */
  14307. class CubeRenderTarget extends WebGLCubeRenderTarget {
  14308. /**
  14309. * Constructs a new cube render target.
  14310. *
  14311. * @param {number} [size=1] - The size of the render target.
  14312. * @param {RenderTarget~Options} [options] - The configuration object.
  14313. */
  14314. constructor( size = 1, options = {} ) {
  14315. super( size, options );
  14316. /**
  14317. * This flag can be used for type testing.
  14318. *
  14319. * @type {boolean}
  14320. * @readonly
  14321. * @default true
  14322. */
  14323. this.isCubeRenderTarget = true;
  14324. }
  14325. /**
  14326. * Converts the given equirectangular texture to a cube map.
  14327. *
  14328. * @param {Renderer} renderer - The renderer.
  14329. * @param {Texture} texture - The equirectangular texture.
  14330. * @return {CubeRenderTarget} A reference to this cube render target.
  14331. */
  14332. fromEquirectangularTexture( renderer, texture$1 ) {
  14333. const currentMinFilter = texture$1.minFilter;
  14334. const currentGenerateMipmaps = texture$1.generateMipmaps;
  14335. texture$1.generateMipmaps = true;
  14336. this.texture.type = texture$1.type;
  14337. this.texture.colorSpace = texture$1.colorSpace;
  14338. this.texture.generateMipmaps = texture$1.generateMipmaps;
  14339. this.texture.minFilter = texture$1.minFilter;
  14340. this.texture.magFilter = texture$1.magFilter;
  14341. const geometry = new BoxGeometry( 5, 5, 5 );
  14342. const uvNode = equirectUV( positionWorldDirection );
  14343. const material = new NodeMaterial();
  14344. material.colorNode = texture( texture$1, uvNode, 0 );
  14345. material.side = BackSide;
  14346. material.blending = NoBlending;
  14347. const mesh = new Mesh( geometry, material );
  14348. const scene = new Scene();
  14349. scene.add( mesh );
  14350. // Avoid blurred poles
  14351. if ( texture$1.minFilter === LinearMipmapLinearFilter ) texture$1.minFilter = LinearFilter;
  14352. const camera = new CubeCamera( 1, 10, this );
  14353. const currentMRT = renderer.getMRT();
  14354. renderer.setMRT( null );
  14355. camera.update( renderer, scene );
  14356. renderer.setMRT( currentMRT );
  14357. texture$1.minFilter = currentMinFilter;
  14358. texture$1.currentGenerateMipmaps = currentGenerateMipmaps;
  14359. mesh.geometry.dispose();
  14360. mesh.material.dispose();
  14361. return this;
  14362. }
  14363. }
  14364. const _cache$1 = new WeakMap();
  14365. /**
  14366. * This node can be used to automatically convert environment maps in the
  14367. * equirectangular format into the cube map format.
  14368. *
  14369. * @augments TempNode
  14370. */
  14371. class CubeMapNode extends TempNode {
  14372. static get type() {
  14373. return 'CubeMapNode';
  14374. }
  14375. /**
  14376. * Constructs a new cube map node.
  14377. *
  14378. * @param {Node} envNode - The node representing the environment map.
  14379. */
  14380. constructor( envNode ) {
  14381. super( 'vec3' );
  14382. /**
  14383. * The node representing the environment map.
  14384. *
  14385. * @type {Node}
  14386. */
  14387. this.envNode = envNode;
  14388. /**
  14389. * A reference to the internal cube texture.
  14390. *
  14391. * @private
  14392. * @type {?CubeTexture}
  14393. * @default null
  14394. */
  14395. this._cubeTexture = null;
  14396. /**
  14397. * A reference to the internal cube texture node.
  14398. *
  14399. * @private
  14400. * @type {CubeTextureNode}
  14401. */
  14402. this._cubeTextureNode = cubeTexture( null );
  14403. const defaultTexture = new CubeTexture();
  14404. defaultTexture.isRenderTargetTexture = true;
  14405. /**
  14406. * A default cube texture that acts as a placeholder.
  14407. * It is used when the conversion from equirectangular to cube
  14408. * map has not finished yet for a given texture.
  14409. *
  14410. * @private
  14411. * @type {CubeTexture}
  14412. */
  14413. this._defaultTexture = defaultTexture;
  14414. /**
  14415. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  14416. * the texture once per render in its {@link CubeMapNode#updateBefore} method.
  14417. *
  14418. * @type {string}
  14419. * @default 'render'
  14420. */
  14421. this.updateBeforeType = NodeUpdateType.RENDER;
  14422. }
  14423. updateBefore( frame ) {
  14424. const { renderer, material } = frame;
  14425. const envNode = this.envNode;
  14426. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  14427. const texture = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  14428. if ( texture && texture.isTexture ) {
  14429. const mapping = texture.mapping;
  14430. if ( mapping === EquirectangularReflectionMapping || mapping === EquirectangularRefractionMapping ) {
  14431. // check for converted cubemap map
  14432. if ( _cache$1.has( texture ) ) {
  14433. const cubeMap = _cache$1.get( texture );
  14434. mapTextureMapping( cubeMap, texture.mapping );
  14435. this._cubeTexture = cubeMap;
  14436. } else {
  14437. // create cube map from equirectangular map
  14438. const image = texture.image;
  14439. if ( isEquirectangularMapReady$1( image ) ) {
  14440. const renderTarget = new CubeRenderTarget( image.height );
  14441. renderTarget.fromEquirectangularTexture( renderer, texture );
  14442. mapTextureMapping( renderTarget.texture, texture.mapping );
  14443. this._cubeTexture = renderTarget.texture;
  14444. _cache$1.set( texture, renderTarget.texture );
  14445. texture.addEventListener( 'dispose', onTextureDispose );
  14446. } else {
  14447. // default cube texture as fallback when equirectangular texture is not yet loaded
  14448. this._cubeTexture = this._defaultTexture;
  14449. }
  14450. }
  14451. //
  14452. this._cubeTextureNode.value = this._cubeTexture;
  14453. } else {
  14454. // envNode already refers to a cube map
  14455. this._cubeTextureNode = this.envNode;
  14456. }
  14457. }
  14458. }
  14459. }
  14460. setup( builder ) {
  14461. this.updateBefore( builder );
  14462. return this._cubeTextureNode;
  14463. }
  14464. }
  14465. /**
  14466. * Returns true if the given equirectangular image has been fully loaded
  14467. * and is ready for further processing.
  14468. *
  14469. * @private
  14470. * @param {Image} image - The equirectangular image to check.
  14471. * @return {boolean} Whether the image is ready or not.
  14472. */
  14473. function isEquirectangularMapReady$1( image ) {
  14474. if ( image === null || image === undefined ) return false;
  14475. return image.height > 0;
  14476. }
  14477. /**
  14478. * This function is executed when `dispose()` is called on the equirectangular
  14479. * texture. In this case, the generated cube map with its render target
  14480. * is deleted as well.
  14481. *
  14482. * @private
  14483. * @param {Object} event - The event object.
  14484. */
  14485. function onTextureDispose( event ) {
  14486. const texture = event.target;
  14487. texture.removeEventListener( 'dispose', onTextureDispose );
  14488. const renderTarget = _cache$1.get( texture );
  14489. if ( renderTarget !== undefined ) {
  14490. _cache$1.delete( texture );
  14491. renderTarget.dispose();
  14492. }
  14493. }
  14494. /**
  14495. * This function makes sure the generated cube map uses the correct
  14496. * texture mapping that corresponds to the equirectangular original.
  14497. *
  14498. * @private
  14499. * @param {Texture} texture - The cube texture.
  14500. * @param {number} mapping - The original texture mapping.
  14501. */
  14502. function mapTextureMapping( texture, mapping ) {
  14503. if ( mapping === EquirectangularReflectionMapping ) {
  14504. texture.mapping = CubeReflectionMapping;
  14505. } else if ( mapping === EquirectangularRefractionMapping ) {
  14506. texture.mapping = CubeRefractionMapping;
  14507. }
  14508. }
  14509. /**
  14510. * TSL function for creating a cube map node.
  14511. *
  14512. * @tsl
  14513. * @function
  14514. * @param {Node} envNode - The node representing the environment map.
  14515. * @returns {CubeMapNode}
  14516. */
  14517. const cubeMapNode = /*@__PURE__*/ nodeProxy( CubeMapNode ).setParameterLength( 1 );
  14518. /**
  14519. * Represents a basic model for Image-based lighting (IBL). The environment
  14520. * is defined via environment maps in the equirectangular or cube map format.
  14521. * `BasicEnvironmentNode` is intended for non-PBR materials like {@link MeshBasicNodeMaterial}
  14522. * or {@link MeshPhongNodeMaterial}.
  14523. *
  14524. * @augments LightingNode
  14525. */
  14526. class BasicEnvironmentNode extends LightingNode {
  14527. static get type() {
  14528. return 'BasicEnvironmentNode';
  14529. }
  14530. /**
  14531. * Constructs a new basic environment node.
  14532. *
  14533. * @param {Node} [envNode=null] - A node representing the environment.
  14534. */
  14535. constructor( envNode = null ) {
  14536. super();
  14537. /**
  14538. * A node representing the environment.
  14539. *
  14540. * @type {Node}
  14541. * @default null
  14542. */
  14543. this.envNode = envNode;
  14544. }
  14545. setup( builder ) {
  14546. // environment property is used in the finish() method of BasicLightingModel
  14547. builder.context.environment = cubeMapNode( this.envNode );
  14548. }
  14549. }
  14550. /**
  14551. * A specific version of {@link IrradianceNode} that is only relevant
  14552. * for {@link MeshBasicNodeMaterial}. Since the material is unlit, it
  14553. * requires a special scaling factor for the light map.
  14554. *
  14555. * @augments LightingNode
  14556. */
  14557. class BasicLightMapNode extends LightingNode {
  14558. static get type() {
  14559. return 'BasicLightMapNode';
  14560. }
  14561. /**
  14562. * Constructs a new basic light map node.
  14563. *
  14564. * @param {?Node<vec3>} [lightMapNode=null] - The light map node.
  14565. */
  14566. constructor( lightMapNode = null ) {
  14567. super();
  14568. /**
  14569. * The light map node.
  14570. *
  14571. * @type {?Node<vec3>}
  14572. */
  14573. this.lightMapNode = lightMapNode;
  14574. }
  14575. setup( builder ) {
  14576. // irradianceLightMap property is used in the indirectDiffuse() method of BasicLightingModel
  14577. const RECIPROCAL_PI = float( 1 / Math.PI );
  14578. builder.context.irradianceLightMap = this.lightMapNode.mul( RECIPROCAL_PI );
  14579. }
  14580. }
  14581. /**
  14582. * Abstract class for implementing lighting models. The module defines
  14583. * multiple methods that concrete lighting models can implement. These
  14584. * methods are executed at different points during the light evaluation
  14585. * process.
  14586. */
  14587. class LightingModel {
  14588. /**
  14589. * This method is intended for setting up lighting model and context data
  14590. * which are later used in the evaluation process.
  14591. *
  14592. * @abstract
  14593. * @param {NodeBuilder} builder - The current node builder.
  14594. */
  14595. start( builder ) {
  14596. // lights ( direct )
  14597. builder.lightsNode.setupLights( builder, builder.lightsNode.getLightNodes( builder ) );
  14598. // indirect
  14599. this.indirect( builder );
  14600. }
  14601. /**
  14602. * This method is intended for executing final tasks like final updates
  14603. * to the outgoing light.
  14604. *
  14605. * @abstract
  14606. * @param {NodeBuilder} builder - The current node builder.
  14607. */
  14608. finish( /*builder*/ ) { }
  14609. /**
  14610. * This method is intended for implementing the direct light term and
  14611. * executed during the build process of directional, point and spot light nodes.
  14612. *
  14613. * @abstract
  14614. * @param {Object} lightData - The light data.
  14615. * @param {NodeBuilder} builder - The current node builder.
  14616. */
  14617. direct( /*lightData, builder*/ ) { }
  14618. /**
  14619. * This method is intended for implementing the direct light term for
  14620. * rect area light nodes.
  14621. *
  14622. * @abstract
  14623. * @param {Object} lightData - The light data.
  14624. * @param {NodeBuilder} builder - The current node builder.
  14625. */
  14626. directRectArea( /*lightData, builder*/ ) {}
  14627. /**
  14628. * This method is intended for implementing the indirect light term.
  14629. *
  14630. * @abstract
  14631. * @param {NodeBuilder} builder - The current node builder.
  14632. */
  14633. indirect( /*builder*/ ) { }
  14634. /**
  14635. * This method is intended for implementing the ambient occlusion term.
  14636. * Unlike other methods, this method must be called manually by the lighting
  14637. * model in its indirect term.
  14638. *
  14639. * @abstract
  14640. * @param {NodeBuilder} builder - The current node builder.
  14641. */
  14642. ambientOcclusion( /*input, stack, builder*/ ) { }
  14643. }
  14644. /**
  14645. * Represents the lighting model for unlit materials. The only light contribution
  14646. * is baked indirect lighting modulated with ambient occlusion and the material's
  14647. * diffuse color. Environment mapping is supported. Used in {@link MeshBasicNodeMaterial}.
  14648. *
  14649. * @augments LightingModel
  14650. */
  14651. class BasicLightingModel extends LightingModel {
  14652. /**
  14653. * Constructs a new basic lighting model.
  14654. */
  14655. constructor() {
  14656. super();
  14657. }
  14658. /**
  14659. * Implements the baked indirect lighting with its modulation.
  14660. *
  14661. * @param {NodeBuilder} builder - The current node builder.
  14662. */
  14663. indirect( { context } ) {
  14664. const ambientOcclusion = context.ambientOcclusion;
  14665. const reflectedLight = context.reflectedLight;
  14666. const irradianceLightMap = context.irradianceLightMap;
  14667. reflectedLight.indirectDiffuse.assign( vec4( 0.0 ) );
  14668. // accumulation (baked indirect lighting only)
  14669. if ( irradianceLightMap ) {
  14670. reflectedLight.indirectDiffuse.addAssign( irradianceLightMap );
  14671. } else {
  14672. reflectedLight.indirectDiffuse.addAssign( vec4( 1.0, 1.0, 1.0, 0.0 ) );
  14673. }
  14674. // modulation
  14675. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14676. reflectedLight.indirectDiffuse.mulAssign( diffuseColor.rgb );
  14677. }
  14678. /**
  14679. * Implements the environment mapping.
  14680. *
  14681. * @param {NodeBuilder} builder - The current node builder.
  14682. */
  14683. finish( builder ) {
  14684. const { material, context } = builder;
  14685. const outgoingLight = context.outgoingLight;
  14686. const envNode = builder.context.environment;
  14687. if ( envNode ) {
  14688. switch ( material.combine ) {
  14689. case MultiplyOperation:
  14690. outgoingLight.rgb.assign( mix( outgoingLight.rgb, outgoingLight.rgb.mul( envNode.rgb ), materialSpecularStrength.mul( materialReflectivity ) ) );
  14691. break;
  14692. case MixOperation:
  14693. outgoingLight.rgb.assign( mix( outgoingLight.rgb, envNode.rgb, materialSpecularStrength.mul( materialReflectivity ) ) );
  14694. break;
  14695. case AddOperation:
  14696. outgoingLight.rgb.addAssign( envNode.rgb.mul( materialSpecularStrength.mul( materialReflectivity ) ) );
  14697. break;
  14698. default:
  14699. console.warn( 'THREE.BasicLightingModel: Unsupported .combine value:', material.combine );
  14700. break;
  14701. }
  14702. }
  14703. }
  14704. }
  14705. const _defaultValues$9 = /*@__PURE__*/ new MeshBasicMaterial();
  14706. /**
  14707. * Node material version of {@link MeshBasicMaterial}.
  14708. *
  14709. * @augments NodeMaterial
  14710. */
  14711. class MeshBasicNodeMaterial extends NodeMaterial {
  14712. static get type() {
  14713. return 'MeshBasicNodeMaterial';
  14714. }
  14715. /**
  14716. * Constructs a new mesh basic node material.
  14717. *
  14718. * @param {Object} [parameters] - The configuration parameter.
  14719. */
  14720. constructor( parameters ) {
  14721. super();
  14722. /**
  14723. * This flag can be used for type testing.
  14724. *
  14725. * @type {boolean}
  14726. * @readonly
  14727. * @default true
  14728. */
  14729. this.isMeshBasicNodeMaterial = true;
  14730. /**
  14731. * Although the basic material is by definition unlit, we set
  14732. * this property to `true` since we use a lighting model to compute
  14733. * the outgoing light of the fragment shader.
  14734. *
  14735. * @type {boolean}
  14736. * @default true
  14737. */
  14738. this.lights = true;
  14739. this.setDefaultValues( _defaultValues$9 );
  14740. this.setValues( parameters );
  14741. }
  14742. /**
  14743. * Basic materials are not affected by normal and bump maps so we
  14744. * return by default {@link normalView}.
  14745. *
  14746. * @return {Node<vec3>} The normal node.
  14747. */
  14748. setupNormal() {
  14749. return normalView; // see #28839
  14750. }
  14751. /**
  14752. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  14753. * to implement the default environment mapping.
  14754. *
  14755. * @param {NodeBuilder} builder - The current node builder.
  14756. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  14757. */
  14758. setupEnvironment( builder ) {
  14759. const envNode = super.setupEnvironment( builder );
  14760. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  14761. }
  14762. /**
  14763. * This method must be overwritten since light maps are evaluated
  14764. * with a special scaling factor for basic materials.
  14765. *
  14766. * @param {NodeBuilder} builder - The current node builder.
  14767. * @return {?BasicLightMapNode<vec3>} The light map node.
  14768. */
  14769. setupLightMap( builder ) {
  14770. let node = null;
  14771. if ( builder.material.lightMap ) {
  14772. node = new BasicLightMapNode( materialLightMap );
  14773. }
  14774. return node;
  14775. }
  14776. /**
  14777. * The material overwrites this method because `lights` is set to `true` but
  14778. * we still want to return the diffuse color as the outgoing light.
  14779. *
  14780. * @return {Node<vec3>} The outgoing light node.
  14781. */
  14782. setupOutgoingLight() {
  14783. return diffuseColor.rgb;
  14784. }
  14785. /**
  14786. * Setups the lighting model.
  14787. *
  14788. * @return {BasicLightingModel} The lighting model.
  14789. */
  14790. setupLightingModel() {
  14791. return new BasicLightingModel();
  14792. }
  14793. }
  14794. const F_Schlick = /*@__PURE__*/ Fn( ( { f0, f90, dotVH } ) => {
  14795. // Original approximation by Christophe Schlick '94
  14796. // float fresnel = pow( 1.0 - dotVH, 5.0 );
  14797. // Optimized variant (presented by Epic at SIGGRAPH '13)
  14798. // https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf
  14799. const fresnel = dotVH.mul( -5.55473 ).sub( 6.98316 ).mul( dotVH ).exp2();
  14800. return f0.mul( fresnel.oneMinus() ).add( f90.mul( fresnel ) );
  14801. } ); // validated
  14802. const BRDF_Lambert = /*@__PURE__*/ Fn( ( inputs ) => {
  14803. return inputs.diffuseColor.mul( 1 / Math.PI ); // punctual light
  14804. } ); // validated
  14805. const G_BlinnPhong_Implicit = () => float( 0.25 );
  14806. const D_BlinnPhong = /*@__PURE__*/ Fn( ( { dotNH } ) => {
  14807. return shininess.mul( float( 0.5 ) ).add( 1.0 ).mul( float( 1 / Math.PI ) ).mul( dotNH.pow( shininess ) );
  14808. } );
  14809. const BRDF_BlinnPhong = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  14810. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  14811. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  14812. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  14813. const F = F_Schlick( { f0: specularColor, f90: 1.0, dotVH } );
  14814. const G = G_BlinnPhong_Implicit();
  14815. const D = D_BlinnPhong( { dotNH } );
  14816. return F.mul( G ).mul( D );
  14817. } );
  14818. /**
  14819. * Represents the lighting model for a phong material. Used in {@link MeshPhongNodeMaterial}.
  14820. *
  14821. * @augments BasicLightingModel
  14822. */
  14823. class PhongLightingModel extends BasicLightingModel {
  14824. /**
  14825. * Constructs a new phong lighting model.
  14826. *
  14827. * @param {boolean} [specular=true] - Whether specular is supported or not.
  14828. */
  14829. constructor( specular = true ) {
  14830. super();
  14831. /**
  14832. * Whether specular is supported or not. Set this to `false` if you are
  14833. * looking for a Lambert-like material meaning a material for non-shiny
  14834. * surfaces, without specular highlights.
  14835. *
  14836. * @type {boolean}
  14837. * @default true
  14838. */
  14839. this.specular = specular;
  14840. }
  14841. /**
  14842. * Implements the direct lighting. The specular portion is optional an can be controlled
  14843. * with the {@link PhongLightingModel#specular} flag.
  14844. *
  14845. * @param {Object} lightData - The light data.
  14846. */
  14847. direct( { lightDirection, lightColor, reflectedLight } ) {
  14848. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  14849. const irradiance = dotNL.mul( lightColor );
  14850. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  14851. if ( this.specular === true ) {
  14852. reflectedLight.directSpecular.addAssign( irradiance.mul( BRDF_BlinnPhong( { lightDirection } ) ).mul( materialSpecularStrength ) );
  14853. }
  14854. }
  14855. /**
  14856. * Implements the indirect lighting.
  14857. *
  14858. * @param {NodeBuilder} builder - The current node builder.
  14859. */
  14860. indirect( builder ) {
  14861. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  14862. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  14863. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  14864. }
  14865. }
  14866. const _defaultValues$8 = /*@__PURE__*/ new MeshLambertMaterial();
  14867. /**
  14868. * Node material version of {@link MeshLambertMaterial}.
  14869. *
  14870. * @augments NodeMaterial
  14871. */
  14872. class MeshLambertNodeMaterial extends NodeMaterial {
  14873. static get type() {
  14874. return 'MeshLambertNodeMaterial';
  14875. }
  14876. /**
  14877. * Constructs a new mesh lambert node material.
  14878. *
  14879. * @param {Object} [parameters] - The configuration parameter.
  14880. */
  14881. constructor( parameters ) {
  14882. super();
  14883. /**
  14884. * This flag can be used for type testing.
  14885. *
  14886. * @type {boolean}
  14887. * @readonly
  14888. * @default true
  14889. */
  14890. this.isMeshLambertNodeMaterial = true;
  14891. /**
  14892. * Set to `true` because lambert materials react on lights.
  14893. *
  14894. * @type {boolean}
  14895. * @default true
  14896. */
  14897. this.lights = true;
  14898. this.setDefaultValues( _defaultValues$8 );
  14899. this.setValues( parameters );
  14900. }
  14901. /**
  14902. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  14903. * to implement the default environment mapping.
  14904. *
  14905. * @param {NodeBuilder} builder - The current node builder.
  14906. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  14907. */
  14908. setupEnvironment( builder ) {
  14909. const envNode = super.setupEnvironment( builder );
  14910. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  14911. }
  14912. /**
  14913. * Setups the lighting model.
  14914. *
  14915. * @return {PhongLightingModel} The lighting model.
  14916. */
  14917. setupLightingModel( /*builder*/ ) {
  14918. return new PhongLightingModel( false ); // ( specular ) -> force lambert
  14919. }
  14920. }
  14921. const _defaultValues$7 = /*@__PURE__*/ new MeshPhongMaterial();
  14922. /**
  14923. * Node material version of {@link MeshPhongMaterial}.
  14924. *
  14925. * @augments NodeMaterial
  14926. */
  14927. class MeshPhongNodeMaterial extends NodeMaterial {
  14928. static get type() {
  14929. return 'MeshPhongNodeMaterial';
  14930. }
  14931. /**
  14932. * Constructs a new mesh lambert node material.
  14933. *
  14934. * @param {Object} [parameters] - The configuration parameter.
  14935. */
  14936. constructor( parameters ) {
  14937. super();
  14938. /**
  14939. * This flag can be used for type testing.
  14940. *
  14941. * @type {boolean}
  14942. * @readonly
  14943. * @default true
  14944. */
  14945. this.isMeshPhongNodeMaterial = true;
  14946. /**
  14947. * Set to `true` because phong materials react on lights.
  14948. *
  14949. * @type {boolean}
  14950. * @default true
  14951. */
  14952. this.lights = true;
  14953. /**
  14954. * The shininess of phong materials is by default inferred from the `shininess`
  14955. * property. This node property allows to overwrite the default
  14956. * and define the shininess with a node instead.
  14957. *
  14958. * If you don't want to overwrite the shininess but modify the existing
  14959. * value instead, use {@link materialShininess}.
  14960. *
  14961. * @type {?Node<float>}
  14962. * @default null
  14963. */
  14964. this.shininessNode = null;
  14965. /**
  14966. * The specular color of phong materials is by default inferred from the
  14967. * `specular` property. This node property allows to overwrite the default
  14968. * and define the specular color with a node instead.
  14969. *
  14970. * If you don't want to overwrite the specular color but modify the existing
  14971. * value instead, use {@link materialSpecular}.
  14972. *
  14973. * @type {?Node<vec3>}
  14974. * @default null
  14975. */
  14976. this.specularNode = null;
  14977. this.setDefaultValues( _defaultValues$7 );
  14978. this.setValues( parameters );
  14979. }
  14980. /**
  14981. * Overwritten since this type of material uses {@link BasicEnvironmentNode}
  14982. * to implement the default environment mapping.
  14983. *
  14984. * @param {NodeBuilder} builder - The current node builder.
  14985. * @return {?BasicEnvironmentNode<vec3>} The environment node.
  14986. */
  14987. setupEnvironment( builder ) {
  14988. const envNode = super.setupEnvironment( builder );
  14989. return envNode ? new BasicEnvironmentNode( envNode ) : null;
  14990. }
  14991. /**
  14992. * Setups the lighting model.
  14993. *
  14994. * @return {PhongLightingModel} The lighting model.
  14995. */
  14996. setupLightingModel( /*builder*/ ) {
  14997. return new PhongLightingModel();
  14998. }
  14999. /**
  15000. * Setups the phong specific node variables.
  15001. *
  15002. * @param {NodeBuilder} builder - The current node builder.
  15003. */
  15004. setupVariants( /*builder*/ ) {
  15005. // SHININESS
  15006. const shininessNode = ( this.shininessNode ? float( this.shininessNode ) : materialShininess ).max( 1e-4 ); // to prevent pow( 0.0, 0.0 )
  15007. shininess.assign( shininessNode );
  15008. // SPECULAR COLOR
  15009. const specularNode = this.specularNode || materialSpecular;
  15010. specularColor.assign( specularNode );
  15011. }
  15012. copy( source ) {
  15013. this.shininessNode = source.shininessNode;
  15014. this.specularNode = source.specularNode;
  15015. return super.copy( source );
  15016. }
  15017. }
  15018. const getGeometryRoughness = /*@__PURE__*/ Fn( ( builder ) => {
  15019. if ( builder.geometry.hasAttribute( 'normal' ) === false ) {
  15020. return float( 0 );
  15021. }
  15022. const dxy = normalView.dFdx().abs().max( normalView.dFdy().abs() );
  15023. const geometryRoughness = dxy.x.max( dxy.y ).max( dxy.z );
  15024. return geometryRoughness;
  15025. } );
  15026. const getRoughness = /*@__PURE__*/ Fn( ( inputs ) => {
  15027. const { roughness } = inputs;
  15028. const geometryRoughness = getGeometryRoughness();
  15029. let roughnessFactor = roughness.max( 0.0525 ); // 0.0525 corresponds to the base mip of a 256 cubemap.
  15030. roughnessFactor = roughnessFactor.add( geometryRoughness );
  15031. roughnessFactor = roughnessFactor.min( 1.0 );
  15032. return roughnessFactor;
  15033. } );
  15034. // Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2
  15035. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  15036. const V_GGX_SmithCorrelated = /*@__PURE__*/ Fn( ( { alpha, dotNL, dotNV } ) => {
  15037. const a2 = alpha.pow2();
  15038. const gv = dotNL.mul( a2.add( a2.oneMinus().mul( dotNV.pow2() ) ).sqrt() );
  15039. const gl = dotNV.mul( a2.add( a2.oneMinus().mul( dotNL.pow2() ) ).sqrt() );
  15040. return div( 0.5, gv.add( gl ).max( EPSILON ) );
  15041. } ).setLayout( {
  15042. name: 'V_GGX_SmithCorrelated',
  15043. type: 'float',
  15044. inputs: [
  15045. { name: 'alpha', type: 'float' },
  15046. { name: 'dotNL', type: 'float' },
  15047. { name: 'dotNV', type: 'float' }
  15048. ]
  15049. } ); // validated
  15050. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15051. const V_GGX_SmithCorrelated_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } ) => {
  15052. const gv = dotNL.mul( vec3( alphaT.mul( dotTV ), alphaB.mul( dotBV ), dotNV ).length() );
  15053. const gl = dotNV.mul( vec3( alphaT.mul( dotTL ), alphaB.mul( dotBL ), dotNL ).length() );
  15054. const v = div( 0.5, gv.add( gl ) );
  15055. return v.saturate();
  15056. } ).setLayout( {
  15057. name: 'V_GGX_SmithCorrelated_Anisotropic',
  15058. type: 'float',
  15059. inputs: [
  15060. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15061. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15062. { name: 'dotTV', type: 'float', qualifier: 'in' },
  15063. { name: 'dotBV', type: 'float', qualifier: 'in' },
  15064. { name: 'dotTL', type: 'float', qualifier: 'in' },
  15065. { name: 'dotBL', type: 'float', qualifier: 'in' },
  15066. { name: 'dotNV', type: 'float', qualifier: 'in' },
  15067. { name: 'dotNL', type: 'float', qualifier: 'in' }
  15068. ]
  15069. } );
  15070. // Microfacet Models for Refraction through Rough Surfaces - equation (33)
  15071. // http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html
  15072. // alpha is "roughness squared" in Disney’s reparameterization
  15073. const D_GGX = /*@__PURE__*/ Fn( ( { alpha, dotNH } ) => {
  15074. const a2 = alpha.pow2();
  15075. const denom = dotNH.pow2().mul( a2.oneMinus() ).oneMinus(); // avoid alpha = 0 with dotNH = 1
  15076. return a2.div( denom.pow2() ).mul( 1 / Math.PI );
  15077. } ).setLayout( {
  15078. name: 'D_GGX',
  15079. type: 'float',
  15080. inputs: [
  15081. { name: 'alpha', type: 'float' },
  15082. { name: 'dotNH', type: 'float' }
  15083. ]
  15084. } ); // validated
  15085. const RECIPROCAL_PI = /*@__PURE__*/ float( 1 / Math.PI );
  15086. // https://google.github.io/filament/Filament.md.html#materialsystem/anisotropicmodel/anisotropicspecularbrdf
  15087. const D_GGX_Anisotropic = /*@__PURE__*/ Fn( ( { alphaT, alphaB, dotNH, dotTH, dotBH } ) => {
  15088. const a2 = alphaT.mul( alphaB );
  15089. const v = vec3( alphaB.mul( dotTH ), alphaT.mul( dotBH ), a2.mul( dotNH ) );
  15090. const v2 = v.dot( v );
  15091. const w2 = a2.div( v2 );
  15092. return RECIPROCAL_PI.mul( a2.mul( w2.pow2() ) );
  15093. } ).setLayout( {
  15094. name: 'D_GGX_Anisotropic',
  15095. type: 'float',
  15096. inputs: [
  15097. { name: 'alphaT', type: 'float', qualifier: 'in' },
  15098. { name: 'alphaB', type: 'float', qualifier: 'in' },
  15099. { name: 'dotNH', type: 'float', qualifier: 'in' },
  15100. { name: 'dotTH', type: 'float', qualifier: 'in' },
  15101. { name: 'dotBH', type: 'float', qualifier: 'in' }
  15102. ]
  15103. } );
  15104. // GGX Distribution, Schlick Fresnel, GGX_SmithCorrelated Visibility
  15105. const BRDF_GGX = /*@__PURE__*/ Fn( ( inputs ) => {
  15106. const { lightDirection, f0, f90, roughness, f, USE_IRIDESCENCE, USE_ANISOTROPY } = inputs;
  15107. const normalView = inputs.normalView || transformedNormalView;
  15108. const alpha = roughness.pow2(); // UE4's roughness
  15109. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15110. const dotNL = normalView.dot( lightDirection ).clamp();
  15111. const dotNV = normalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15112. const dotNH = normalView.dot( halfDir ).clamp();
  15113. const dotVH = positionViewDirection.dot( halfDir ).clamp();
  15114. let F = F_Schlick( { f0, f90, dotVH } );
  15115. let V, D;
  15116. if ( defined( USE_IRIDESCENCE ) ) {
  15117. F = iridescence.mix( F, f );
  15118. }
  15119. if ( defined( USE_ANISOTROPY ) ) {
  15120. const dotTL = anisotropyT.dot( lightDirection );
  15121. const dotTV = anisotropyT.dot( positionViewDirection );
  15122. const dotTH = anisotropyT.dot( halfDir );
  15123. const dotBL = anisotropyB.dot( lightDirection );
  15124. const dotBV = anisotropyB.dot( positionViewDirection );
  15125. const dotBH = anisotropyB.dot( halfDir );
  15126. V = V_GGX_SmithCorrelated_Anisotropic( { alphaT, alphaB: alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL } );
  15127. D = D_GGX_Anisotropic( { alphaT, alphaB: alpha, dotNH, dotTH, dotBH } );
  15128. } else {
  15129. V = V_GGX_SmithCorrelated( { alpha, dotNL, dotNV } );
  15130. D = D_GGX( { alpha, dotNH } );
  15131. }
  15132. return F.mul( V ).mul( D );
  15133. } ); // validated
  15134. // Analytical approximation of the DFG LUT, one half of the
  15135. // split-sum approximation used in indirect specular lighting.
  15136. // via 'environmentBRDF' from "Physically Based Shading on Mobile"
  15137. // https://www.unrealengine.com/blog/physically-based-shading-on-mobile
  15138. const DFGApprox = /*@__PURE__*/ Fn( ( { roughness, dotNV } ) => {
  15139. const c0 = vec4( -1, -0.0275, -0.572, 0.022 );
  15140. const c1 = vec4( 1, 0.0425, 1.04, -0.04 );
  15141. const r = roughness.mul( c0 ).add( c1 );
  15142. const a004 = r.x.mul( r.x ).min( dotNV.mul( -9.28 ).exp2() ).mul( r.x ).add( r.y );
  15143. const fab = vec2( -1.04, 1.04 ).mul( a004 ).add( r.zw );
  15144. return fab;
  15145. } ).setLayout( {
  15146. name: 'DFGApprox',
  15147. type: 'vec2',
  15148. inputs: [
  15149. { name: 'roughness', type: 'float' },
  15150. { name: 'dotNV', type: 'vec3' }
  15151. ]
  15152. } );
  15153. const EnvironmentBRDF = /*@__PURE__*/ Fn( ( inputs ) => {
  15154. const { dotNV, specularColor, specularF90, roughness } = inputs;
  15155. const fab = DFGApprox( { dotNV, roughness } );
  15156. return specularColor.mul( fab.x ).add( specularF90.mul( fab.y ) );
  15157. } );
  15158. const Schlick_to_F0 = /*@__PURE__*/ Fn( ( { f, f90, dotVH } ) => {
  15159. const x = dotVH.oneMinus().saturate();
  15160. const x2 = x.mul( x );
  15161. const x5 = x.mul( x2, x2 ).clamp( 0, .9999 );
  15162. return f.sub( vec3( f90 ).mul( x5 ) ).div( x5.oneMinus() );
  15163. } ).setLayout( {
  15164. name: 'Schlick_to_F0',
  15165. type: 'vec3',
  15166. inputs: [
  15167. { name: 'f', type: 'vec3' },
  15168. { name: 'f90', type: 'float' },
  15169. { name: 'dotVH', type: 'float' }
  15170. ]
  15171. } );
  15172. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  15173. const D_Charlie = /*@__PURE__*/ Fn( ( { roughness, dotNH } ) => {
  15174. const alpha = roughness.pow2();
  15175. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF"
  15176. const invAlpha = float( 1.0 ).div( alpha );
  15177. const cos2h = dotNH.pow2();
  15178. const sin2h = cos2h.oneMinus().max( 0.0078125 ); // 2^(-14/2), so sin2h^2 > 0 in fp16
  15179. return float( 2.0 ).add( invAlpha ).mul( sin2h.pow( invAlpha.mul( 0.5 ) ) ).div( 2.0 * Math.PI );
  15180. } ).setLayout( {
  15181. name: 'D_Charlie',
  15182. type: 'float',
  15183. inputs: [
  15184. { name: 'roughness', type: 'float' },
  15185. { name: 'dotNH', type: 'float' }
  15186. ]
  15187. } );
  15188. // https://github.com/google/filament/blob/master/shaders/src/brdf.fs
  15189. const V_Neubelt = /*@__PURE__*/ Fn( ( { dotNV, dotNL } ) => {
  15190. // Neubelt and Pettineo 2013, "Crafting a Next-gen Material Pipeline for The Order: 1886"
  15191. return float( 1.0 ).div( float( 4.0 ).mul( dotNL.add( dotNV ).sub( dotNL.mul( dotNV ) ) ) );
  15192. } ).setLayout( {
  15193. name: 'V_Neubelt',
  15194. type: 'float',
  15195. inputs: [
  15196. { name: 'dotNV', type: 'float' },
  15197. { name: 'dotNL', type: 'float' }
  15198. ]
  15199. } );
  15200. const BRDF_Sheen = /*@__PURE__*/ Fn( ( { lightDirection } ) => {
  15201. const halfDir = lightDirection.add( positionViewDirection ).normalize();
  15202. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  15203. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp();
  15204. const dotNH = transformedNormalView.dot( halfDir ).clamp();
  15205. const D = D_Charlie( { roughness: sheenRoughness, dotNH } );
  15206. const V = V_Neubelt( { dotNV, dotNL } );
  15207. return sheen.mul( D ).mul( V );
  15208. } );
  15209. // Rect Area Light
  15210. // Real-Time Polygonal-Light Shading with Linearly Transformed Cosines
  15211. // by Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt
  15212. // code: https://github.com/selfshadow/ltc_code/
  15213. const LTC_Uv = /*@__PURE__*/ Fn( ( { N, V, roughness } ) => {
  15214. const LUT_SIZE = 64.0;
  15215. const LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;
  15216. const LUT_BIAS = 0.5 / LUT_SIZE;
  15217. const dotNV = N.dot( V ).saturate();
  15218. // texture parameterized by sqrt( GGX alpha ) and sqrt( 1 - cos( theta ) )
  15219. const uv = vec2( roughness, dotNV.oneMinus().sqrt() );
  15220. uv.assign( uv.mul( LUT_SCALE ).add( LUT_BIAS ) );
  15221. return uv;
  15222. } ).setLayout( {
  15223. name: 'LTC_Uv',
  15224. type: 'vec2',
  15225. inputs: [
  15226. { name: 'N', type: 'vec3' },
  15227. { name: 'V', type: 'vec3' },
  15228. { name: 'roughness', type: 'float' }
  15229. ]
  15230. } );
  15231. const LTC_ClippedSphereFormFactor = /*@__PURE__*/ Fn( ( { f } ) => {
  15232. // Real-Time Area Lighting: a Journey from Research to Production (p.102)
  15233. // An approximation of the form factor of a horizon-clipped rectangle.
  15234. const l = f.length();
  15235. return max$1( l.mul( l ).add( f.z ).div( l.add( 1.0 ) ), 0 );
  15236. } ).setLayout( {
  15237. name: 'LTC_ClippedSphereFormFactor',
  15238. type: 'float',
  15239. inputs: [
  15240. { name: 'f', type: 'vec3' }
  15241. ]
  15242. } );
  15243. const LTC_EdgeVectorFormFactor = /*@__PURE__*/ Fn( ( { v1, v2 } ) => {
  15244. const x = v1.dot( v2 );
  15245. const y = x.abs().toVar();
  15246. // rational polynomial approximation to theta / sin( theta ) / 2PI
  15247. const a = y.mul( 0.0145206 ).add( 0.4965155 ).mul( y ).add( 0.8543985 ).toVar();
  15248. const b = y.add( 4.1616724 ).mul( y ).add( 3.4175940 ).toVar();
  15249. const v = a.div( b );
  15250. const theta_sintheta = x.greaterThan( 0.0 ).select( v, max$1( x.mul( x ).oneMinus(), 1e-7 ).inverseSqrt().mul( 0.5 ).sub( v ) );
  15251. return v1.cross( v2 ).mul( theta_sintheta );
  15252. } ).setLayout( {
  15253. name: 'LTC_EdgeVectorFormFactor',
  15254. type: 'vec3',
  15255. inputs: [
  15256. { name: 'v1', type: 'vec3' },
  15257. { name: 'v2', type: 'vec3' }
  15258. ]
  15259. } );
  15260. const LTC_Evaluate = /*@__PURE__*/ Fn( ( { N, V, P, mInv, p0, p1, p2, p3 } ) => {
  15261. // bail if point is on back side of plane of light
  15262. // assumes ccw winding order of light vertices
  15263. const v1 = p1.sub( p0 ).toVar();
  15264. const v2 = p3.sub( p0 ).toVar();
  15265. const lightNormal = v1.cross( v2 );
  15266. const result = vec3().toVar();
  15267. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15268. // construct orthonormal basis around N
  15269. const T1 = V.sub( N.mul( V.dot( N ) ) ).normalize();
  15270. const T2 = N.cross( T1 ).negate(); // negated from paper; possibly due to a different handedness of world coordinate system
  15271. // compute transform
  15272. const mat = mInv.mul( mat3( T1, T2, N ).transpose() ).toVar();
  15273. // transform rect
  15274. // & project rect onto sphere
  15275. const coords0 = mat.mul( p0.sub( P ) ).normalize().toVar();
  15276. const coords1 = mat.mul( p1.sub( P ) ).normalize().toVar();
  15277. const coords2 = mat.mul( p2.sub( P ) ).normalize().toVar();
  15278. const coords3 = mat.mul( p3.sub( P ) ).normalize().toVar();
  15279. // calculate vector form factor
  15280. const vectorFormFactor = vec3( 0 ).toVar();
  15281. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15282. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15283. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15284. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15285. // adjust for horizon clipping
  15286. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor } ) ) );
  15287. } );
  15288. return result;
  15289. } ).setLayout( {
  15290. name: 'LTC_Evaluate',
  15291. type: 'vec3',
  15292. inputs: [
  15293. { name: 'N', type: 'vec3' },
  15294. { name: 'V', type: 'vec3' },
  15295. { name: 'P', type: 'vec3' },
  15296. { name: 'mInv', type: 'mat3' },
  15297. { name: 'p0', type: 'vec3' },
  15298. { name: 'p1', type: 'vec3' },
  15299. { name: 'p2', type: 'vec3' },
  15300. { name: 'p3', type: 'vec3' }
  15301. ]
  15302. } );
  15303. const LTC_Evaluate_Volume = /*@__PURE__*/ Fn( ( { P, p0, p1, p2, p3 } ) => {
  15304. // bail if point is on back side of plane of light
  15305. // assumes ccw winding order of light vertices
  15306. const v1 = p1.sub( p0 ).toVar();
  15307. const v2 = p3.sub( p0 ).toVar();
  15308. const lightNormal = v1.cross( v2 );
  15309. const result = vec3().toVar();
  15310. If( lightNormal.dot( P.sub( p0 ) ).greaterThanEqual( 0.0 ), () => {
  15311. // transform rect
  15312. // & project rect onto sphere
  15313. const coords0 = p0.sub( P ).normalize().toVar();
  15314. const coords1 = p1.sub( P ).normalize().toVar();
  15315. const coords2 = p2.sub( P ).normalize().toVar();
  15316. const coords3 = p3.sub( P ).normalize().toVar();
  15317. // calculate vector form factor
  15318. const vectorFormFactor = vec3( 0 ).toVar();
  15319. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords0, v2: coords1 } ) );
  15320. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords1, v2: coords2 } ) );
  15321. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords2, v2: coords3 } ) );
  15322. vectorFormFactor.addAssign( LTC_EdgeVectorFormFactor( { v1: coords3, v2: coords0 } ) );
  15323. // adjust for horizon clipping
  15324. result.assign( vec3( LTC_ClippedSphereFormFactor( { f: vectorFormFactor.abs() } ) ) );
  15325. } );
  15326. return result;
  15327. } ).setLayout( {
  15328. name: 'LTC_Evaluate',
  15329. type: 'vec3',
  15330. inputs: [
  15331. { name: 'P', type: 'vec3' },
  15332. { name: 'p0', type: 'vec3' },
  15333. { name: 'p1', type: 'vec3' },
  15334. { name: 'p2', type: 'vec3' },
  15335. { name: 'p3', type: 'vec3' }
  15336. ]
  15337. } );
  15338. // Mipped Bicubic Texture Filtering by N8
  15339. // https://www.shadertoy.com/view/Dl2SDW
  15340. const bC = 1.0 / 6.0;
  15341. const w0 = ( a ) => mul( bC, mul( a, mul( a, a.negate().add( 3.0 ) ).sub( 3.0 ) ).add( 1.0 ) );
  15342. const w1 = ( a ) => mul( bC, mul( a, mul( a, mul( 3.0, a ).sub( 6.0 ) ) ).add( 4.0 ) );
  15343. const w2 = ( a ) => mul( bC, mul( a, mul( a, mul( -3, a ).add( 3.0 ) ).add( 3.0 ) ).add( 1.0 ) );
  15344. const w3 = ( a ) => mul( bC, pow( a, 3 ) );
  15345. const g0 = ( a ) => w0( a ).add( w1( a ) );
  15346. const g1 = ( a ) => w2( a ).add( w3( a ) );
  15347. // h0 and h1 are the two offset functions
  15348. const h0 = ( a ) => add( -1, w1( a ).div( w0( a ).add( w1( a ) ) ) );
  15349. const h1 = ( a ) => add( 1.0, w3( a ).div( w2( a ).add( w3( a ) ) ) );
  15350. const bicubic = ( textureNode, texelSize, lod ) => {
  15351. const uv = textureNode.uvNode;
  15352. const uvScaled = mul( uv, texelSize.zw ).add( 0.5 );
  15353. const iuv = floor( uvScaled );
  15354. const fuv = fract( uvScaled );
  15355. const g0x = g0( fuv.x );
  15356. const g1x = g1( fuv.x );
  15357. const h0x = h0( fuv.x );
  15358. const h1x = h1( fuv.x );
  15359. const h0y = h0( fuv.y );
  15360. const h1y = h1( fuv.y );
  15361. const p0 = vec2( iuv.x.add( h0x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  15362. const p1 = vec2( iuv.x.add( h1x ), iuv.y.add( h0y ) ).sub( 0.5 ).mul( texelSize.xy );
  15363. const p2 = vec2( iuv.x.add( h0x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  15364. const p3 = vec2( iuv.x.add( h1x ), iuv.y.add( h1y ) ).sub( 0.5 ).mul( texelSize.xy );
  15365. const a = g0( fuv.y ).mul( add( g0x.mul( textureNode.sample( p0 ).level( lod ) ), g1x.mul( textureNode.sample( p1 ).level( lod ) ) ) );
  15366. const b = g1( fuv.y ).mul( add( g0x.mul( textureNode.sample( p2 ).level( lod ) ), g1x.mul( textureNode.sample( p3 ).level( lod ) ) ) );
  15367. return a.add( b );
  15368. };
  15369. /**
  15370. * Applies mipped bicubic texture filtering to the given texture node.
  15371. *
  15372. * @tsl
  15373. * @function
  15374. * @param {TextureNode} textureNode - The texture node that should be filtered.
  15375. * @param {Node<float>} [lodNode=float(3)] - Defines the LOD to sample from.
  15376. * @return {Node} The filtered texture sample.
  15377. */
  15378. const textureBicubic = /*@__PURE__*/ Fn( ( [ textureNode, lodNode = float( 3 ) ] ) => {
  15379. const fLodSize = vec2( textureNode.size( int( lodNode ) ) );
  15380. const cLodSize = vec2( textureNode.size( int( lodNode.add( 1.0 ) ) ) );
  15381. const fLodSizeInv = div( 1.0, fLodSize );
  15382. const cLodSizeInv = div( 1.0, cLodSize );
  15383. const fSample = bicubic( textureNode, vec4( fLodSizeInv, fLodSize ), floor( lodNode ) );
  15384. const cSample = bicubic( textureNode, vec4( cLodSizeInv, cLodSize ), ceil( lodNode ) );
  15385. return fract( lodNode ).mix( fSample, cSample );
  15386. } );
  15387. //
  15388. // Transmission
  15389. //
  15390. const getVolumeTransmissionRay = /*@__PURE__*/ Fn( ( [ n, v, thickness, ior, modelMatrix ] ) => {
  15391. // Direction of refracted light.
  15392. const refractionVector = vec3( refract( v.negate(), normalize( n ), div( 1.0, ior ) ) );
  15393. // Compute rotation-independent scaling of the model matrix.
  15394. const modelScale = vec3(
  15395. length( modelMatrix[ 0 ].xyz ),
  15396. length( modelMatrix[ 1 ].xyz ),
  15397. length( modelMatrix[ 2 ].xyz )
  15398. );
  15399. // The thickness is specified in local space.
  15400. return normalize( refractionVector ).mul( thickness.mul( modelScale ) );
  15401. } ).setLayout( {
  15402. name: 'getVolumeTransmissionRay',
  15403. type: 'vec3',
  15404. inputs: [
  15405. { name: 'n', type: 'vec3' },
  15406. { name: 'v', type: 'vec3' },
  15407. { name: 'thickness', type: 'float' },
  15408. { name: 'ior', type: 'float' },
  15409. { name: 'modelMatrix', type: 'mat4' }
  15410. ]
  15411. } );
  15412. const applyIorToRoughness = /*@__PURE__*/ Fn( ( [ roughness, ior ] ) => {
  15413. // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and
  15414. // an IOR of 1.5 results in the default amount of microfacet refraction.
  15415. return roughness.mul( clamp( ior.mul( 2.0 ).sub( 2.0 ), 0.0, 1.0 ) );
  15416. } ).setLayout( {
  15417. name: 'applyIorToRoughness',
  15418. type: 'float',
  15419. inputs: [
  15420. { name: 'roughness', type: 'float' },
  15421. { name: 'ior', type: 'float' }
  15422. ]
  15423. } );
  15424. const viewportBackSideTexture = /*@__PURE__*/ viewportMipTexture();
  15425. const viewportFrontSideTexture = /*@__PURE__*/ viewportMipTexture();
  15426. const getTransmissionSample = /*@__PURE__*/ Fn( ( [ fragCoord, roughness, ior ], { material } ) => {
  15427. const vTexture = material.side === BackSide ? viewportBackSideTexture : viewportFrontSideTexture;
  15428. const transmissionSample = vTexture.sample( fragCoord );
  15429. //const transmissionSample = viewportMipTexture( fragCoord );
  15430. const lod = log2( screenSize.x ).mul( applyIorToRoughness( roughness, ior ) );
  15431. return textureBicubic( transmissionSample, lod );
  15432. } );
  15433. const volumeAttenuation = /*@__PURE__*/ Fn( ( [ transmissionDistance, attenuationColor, attenuationDistance ] ) => {
  15434. If( attenuationDistance.notEqual( 0 ), () => {
  15435. // Compute light attenuation using Beer's law.
  15436. const attenuationCoefficient = log( attenuationColor ).negate().div( attenuationDistance );
  15437. const transmittance = exp( attenuationCoefficient.negate().mul( transmissionDistance ) );
  15438. return transmittance;
  15439. } );
  15440. // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all.
  15441. return vec3( 1.0 );
  15442. } ).setLayout( {
  15443. name: 'volumeAttenuation',
  15444. type: 'vec3',
  15445. inputs: [
  15446. { name: 'transmissionDistance', type: 'float' },
  15447. { name: 'attenuationColor', type: 'vec3' },
  15448. { name: 'attenuationDistance', type: 'float' }
  15449. ]
  15450. } );
  15451. const getIBLVolumeRefraction = /*@__PURE__*/ Fn( ( [ n, v, roughness, diffuseColor, specularColor, specularF90, position, modelMatrix, viewMatrix, projMatrix, ior, thickness, attenuationColor, attenuationDistance, dispersion ] ) => {
  15452. let transmittedLight, transmittance;
  15453. if ( dispersion ) {
  15454. transmittedLight = vec4().toVar();
  15455. transmittance = vec3().toVar();
  15456. const halfSpread = ior.sub( 1.0 ).mul( dispersion.mul( 0.025 ) );
  15457. const iors = vec3( ior.sub( halfSpread ), ior, ior.add( halfSpread ) );
  15458. Loop( { start: 0, end: 3 }, ( { i } ) => {
  15459. const ior = iors.element( i );
  15460. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  15461. const refractedRayExit = position.add( transmissionRay );
  15462. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  15463. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  15464. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  15465. refractionCoords.addAssign( 1.0 );
  15466. refractionCoords.divAssign( 2.0 );
  15467. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  15468. // Sample framebuffer to get pixel the refracted ray hits.
  15469. const transmissionSample = getTransmissionSample( refractionCoords, roughness, ior );
  15470. transmittedLight.element( i ).assign( transmissionSample.element( i ) );
  15471. transmittedLight.a.addAssign( transmissionSample.a );
  15472. transmittance.element( i ).assign( diffuseColor.element( i ).mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ).element( i ) ) );
  15473. } );
  15474. transmittedLight.a.divAssign( 3.0 );
  15475. } else {
  15476. const transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix );
  15477. const refractedRayExit = position.add( transmissionRay );
  15478. // Project refracted vector on the framebuffer, while mapping to normalized device coordinates.
  15479. const ndcPos = projMatrix.mul( viewMatrix.mul( vec4( refractedRayExit, 1.0 ) ) );
  15480. const refractionCoords = vec2( ndcPos.xy.div( ndcPos.w ) ).toVar();
  15481. refractionCoords.addAssign( 1.0 );
  15482. refractionCoords.divAssign( 2.0 );
  15483. refractionCoords.assign( vec2( refractionCoords.x, refractionCoords.y.oneMinus() ) ); // webgpu
  15484. // Sample framebuffer to get pixel the refracted ray hits.
  15485. transmittedLight = getTransmissionSample( refractionCoords, roughness, ior );
  15486. transmittance = diffuseColor.mul( volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ) );
  15487. }
  15488. const attenuatedColor = transmittance.rgb.mul( transmittedLight.rgb );
  15489. const dotNV = n.dot( v ).clamp();
  15490. // Get the specular component.
  15491. const F = vec3( EnvironmentBRDF( { // n, v, specularColor, specularF90, roughness
  15492. dotNV,
  15493. specularColor,
  15494. specularF90,
  15495. roughness
  15496. } ) );
  15497. // As less light is transmitted, the opacity should be increased. This simple approximation does a decent job
  15498. // of modulating a CSS background, and has no effect when the buffer is opaque, due to a solid object or clear color.
  15499. const transmittanceFactor = transmittance.r.add( transmittance.g, transmittance.b ).div( 3.0 );
  15500. return vec4( F.oneMinus().mul( attenuatedColor ), transmittedLight.a.oneMinus().mul( transmittanceFactor ).oneMinus() );
  15501. } );
  15502. //
  15503. // Iridescence
  15504. //
  15505. // XYZ to linear-sRGB color space
  15506. const XYZ_TO_REC709 = /*@__PURE__*/ mat3(
  15507. 3.2404542, -0.969266, 0.0556434,
  15508. -1.5371385, 1.8760108, -0.2040259,
  15509. -0.4985314, 0.0415560, 1.0572252
  15510. );
  15511. // Assume air interface for top
  15512. // Note: We don't handle the case fresnel0 == 1
  15513. const Fresnel0ToIor = ( fresnel0 ) => {
  15514. const sqrtF0 = fresnel0.sqrt();
  15515. return vec3( 1.0 ).add( sqrtF0 ).div( vec3( 1.0 ).sub( sqrtF0 ) );
  15516. };
  15517. // ior is a value between 1.0 and 3.0. 1.0 is air interface
  15518. const IorToFresnel0 = ( transmittedIor, incidentIor ) => {
  15519. return transmittedIor.sub( incidentIor ).div( transmittedIor.add( incidentIor ) ).pow2();
  15520. };
  15521. // Fresnel equations for dielectric/dielectric interfaces.
  15522. // Ref: https://belcour.github.io/blog/research/2017/05/01/brdf-thin-film.html
  15523. // Evaluation XYZ sensitivity curves in Fourier space
  15524. const evalSensitivity = ( OPD, shift ) => {
  15525. const phase = OPD.mul( 2.0 * Math.PI * 1.0e-9 );
  15526. const val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 );
  15527. const pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 );
  15528. const VAR = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 );
  15529. 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() );
  15530. 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() );
  15531. xyz = vec3( xyz.x.add( x ), xyz.y, xyz.z ).div( 1.0685e-7 );
  15532. const rgb = XYZ_TO_REC709.mul( xyz );
  15533. return rgb;
  15534. };
  15535. const evalIridescence = /*@__PURE__*/ Fn( ( { outsideIOR, eta2, cosTheta1, thinFilmThickness, baseF0 } ) => {
  15536. // Force iridescenceIOR -> outsideIOR when thinFilmThickness -> 0.0
  15537. const iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) );
  15538. // Evaluate the cosTheta on the base layer (Snell law)
  15539. const sinTheta2Sq = outsideIOR.div( iridescenceIOR ).pow2().mul( cosTheta1.pow2().oneMinus() );
  15540. // Handle TIR:
  15541. const cosTheta2Sq = sinTheta2Sq.oneMinus();
  15542. If( cosTheta2Sq.lessThan( 0 ), () => {
  15543. return vec3( 1.0 );
  15544. } );
  15545. const cosTheta2 = cosTheta2Sq.sqrt();
  15546. // First interface
  15547. const R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
  15548. const R12 = F_Schlick( { f0: R0, f90: 1.0, dotVH: cosTheta1 } );
  15549. //const R21 = R12;
  15550. const T121 = R12.oneMinus();
  15551. const phi12 = iridescenceIOR.lessThan( outsideIOR ).select( Math.PI, 0.0 );
  15552. const phi21 = float( Math.PI ).sub( phi12 );
  15553. // Second interface
  15554. const baseIOR = Fresnel0ToIor( baseF0.clamp( 0.0, 0.9999 ) ); // guard against 1.0
  15555. const R1 = IorToFresnel0( baseIOR, iridescenceIOR.toVec3() );
  15556. const R23 = F_Schlick( { f0: R1, f90: 1.0, dotVH: cosTheta2 } );
  15557. const phi23 = vec3(
  15558. baseIOR.x.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  15559. baseIOR.y.lessThan( iridescenceIOR ).select( Math.PI, 0.0 ),
  15560. baseIOR.z.lessThan( iridescenceIOR ).select( Math.PI, 0.0 )
  15561. );
  15562. // Phase shift
  15563. const OPD = iridescenceIOR.mul( thinFilmThickness, cosTheta2, 2.0 );
  15564. const phi = vec3( phi21 ).add( phi23 );
  15565. // Compound terms
  15566. const R123 = R12.mul( R23 ).clamp( 1e-5, 0.9999 );
  15567. const r123 = R123.sqrt();
  15568. const Rs = T121.pow2().mul( R23 ).div( vec3( 1.0 ).sub( R123 ) );
  15569. // Reflectance term for m = 0 (DC term amplitude)
  15570. const C0 = R12.add( Rs );
  15571. const I = C0.toVar();
  15572. // Reflectance term for m > 0 (pairs of diracs)
  15573. const Cm = Rs.sub( T121 ).toVar();
  15574. Loop( { start: 1, end: 2, condition: '<=', name: 'm' }, ( { m } ) => {
  15575. Cm.mulAssign( r123 );
  15576. const Sm = evalSensitivity( float( m ).mul( OPD ), float( m ).mul( phi ) ).mul( 2.0 );
  15577. I.addAssign( Cm.mul( Sm ) );
  15578. } );
  15579. // Since out of gamut colors might be produced, negative color values are clamped to 0.
  15580. return I.max( vec3( 0.0 ) );
  15581. } ).setLayout( {
  15582. name: 'evalIridescence',
  15583. type: 'vec3',
  15584. inputs: [
  15585. { name: 'outsideIOR', type: 'float' },
  15586. { name: 'eta2', type: 'float' },
  15587. { name: 'cosTheta1', type: 'float' },
  15588. { name: 'thinFilmThickness', type: 'float' },
  15589. { name: 'baseF0', type: 'vec3' }
  15590. ]
  15591. } );
  15592. //
  15593. // Sheen
  15594. //
  15595. // This is a curve-fit approximation to the "Charlie sheen" BRDF integrated over the hemisphere from
  15596. // Estevez and Kulla 2017, "Production Friendly Microfacet Sheen BRDF". The analysis can be found
  15597. // in the Sheen section of https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
  15598. const IBLSheenBRDF = /*@__PURE__*/ Fn( ( { normal, viewDir, roughness } ) => {
  15599. const dotNV = normal.dot( viewDir ).saturate();
  15600. const r2 = roughness.pow2();
  15601. const a = select(
  15602. roughness.lessThan( 0.25 ),
  15603. float( -339.2 ).mul( r2 ).add( float( 161.4 ).mul( roughness ) ).sub( 25.9 ),
  15604. float( -8.48 ).mul( r2 ).add( float( 14.3 ).mul( roughness ) ).sub( 9.95 )
  15605. );
  15606. const b = select(
  15607. roughness.lessThan( 0.25 ),
  15608. float( 44.0 ).mul( r2 ).sub( float( 23.7 ).mul( roughness ) ).add( 3.26 ),
  15609. float( 1.97 ).mul( r2 ).sub( float( 3.27 ).mul( roughness ) ).add( 0.72 )
  15610. );
  15611. const DG = select( roughness.lessThan( 0.25 ), 0.0, float( 0.1 ).mul( roughness ).sub( 0.025 ) ).add( a.mul( dotNV ).add( b ).exp() );
  15612. return DG.mul( 1.0 / Math.PI ).saturate();
  15613. } );
  15614. const clearcoatF0 = vec3( 0.04 );
  15615. const clearcoatF90 = float( 1 );
  15616. /**
  15617. * Represents the lighting model for a PBR material.
  15618. *
  15619. * @augments LightingModel
  15620. */
  15621. class PhysicalLightingModel extends LightingModel {
  15622. /**
  15623. * Constructs a new physical lighting model.
  15624. *
  15625. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  15626. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  15627. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  15628. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  15629. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  15630. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  15631. */
  15632. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false ) {
  15633. super();
  15634. /**
  15635. * Whether clearcoat is supported or not.
  15636. *
  15637. * @type {boolean}
  15638. * @default false
  15639. */
  15640. this.clearcoat = clearcoat;
  15641. /**
  15642. * Whether sheen is supported or not.
  15643. *
  15644. * @type {boolean}
  15645. * @default false
  15646. */
  15647. this.sheen = sheen;
  15648. /**
  15649. * Whether iridescence is supported or not.
  15650. *
  15651. * @type {boolean}
  15652. * @default false
  15653. */
  15654. this.iridescence = iridescence;
  15655. /**
  15656. * Whether anisotropy is supported or not.
  15657. *
  15658. * @type {boolean}
  15659. * @default false
  15660. */
  15661. this.anisotropy = anisotropy;
  15662. /**
  15663. * Whether transmission is supported or not.
  15664. *
  15665. * @type {boolean}
  15666. * @default false
  15667. */
  15668. this.transmission = transmission;
  15669. /**
  15670. * Whether dispersion is supported or not.
  15671. *
  15672. * @type {boolean}
  15673. * @default false
  15674. */
  15675. this.dispersion = dispersion;
  15676. /**
  15677. * The clear coat radiance.
  15678. *
  15679. * @type {?Node}
  15680. * @default null
  15681. */
  15682. this.clearcoatRadiance = null;
  15683. /**
  15684. * The clear coat specular direct.
  15685. *
  15686. * @type {?Node}
  15687. * @default null
  15688. */
  15689. this.clearcoatSpecularDirect = null;
  15690. /**
  15691. * The clear coat specular indirect.
  15692. *
  15693. * @type {?Node}
  15694. * @default null
  15695. */
  15696. this.clearcoatSpecularIndirect = null;
  15697. /**
  15698. * The sheen specular direct.
  15699. *
  15700. * @type {?Node}
  15701. * @default null
  15702. */
  15703. this.sheenSpecularDirect = null;
  15704. /**
  15705. * The sheen specular indirect.
  15706. *
  15707. * @type {?Node}
  15708. * @default null
  15709. */
  15710. this.sheenSpecularIndirect = null;
  15711. /**
  15712. * The iridescence Fresnel.
  15713. *
  15714. * @type {?Node}
  15715. * @default null
  15716. */
  15717. this.iridescenceFresnel = null;
  15718. /**
  15719. * The iridescence F0.
  15720. *
  15721. * @type {?Node}
  15722. * @default null
  15723. */
  15724. this.iridescenceF0 = null;
  15725. }
  15726. /**
  15727. * Depending on what features are requested, the method prepares certain node variables
  15728. * which are later used for lighting computations.
  15729. *
  15730. * @param {NodeBuilder} builder - The current node builder.
  15731. */
  15732. start( builder ) {
  15733. if ( this.clearcoat === true ) {
  15734. this.clearcoatRadiance = vec3().toVar( 'clearcoatRadiance' );
  15735. this.clearcoatSpecularDirect = vec3().toVar( 'clearcoatSpecularDirect' );
  15736. this.clearcoatSpecularIndirect = vec3().toVar( 'clearcoatSpecularIndirect' );
  15737. }
  15738. if ( this.sheen === true ) {
  15739. this.sheenSpecularDirect = vec3().toVar( 'sheenSpecularDirect' );
  15740. this.sheenSpecularIndirect = vec3().toVar( 'sheenSpecularIndirect' );
  15741. }
  15742. if ( this.iridescence === true ) {
  15743. const dotNVi = transformedNormalView.dot( positionViewDirection ).clamp();
  15744. this.iridescenceFresnel = evalIridescence( {
  15745. outsideIOR: float( 1.0 ),
  15746. eta2: iridescenceIOR,
  15747. cosTheta1: dotNVi,
  15748. thinFilmThickness: iridescenceThickness,
  15749. baseF0: specularColor
  15750. } );
  15751. this.iridescenceF0 = Schlick_to_F0( { f: this.iridescenceFresnel, f90: 1.0, dotVH: dotNVi } );
  15752. }
  15753. if ( this.transmission === true ) {
  15754. const position = positionWorld;
  15755. const v = cameraPosition.sub( positionWorld ).normalize(); // TODO: Create Node for this, same issue in MaterialX
  15756. const n = transformedNormalWorld;
  15757. const context = builder.context;
  15758. context.backdrop = getIBLVolumeRefraction(
  15759. n,
  15760. v,
  15761. roughness,
  15762. diffuseColor,
  15763. specularColor,
  15764. specularF90, // specularF90
  15765. position, // positionWorld
  15766. modelWorldMatrix, // modelMatrix
  15767. cameraViewMatrix, // viewMatrix
  15768. cameraProjectionMatrix, // projMatrix
  15769. ior,
  15770. thickness,
  15771. attenuationColor,
  15772. attenuationDistance,
  15773. this.dispersion ? dispersion : null
  15774. );
  15775. context.backdropAlpha = transmission;
  15776. diffuseColor.a.mulAssign( mix( 1, context.backdrop.a, transmission ) );
  15777. }
  15778. super.start( builder );
  15779. }
  15780. // Fdez-Agüera's "Multiple-Scattering Microfacet Model for Real-Time Image Based Lighting"
  15781. // Approximates multi-scattering in order to preserve energy.
  15782. // http://www.jcgt.org/published/0008/01/03/
  15783. computeMultiscattering( singleScatter, multiScatter, specularF90 ) {
  15784. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15785. const fab = DFGApprox( { roughness, dotNV } );
  15786. const Fr = this.iridescenceF0 ? iridescence.mix( specularColor, this.iridescenceF0 ) : specularColor;
  15787. const FssEss = Fr.mul( fab.x ).add( specularF90.mul( fab.y ) );
  15788. const Ess = fab.x.add( fab.y );
  15789. const Ems = Ess.oneMinus();
  15790. const Favg = specularColor.add( specularColor.oneMinus().mul( 0.047619 ) ); // 1/21
  15791. const Fms = FssEss.mul( Favg ).div( Ems.mul( Favg ).oneMinus() );
  15792. singleScatter.addAssign( FssEss );
  15793. multiScatter.addAssign( Fms.mul( Ems ) );
  15794. }
  15795. /**
  15796. * Implements the direct light.
  15797. *
  15798. * @param {Object} lightData - The light data.
  15799. * @param {NodeBuilder} builder - The current node builder.
  15800. */
  15801. direct( { lightDirection, lightColor, reflectedLight } ) {
  15802. const dotNL = transformedNormalView.dot( lightDirection ).clamp();
  15803. const irradiance = dotNL.mul( lightColor );
  15804. if ( this.sheen === true ) {
  15805. this.sheenSpecularDirect.addAssign( irradiance.mul( BRDF_Sheen( { lightDirection } ) ) );
  15806. }
  15807. if ( this.clearcoat === true ) {
  15808. const dotNLcc = transformedClearcoatNormalView.dot( lightDirection ).clamp();
  15809. const ccIrradiance = dotNLcc.mul( lightColor );
  15810. this.clearcoatSpecularDirect.addAssign( ccIrradiance.mul( BRDF_GGX( { lightDirection, f0: clearcoatF0, f90: clearcoatF90, roughness: clearcoatRoughness, normalView: transformedClearcoatNormalView } ) ) );
  15811. }
  15812. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  15813. 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 } ) ) );
  15814. }
  15815. /**
  15816. * This method is intended for implementing the direct light term for
  15817. * rect area light nodes.
  15818. *
  15819. * @param {Object} input - The input data.
  15820. * @param {NodeBuilder} builder - The current node builder.
  15821. */
  15822. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight, reflectedLight, ltc_1, ltc_2 } ) {
  15823. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  15824. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  15825. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  15826. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  15827. const N = transformedNormalView;
  15828. const V = positionViewDirection;
  15829. const P = positionView.toVar();
  15830. const uv = LTC_Uv( { N, V, roughness } );
  15831. const t1 = ltc_1.sample( uv ).toVar();
  15832. const t2 = ltc_2.sample( uv ).toVar();
  15833. const mInv = mat3(
  15834. vec3( t1.x, 0, t1.y ),
  15835. vec3( 0, 1, 0 ),
  15836. vec3( t1.z, 0, t1.w )
  15837. ).toVar();
  15838. // LTC Fresnel Approximation by Stephen Hill
  15839. // http://blog.selfshadow.com/publications/s2016-advances/s2016_ltc_fresnel.pdf
  15840. const fresnel = specularColor.mul( t2.x ).add( specularColor.oneMinus().mul( t2.y ) ).toVar();
  15841. reflectedLight.directSpecular.addAssign( lightColor.mul( fresnel ).mul( LTC_Evaluate( { N, V, P, mInv, p0, p1, p2, p3 } ) ) );
  15842. 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 } ) ) );
  15843. }
  15844. /**
  15845. * Implements the indirect lighting.
  15846. *
  15847. * @param {NodeBuilder} builder - The current node builder.
  15848. */
  15849. indirect( builder ) {
  15850. this.indirectDiffuse( builder );
  15851. this.indirectSpecular( builder );
  15852. this.ambientOcclusion( builder );
  15853. }
  15854. /**
  15855. * Implements the indirect diffuse term.
  15856. *
  15857. * @param {NodeBuilder} builder - The current node builder.
  15858. */
  15859. indirectDiffuse( builder ) {
  15860. const { irradiance, reflectedLight } = builder.context;
  15861. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  15862. }
  15863. /**
  15864. * Implements the indirect specular term.
  15865. *
  15866. * @param {NodeBuilder} builder - The current node builder.
  15867. */
  15868. indirectSpecular( builder ) {
  15869. const { radiance, iblIrradiance, reflectedLight } = builder.context;
  15870. if ( this.sheen === true ) {
  15871. this.sheenSpecularIndirect.addAssign( iblIrradiance.mul(
  15872. sheen,
  15873. IBLSheenBRDF( {
  15874. normal: transformedNormalView,
  15875. viewDir: positionViewDirection,
  15876. roughness: sheenRoughness
  15877. } )
  15878. ) );
  15879. }
  15880. if ( this.clearcoat === true ) {
  15881. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  15882. const clearcoatEnv = EnvironmentBRDF( {
  15883. dotNV: dotNVcc,
  15884. specularColor: clearcoatF0,
  15885. specularF90: clearcoatF90,
  15886. roughness: clearcoatRoughness
  15887. } );
  15888. this.clearcoatSpecularIndirect.addAssign( this.clearcoatRadiance.mul( clearcoatEnv ) );
  15889. }
  15890. // Both indirect specular and indirect diffuse light accumulate here
  15891. const singleScattering = vec3().toVar( 'singleScattering' );
  15892. const multiScattering = vec3().toVar( 'multiScattering' );
  15893. const cosineWeightedIrradiance = iblIrradiance.mul( 1 / Math.PI );
  15894. this.computeMultiscattering( singleScattering, multiScattering, specularF90 );
  15895. const totalScattering = singleScattering.add( multiScattering );
  15896. const diffuse = diffuseColor.mul( totalScattering.r.max( totalScattering.g ).max( totalScattering.b ).oneMinus() );
  15897. reflectedLight.indirectSpecular.addAssign( radiance.mul( singleScattering ) );
  15898. reflectedLight.indirectSpecular.addAssign( multiScattering.mul( cosineWeightedIrradiance ) );
  15899. reflectedLight.indirectDiffuse.addAssign( diffuse.mul( cosineWeightedIrradiance ) );
  15900. }
  15901. /**
  15902. * Implements the ambient occlusion term.
  15903. *
  15904. * @param {NodeBuilder} builder - The current node builder.
  15905. */
  15906. ambientOcclusion( builder ) {
  15907. const { ambientOcclusion, reflectedLight } = builder.context;
  15908. const dotNV = transformedNormalView.dot( positionViewDirection ).clamp(); // @ TODO: Move to core dotNV
  15909. const aoNV = dotNV.add( ambientOcclusion );
  15910. const aoExp = roughness.mul( -16 ).oneMinus().negate().exp2();
  15911. const aoNode = ambientOcclusion.sub( aoNV.pow( aoExp ).oneMinus() ).clamp();
  15912. if ( this.clearcoat === true ) {
  15913. this.clearcoatSpecularIndirect.mulAssign( ambientOcclusion );
  15914. }
  15915. if ( this.sheen === true ) {
  15916. this.sheenSpecularIndirect.mulAssign( ambientOcclusion );
  15917. }
  15918. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  15919. reflectedLight.indirectSpecular.mulAssign( aoNode );
  15920. }
  15921. /**
  15922. * Used for final lighting accumulations depending on the requested features.
  15923. *
  15924. * @param {NodeBuilder} builder - The current node builder.
  15925. */
  15926. finish( { context } ) {
  15927. const { outgoingLight } = context;
  15928. if ( this.clearcoat === true ) {
  15929. const dotNVcc = transformedClearcoatNormalView.dot( positionViewDirection ).clamp();
  15930. const Fcc = F_Schlick( {
  15931. dotVH: dotNVcc,
  15932. f0: clearcoatF0,
  15933. f90: clearcoatF90
  15934. } );
  15935. const clearcoatLight = outgoingLight.mul( clearcoat.mul( Fcc ).oneMinus() ).add( this.clearcoatSpecularDirect.add( this.clearcoatSpecularIndirect ).mul( clearcoat ) );
  15936. outgoingLight.assign( clearcoatLight );
  15937. }
  15938. if ( this.sheen === true ) {
  15939. const sheenEnergyComp = sheen.r.max( sheen.g ).max( sheen.b ).mul( 0.157 ).oneMinus();
  15940. const sheenLight = outgoingLight.mul( sheenEnergyComp ).add( this.sheenSpecularDirect, this.sheenSpecularIndirect );
  15941. outgoingLight.assign( sheenLight );
  15942. }
  15943. }
  15944. }
  15945. // These defines must match with PMREMGenerator
  15946. const cubeUV_r0 = /*@__PURE__*/ float( 1.0 );
  15947. const cubeUV_m0 = /*@__PURE__*/ float( -2 );
  15948. const cubeUV_r1 = /*@__PURE__*/ float( 0.8 );
  15949. const cubeUV_m1 = /*@__PURE__*/ float( -1 );
  15950. const cubeUV_r4 = /*@__PURE__*/ float( 0.4 );
  15951. const cubeUV_m4 = /*@__PURE__*/ float( 2.0 );
  15952. const cubeUV_r5 = /*@__PURE__*/ float( 0.305 );
  15953. const cubeUV_m5 = /*@__PURE__*/ float( 3.0 );
  15954. const cubeUV_r6 = /*@__PURE__*/ float( 0.21 );
  15955. const cubeUV_m6 = /*@__PURE__*/ float( 4.0 );
  15956. const cubeUV_minMipLevel = /*@__PURE__*/ float( 4.0 );
  15957. const cubeUV_minTileSize = /*@__PURE__*/ float( 16.0 );
  15958. // These shader functions convert between the UV coordinates of a single face of
  15959. // a cubemap, the 0-5 integer index of a cube face, and the direction vector for
  15960. // sampling a textureCube (not generally normalized ).
  15961. const getFace = /*@__PURE__*/ Fn( ( [ direction ] ) => {
  15962. const absDirection = vec3( abs( direction ) ).toVar();
  15963. const face = float( -1 ).toVar();
  15964. If( absDirection.x.greaterThan( absDirection.z ), () => {
  15965. If( absDirection.x.greaterThan( absDirection.y ), () => {
  15966. face.assign( select( direction.x.greaterThan( 0.0 ), 0.0, 3.0 ) );
  15967. } ).Else( () => {
  15968. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  15969. } );
  15970. } ).Else( () => {
  15971. If( absDirection.z.greaterThan( absDirection.y ), () => {
  15972. face.assign( select( direction.z.greaterThan( 0.0 ), 2.0, 5.0 ) );
  15973. } ).Else( () => {
  15974. face.assign( select( direction.y.greaterThan( 0.0 ), 1.0, 4.0 ) );
  15975. } );
  15976. } );
  15977. return face;
  15978. } ).setLayout( {
  15979. name: 'getFace',
  15980. type: 'float',
  15981. inputs: [
  15982. { name: 'direction', type: 'vec3' }
  15983. ]
  15984. } );
  15985. // RH coordinate system; PMREM face-indexing convention
  15986. const getUV = /*@__PURE__*/ Fn( ( [ direction, face ] ) => {
  15987. const uv = vec2().toVar();
  15988. If( face.equal( 0.0 ), () => {
  15989. uv.assign( vec2( direction.z, direction.y ).div( abs( direction.x ) ) ); // pos x
  15990. } ).ElseIf( face.equal( 1.0 ), () => {
  15991. uv.assign( vec2( direction.x.negate(), direction.z.negate() ).div( abs( direction.y ) ) ); // pos y
  15992. } ).ElseIf( face.equal( 2.0 ), () => {
  15993. uv.assign( vec2( direction.x.negate(), direction.y ).div( abs( direction.z ) ) ); // pos z
  15994. } ).ElseIf( face.equal( 3.0 ), () => {
  15995. uv.assign( vec2( direction.z.negate(), direction.y ).div( abs( direction.x ) ) ); // neg x
  15996. } ).ElseIf( face.equal( 4.0 ), () => {
  15997. uv.assign( vec2( direction.x.negate(), direction.z ).div( abs( direction.y ) ) ); // neg y
  15998. } ).Else( () => {
  15999. uv.assign( vec2( direction.x, direction.y ).div( abs( direction.z ) ) ); // neg z
  16000. } );
  16001. return mul( 0.5, uv.add( 1.0 ) );
  16002. } ).setLayout( {
  16003. name: 'getUV',
  16004. type: 'vec2',
  16005. inputs: [
  16006. { name: 'direction', type: 'vec3' },
  16007. { name: 'face', type: 'float' }
  16008. ]
  16009. } );
  16010. const roughnessToMip = /*@__PURE__*/ Fn( ( [ roughness ] ) => {
  16011. const mip = float( 0.0 ).toVar();
  16012. If( roughness.greaterThanEqual( cubeUV_r1 ), () => {
  16013. mip.assign( cubeUV_r0.sub( roughness ).mul( cubeUV_m1.sub( cubeUV_m0 ) ).div( cubeUV_r0.sub( cubeUV_r1 ) ).add( cubeUV_m0 ) );
  16014. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r4 ), () => {
  16015. mip.assign( cubeUV_r1.sub( roughness ).mul( cubeUV_m4.sub( cubeUV_m1 ) ).div( cubeUV_r1.sub( cubeUV_r4 ) ).add( cubeUV_m1 ) );
  16016. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r5 ), () => {
  16017. mip.assign( cubeUV_r4.sub( roughness ).mul( cubeUV_m5.sub( cubeUV_m4 ) ).div( cubeUV_r4.sub( cubeUV_r5 ) ).add( cubeUV_m4 ) );
  16018. } ).ElseIf( roughness.greaterThanEqual( cubeUV_r6 ), () => {
  16019. mip.assign( cubeUV_r5.sub( roughness ).mul( cubeUV_m6.sub( cubeUV_m5 ) ).div( cubeUV_r5.sub( cubeUV_r6 ) ).add( cubeUV_m5 ) );
  16020. } ).Else( () => {
  16021. mip.assign( float( -2 ).mul( log2( mul( 1.16, roughness ) ) ) ); // 1.16 = 1.79^0.25
  16022. } );
  16023. return mip;
  16024. } ).setLayout( {
  16025. name: 'roughnessToMip',
  16026. type: 'float',
  16027. inputs: [
  16028. { name: 'roughness', type: 'float' }
  16029. ]
  16030. } );
  16031. // RH coordinate system; PMREM face-indexing convention
  16032. const getDirection = /*@__PURE__*/ Fn( ( [ uv_immutable, face ] ) => {
  16033. const uv = uv_immutable.toVar();
  16034. uv.assign( mul( 2.0, uv ).sub( 1.0 ) );
  16035. const direction = vec3( uv, 1.0 ).toVar();
  16036. If( face.equal( 0.0 ), () => {
  16037. direction.assign( direction.zyx ); // ( 1, v, u ) pos x
  16038. } ).ElseIf( face.equal( 1.0 ), () => {
  16039. direction.assign( direction.xzy );
  16040. direction.xz.mulAssign( -1 ); // ( -u, 1, -v ) pos y
  16041. } ).ElseIf( face.equal( 2.0 ), () => {
  16042. direction.x.mulAssign( -1 ); // ( -u, v, 1 ) pos z
  16043. } ).ElseIf( face.equal( 3.0 ), () => {
  16044. direction.assign( direction.zyx );
  16045. direction.xz.mulAssign( -1 ); // ( -1, v, -u ) neg x
  16046. } ).ElseIf( face.equal( 4.0 ), () => {
  16047. direction.assign( direction.xzy );
  16048. direction.xy.mulAssign( -1 ); // ( -u, -1, v ) neg y
  16049. } ).ElseIf( face.equal( 5.0 ), () => {
  16050. direction.z.mulAssign( -1 ); // ( u, v, -1 ) neg zS
  16051. } );
  16052. return direction;
  16053. } ).setLayout( {
  16054. name: 'getDirection',
  16055. type: 'vec3',
  16056. inputs: [
  16057. { name: 'uv', type: 'vec2' },
  16058. { name: 'face', type: 'float' }
  16059. ]
  16060. } );
  16061. //
  16062. const textureCubeUV = /*@__PURE__*/ Fn( ( [ envMap, sampleDir_immutable, roughness_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16063. const roughness = float( roughness_immutable );
  16064. const sampleDir = vec3( sampleDir_immutable );
  16065. const mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP );
  16066. const mipF = fract( mip );
  16067. const mipInt = floor( mip );
  16068. const color0 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16069. If( mipF.notEqual( 0.0 ), () => {
  16070. const color1 = vec3( bilinearCubeUV( envMap, sampleDir, mipInt.add( 1.0 ), CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ) ).toVar();
  16071. color0.assign( mix( color0, color1, mipF ) );
  16072. } );
  16073. return color0;
  16074. } );
  16075. const bilinearCubeUV = /*@__PURE__*/ Fn( ( [ envMap, direction_immutable, mipInt_immutable, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP ] ) => {
  16076. const mipInt = float( mipInt_immutable ).toVar();
  16077. const direction = vec3( direction_immutable );
  16078. const face = float( getFace( direction ) ).toVar();
  16079. const filterInt = float( max$1( cubeUV_minMipLevel.sub( mipInt ), 0.0 ) ).toVar();
  16080. mipInt.assign( max$1( mipInt, cubeUV_minMipLevel ) );
  16081. const faceSize = float( exp2( mipInt ) ).toVar();
  16082. const uv = vec2( getUV( direction, face ).mul( faceSize.sub( 2.0 ) ).add( 1.0 ) ).toVar();
  16083. If( face.greaterThan( 2.0 ), () => {
  16084. uv.y.addAssign( faceSize );
  16085. face.subAssign( 3.0 );
  16086. } );
  16087. uv.x.addAssign( face.mul( faceSize ) );
  16088. uv.x.addAssign( filterInt.mul( mul( 3.0, cubeUV_minTileSize ) ) );
  16089. uv.y.addAssign( mul( 4.0, exp2( CUBEUV_MAX_MIP ).sub( faceSize ) ) );
  16090. uv.x.mulAssign( CUBEUV_TEXEL_WIDTH );
  16091. uv.y.mulAssign( CUBEUV_TEXEL_HEIGHT );
  16092. return envMap.sample( uv ).grad( vec2(), vec2() ); // disable anisotropic filtering
  16093. } );
  16094. const getSample = /*@__PURE__*/ Fn( ( { envMap, mipInt, outputDirection, theta, axis, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16095. const cosTheta = cos( theta );
  16096. // Rodrigues' axis-angle rotation
  16097. const sampleDirection = outputDirection.mul( cosTheta )
  16098. .add( axis.cross( outputDirection ).mul( sin( theta ) ) )
  16099. .add( axis.mul( axis.dot( outputDirection ).mul( cosTheta.oneMinus() ) ) );
  16100. return bilinearCubeUV( envMap, sampleDirection, mipInt, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP );
  16101. } );
  16102. const blur = /*@__PURE__*/ Fn( ( { n, latitudinal, poleAxis, outputDirection, weights, samples, dTheta, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) => {
  16103. const axis = vec3( select( latitudinal, poleAxis, cross( poleAxis, outputDirection ) ) ).toVar();
  16104. If( axis.equal( vec3( 0.0 ) ), () => {
  16105. axis.assign( vec3( outputDirection.z, 0.0, outputDirection.x.negate() ) );
  16106. } );
  16107. axis.assign( normalize( axis ) );
  16108. const gl_FragColor = vec3().toVar();
  16109. gl_FragColor.addAssign( weights.element( 0 ).mul( getSample( { theta: 0.0, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  16110. Loop( { start: int( 1 ), end: n }, ( { i } ) => {
  16111. If( i.greaterThanEqual( samples ), () => {
  16112. Break();
  16113. } );
  16114. const theta = float( dTheta.mul( float( i ) ) ).toVar();
  16115. 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 } ) ) );
  16116. gl_FragColor.addAssign( weights.element( i ).mul( getSample( { theta, axis, outputDirection, mipInt, envMap, CUBEUV_TEXEL_WIDTH, CUBEUV_TEXEL_HEIGHT, CUBEUV_MAX_MIP } ) ) );
  16117. } );
  16118. return vec4( gl_FragColor, 1 );
  16119. } );
  16120. const LOD_MIN = 4;
  16121. // The standard deviations (radians) associated with the extra mips. These are
  16122. // chosen to approximate a Trowbridge-Reitz distribution function times the
  16123. // geometric shadowing function. These sigma values squared must match the
  16124. // variance #defines in cube_uv_reflection_fragment.glsl.js.
  16125. const EXTRA_LOD_SIGMA = [ 0.125, 0.215, 0.35, 0.446, 0.526, 0.582 ];
  16126. // The maximum length of the blur for loop. Smaller sigmas will use fewer
  16127. // samples and exit early, but not recompile the shader.
  16128. const MAX_SAMPLES = 20;
  16129. const _flatCamera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  16130. const _cubeCamera = /*@__PURE__*/ new PerspectiveCamera( 90, 1 );
  16131. const _clearColor$2 = /*@__PURE__*/ new Color();
  16132. let _oldTarget = null;
  16133. let _oldActiveCubeFace = 0;
  16134. let _oldActiveMipmapLevel = 0;
  16135. // Golden Ratio
  16136. const PHI = ( 1 + Math.sqrt( 5 ) ) / 2;
  16137. const INV_PHI = 1 / PHI;
  16138. // Vertices of a dodecahedron (except the opposites, which represent the
  16139. // same axis), used as axis directions evenly spread on a sphere.
  16140. const _axisDirections = [
  16141. /*@__PURE__*/ new Vector3( - PHI, INV_PHI, 0 ),
  16142. /*@__PURE__*/ new Vector3( PHI, INV_PHI, 0 ),
  16143. /*@__PURE__*/ new Vector3( - INV_PHI, 0, PHI ),
  16144. /*@__PURE__*/ new Vector3( INV_PHI, 0, PHI ),
  16145. /*@__PURE__*/ new Vector3( 0, PHI, - INV_PHI ),
  16146. /*@__PURE__*/ new Vector3( 0, PHI, INV_PHI ),
  16147. /*@__PURE__*/ new Vector3( -1, 1, -1 ),
  16148. /*@__PURE__*/ new Vector3( 1, 1, -1 ),
  16149. /*@__PURE__*/ new Vector3( -1, 1, 1 ),
  16150. /*@__PURE__*/ new Vector3( 1, 1, 1 )
  16151. ];
  16152. const _origin = /*@__PURE__*/ new Vector3();
  16153. // maps blur materials to their uniforms dictionary
  16154. const _uniformsMap = new WeakMap();
  16155. // WebGPU Face indices
  16156. const _faceLib = [
  16157. 3, 1, 5,
  16158. 0, 4, 2
  16159. ];
  16160. const _direction = /*@__PURE__*/ getDirection( uv(), attribute( 'faceIndex' ) ).normalize();
  16161. const _outputDirection = /*@__PURE__*/ vec3( _direction.x, _direction.y, _direction.z );
  16162. /**
  16163. * This class generates a Prefiltered, Mipmapped Radiance Environment Map
  16164. * (PMREM) from a cubeMap environment texture. This allows different levels of
  16165. * blur to be quickly accessed based on material roughness. It is packed into a
  16166. * special CubeUV format that allows us to perform custom interpolation so that
  16167. * we can support nonlinear formats such as RGBE. Unlike a traditional mipmap
  16168. * chain, it only goes down to the LOD_MIN level (above), and then creates extra
  16169. * even more filtered 'mips' at the same LOD_MIN resolution, associated with
  16170. * higher roughness levels. In this way we maintain resolution to smoothly
  16171. * interpolate diffuse lighting while limiting sampling computation.
  16172. *
  16173. * Paper: Fast, Accurate Image-Based Lighting:
  16174. * {@link https://drive.google.com/file/d/15y8r_UpKlU9SvV4ILb0C3qCPecS8pvLz/view}
  16175. */
  16176. class PMREMGenerator {
  16177. /**
  16178. * Constructs a new PMREM generator.
  16179. *
  16180. * @param {Renderer} renderer - The renderer.
  16181. */
  16182. constructor( renderer ) {
  16183. this._renderer = renderer;
  16184. this._pingPongRenderTarget = null;
  16185. this._lodMax = 0;
  16186. this._cubeSize = 0;
  16187. this._lodPlanes = [];
  16188. this._sizeLods = [];
  16189. this._sigmas = [];
  16190. this._lodMeshes = [];
  16191. this._blurMaterial = null;
  16192. this._cubemapMaterial = null;
  16193. this._equirectMaterial = null;
  16194. this._backgroundBox = null;
  16195. }
  16196. get _hasInitialized() {
  16197. return this._renderer.hasInitialized();
  16198. }
  16199. /**
  16200. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16201. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16202. * in radians to be applied to the scene before PMREM generation. Optional near
  16203. * and far planes ensure the scene is rendered in its entirety.
  16204. *
  16205. * @param {Scene} scene - The scene to be captured.
  16206. * @param {number} [sigma=0] - The blur radius in radians.
  16207. * @param {number} [near=0.1] - The near plane distance.
  16208. * @param {number} [far=100] - The far plane distance.
  16209. * @param {Object} [options={}] - The configuration options.
  16210. * @param {number} [options.size=256] - The texture size of the PMREM.
  16211. * @param {Vector3} [options.renderTarget=origin] - The position of the internal cube camera that renders the scene.
  16212. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16213. * @return {RenderTarget} The resulting PMREM.
  16214. * @see {@link PMREMGenerator#fromSceneAsync}
  16215. */
  16216. fromScene( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16217. const {
  16218. size = 256,
  16219. position = _origin,
  16220. renderTarget = null,
  16221. } = options;
  16222. this._setSize( size );
  16223. if ( this._hasInitialized === false ) {
  16224. console.warn( 'THREE.PMREMGenerator: .fromScene() called before the backend is initialized. Try using .fromSceneAsync() instead.' );
  16225. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16226. options.renderTarget = cubeUVRenderTarget;
  16227. this.fromSceneAsync( scene, sigma, near, far, options );
  16228. return cubeUVRenderTarget;
  16229. }
  16230. _oldTarget = this._renderer.getRenderTarget();
  16231. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16232. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16233. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16234. cubeUVRenderTarget.depthBuffer = true;
  16235. this._init( cubeUVRenderTarget );
  16236. this._sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position );
  16237. if ( sigma > 0 ) {
  16238. this._blur( cubeUVRenderTarget, 0, 0, sigma );
  16239. }
  16240. this._applyPMREM( cubeUVRenderTarget );
  16241. this._cleanup( cubeUVRenderTarget );
  16242. return cubeUVRenderTarget;
  16243. }
  16244. /**
  16245. * Generates a PMREM from a supplied Scene, which can be faster than using an
  16246. * image if networking bandwidth is low. Optional sigma specifies a blur radius
  16247. * in radians to be applied to the scene before PMREM generation. Optional near
  16248. * and far planes ensure the scene is rendered in its entirety (the cubeCamera
  16249. * is placed at the origin).
  16250. *
  16251. * @param {Scene} scene - The scene to be captured.
  16252. * @param {number} [sigma=0] - The blur radius in radians.
  16253. * @param {number} [near=0.1] - The near plane distance.
  16254. * @param {number} [far=100] - The far plane distance.
  16255. * @param {Object} [options={}] - The configuration options.
  16256. * @param {number} [options.size=256] - The texture size of the PMREM.
  16257. * @param {Vector3} [options.position=origin] - The position of the internal cube camera that renders the scene.
  16258. * @param {?RenderTarget} [options.renderTarget=null] - The render target to use.
  16259. * @return {Promise<RenderTarget>} A Promise that resolve with the PMREM when the generation has been finished.
  16260. * @see {@link PMREMGenerator#fromScene}
  16261. */
  16262. async fromSceneAsync( scene, sigma = 0, near = 0.1, far = 100, options = {} ) {
  16263. if ( this._hasInitialized === false ) await this._renderer.init();
  16264. return this.fromScene( scene, sigma, near, far, options );
  16265. }
  16266. /**
  16267. * Generates a PMREM from an equirectangular texture, which can be either LDR
  16268. * or HDR. The ideal input image size is 1k (1024 x 512),
  16269. * as this matches best with the 256 x 256 cubemap output.
  16270. *
  16271. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  16272. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16273. * @return {RenderTarget} The resulting PMREM.
  16274. * @see {@link PMREMGenerator#fromEquirectangularAsync}
  16275. */
  16276. fromEquirectangular( equirectangular, renderTarget = null ) {
  16277. if ( this._hasInitialized === false ) {
  16278. console.warn( 'THREE.PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using .fromEquirectangularAsync() instead.' );
  16279. this._setSizeFromTexture( equirectangular );
  16280. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16281. this.fromEquirectangularAsync( equirectangular, cubeUVRenderTarget );
  16282. return cubeUVRenderTarget;
  16283. }
  16284. return this._fromTexture( equirectangular, renderTarget );
  16285. }
  16286. /**
  16287. * Generates a PMREM from an equirectangular texture, which can be either LDR
  16288. * or HDR. The ideal input image size is 1k (1024 x 512),
  16289. * as this matches best with the 256 x 256 cubemap output.
  16290. *
  16291. * @param {Texture} equirectangular - The equirectangular texture to be converted.
  16292. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16293. * @return {Promise<RenderTarget>} The resulting PMREM.
  16294. * @see {@link PMREMGenerator#fromEquirectangular}
  16295. */
  16296. async fromEquirectangularAsync( equirectangular, renderTarget = null ) {
  16297. if ( this._hasInitialized === false ) await this._renderer.init();
  16298. return this._fromTexture( equirectangular, renderTarget );
  16299. }
  16300. /**
  16301. * Generates a PMREM from an cubemap texture, which can be either LDR
  16302. * or HDR. The ideal input cube size is 256 x 256,
  16303. * as this matches best with the 256 x 256 cubemap output.
  16304. *
  16305. * @param {Texture} cubemap - The cubemap texture to be converted.
  16306. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16307. * @return {RenderTarget} The resulting PMREM.
  16308. * @see {@link PMREMGenerator#fromCubemapAsync}
  16309. */
  16310. fromCubemap( cubemap, renderTarget = null ) {
  16311. if ( this._hasInitialized === false ) {
  16312. console.warn( 'THREE.PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead.' );
  16313. this._setSizeFromTexture( cubemap );
  16314. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16315. this.fromCubemapAsync( cubemap, renderTarget );
  16316. return cubeUVRenderTarget;
  16317. }
  16318. return this._fromTexture( cubemap, renderTarget );
  16319. }
  16320. /**
  16321. * Generates a PMREM from an cubemap texture, which can be either LDR
  16322. * or HDR. The ideal input cube size is 256 x 256,
  16323. * with the 256 x 256 cubemap output.
  16324. *
  16325. * @param {Texture} cubemap - The cubemap texture to be converted.
  16326. * @param {?RenderTarget} [renderTarget=null] - The render target to use.
  16327. * @return {Promise<RenderTarget>} The resulting PMREM.
  16328. * @see {@link PMREMGenerator#fromCubemap}
  16329. */
  16330. async fromCubemapAsync( cubemap, renderTarget = null ) {
  16331. if ( this._hasInitialized === false ) await this._renderer.init();
  16332. return this._fromTexture( cubemap, renderTarget );
  16333. }
  16334. /**
  16335. * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during
  16336. * your texture's network fetch for increased concurrency.
  16337. *
  16338. * @returns {Promise}
  16339. */
  16340. async compileCubemapShader() {
  16341. if ( this._cubemapMaterial === null ) {
  16342. this._cubemapMaterial = _getCubemapMaterial();
  16343. await this._compileMaterial( this._cubemapMaterial );
  16344. }
  16345. }
  16346. /**
  16347. * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during
  16348. * your texture's network fetch for increased concurrency.
  16349. *
  16350. * @returns {Promise}
  16351. */
  16352. async compileEquirectangularShader() {
  16353. if ( this._equirectMaterial === null ) {
  16354. this._equirectMaterial = _getEquirectMaterial();
  16355. await this._compileMaterial( this._equirectMaterial );
  16356. }
  16357. }
  16358. /**
  16359. * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class,
  16360. * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on
  16361. * one of them will cause any others to also become unusable.
  16362. */
  16363. dispose() {
  16364. this._dispose();
  16365. if ( this._cubemapMaterial !== null ) this._cubemapMaterial.dispose();
  16366. if ( this._equirectMaterial !== null ) this._equirectMaterial.dispose();
  16367. if ( this._backgroundBox !== null ) {
  16368. this._backgroundBox.geometry.dispose();
  16369. this._backgroundBox.material.dispose();
  16370. }
  16371. }
  16372. // private interface
  16373. _setSizeFromTexture( texture ) {
  16374. if ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping ) {
  16375. this._setSize( texture.image.length === 0 ? 16 : ( texture.image[ 0 ].width || texture.image[ 0 ].image.width ) );
  16376. } else { // Equirectangular
  16377. this._setSize( texture.image.width / 4 );
  16378. }
  16379. }
  16380. _setSize( cubeSize ) {
  16381. this._lodMax = Math.floor( Math.log2( cubeSize ) );
  16382. this._cubeSize = Math.pow( 2, this._lodMax );
  16383. }
  16384. _dispose() {
  16385. if ( this._blurMaterial !== null ) this._blurMaterial.dispose();
  16386. if ( this._pingPongRenderTarget !== null ) this._pingPongRenderTarget.dispose();
  16387. for ( let i = 0; i < this._lodPlanes.length; i ++ ) {
  16388. this._lodPlanes[ i ].dispose();
  16389. }
  16390. }
  16391. _cleanup( outputTarget ) {
  16392. this._renderer.setRenderTarget( _oldTarget, _oldActiveCubeFace, _oldActiveMipmapLevel );
  16393. outputTarget.scissorTest = false;
  16394. _setViewport( outputTarget, 0, 0, outputTarget.width, outputTarget.height );
  16395. }
  16396. _fromTexture( texture, renderTarget ) {
  16397. this._setSizeFromTexture( texture );
  16398. _oldTarget = this._renderer.getRenderTarget();
  16399. _oldActiveCubeFace = this._renderer.getActiveCubeFace();
  16400. _oldActiveMipmapLevel = this._renderer.getActiveMipmapLevel();
  16401. const cubeUVRenderTarget = renderTarget || this._allocateTarget();
  16402. this._init( cubeUVRenderTarget );
  16403. this._textureToCubeUV( texture, cubeUVRenderTarget );
  16404. this._applyPMREM( cubeUVRenderTarget );
  16405. this._cleanup( cubeUVRenderTarget );
  16406. return cubeUVRenderTarget;
  16407. }
  16408. _allocateTarget() {
  16409. const width = 3 * Math.max( this._cubeSize, 16 * 7 );
  16410. const height = 4 * this._cubeSize;
  16411. const cubeUVRenderTarget = _createRenderTarget( width, height );
  16412. return cubeUVRenderTarget;
  16413. }
  16414. _init( renderTarget ) {
  16415. if ( this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== renderTarget.width || this._pingPongRenderTarget.height !== renderTarget.height ) {
  16416. if ( this._pingPongRenderTarget !== null ) {
  16417. this._dispose();
  16418. }
  16419. this._pingPongRenderTarget = _createRenderTarget( renderTarget.width, renderTarget.height );
  16420. const { _lodMax } = this;
  16421. ( { sizeLods: this._sizeLods, lodPlanes: this._lodPlanes, sigmas: this._sigmas, lodMeshes: this._lodMeshes } = _createPlanes( _lodMax ) );
  16422. this._blurMaterial = _getBlurShader( _lodMax, renderTarget.width, renderTarget.height );
  16423. }
  16424. }
  16425. async _compileMaterial( material ) {
  16426. const tmpMesh = new Mesh( this._lodPlanes[ 0 ], material );
  16427. await this._renderer.compile( tmpMesh, _flatCamera );
  16428. }
  16429. _sceneToCubeUV( scene, near, far, cubeUVRenderTarget, position ) {
  16430. const cubeCamera = _cubeCamera;
  16431. cubeCamera.near = near;
  16432. cubeCamera.far = far;
  16433. // px, py, pz, nx, ny, nz
  16434. const upSign = [ 1, 1, 1, 1, -1, 1 ];
  16435. const forwardSign = [ 1, -1, 1, -1, 1, -1 ];
  16436. const renderer = this._renderer;
  16437. const originalAutoClear = renderer.autoClear;
  16438. renderer.getClearColor( _clearColor$2 );
  16439. renderer.autoClear = false;
  16440. let backgroundBox = this._backgroundBox;
  16441. if ( backgroundBox === null ) {
  16442. const backgroundMaterial = new MeshBasicMaterial( {
  16443. name: 'PMREM.Background',
  16444. side: BackSide,
  16445. depthWrite: false,
  16446. depthTest: false
  16447. } );
  16448. backgroundBox = new Mesh( new BoxGeometry(), backgroundMaterial );
  16449. }
  16450. let useSolidColor = false;
  16451. const background = scene.background;
  16452. if ( background ) {
  16453. if ( background.isColor ) {
  16454. backgroundBox.material.color.copy( background );
  16455. scene.background = null;
  16456. useSolidColor = true;
  16457. }
  16458. } else {
  16459. backgroundBox.material.color.copy( _clearColor$2 );
  16460. useSolidColor = true;
  16461. }
  16462. renderer.setRenderTarget( cubeUVRenderTarget );
  16463. renderer.clear();
  16464. if ( useSolidColor ) {
  16465. renderer.render( backgroundBox, cubeCamera );
  16466. }
  16467. for ( let i = 0; i < 6; i ++ ) {
  16468. const col = i % 3;
  16469. if ( col === 0 ) {
  16470. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16471. cubeCamera.position.set( position.x, position.y, position.z );
  16472. cubeCamera.lookAt( position.x + forwardSign[ i ], position.y, position.z );
  16473. } else if ( col === 1 ) {
  16474. cubeCamera.up.set( 0, 0, upSign[ i ] );
  16475. cubeCamera.position.set( position.x, position.y, position.z );
  16476. cubeCamera.lookAt( position.x, position.y + forwardSign[ i ], position.z );
  16477. } else {
  16478. cubeCamera.up.set( 0, upSign[ i ], 0 );
  16479. cubeCamera.position.set( position.x, position.y, position.z );
  16480. cubeCamera.lookAt( position.x, position.y, position.z + forwardSign[ i ] );
  16481. }
  16482. const size = this._cubeSize;
  16483. _setViewport( cubeUVRenderTarget, col * size, i > 2 ? size : 0, size, size );
  16484. renderer.render( scene, cubeCamera );
  16485. }
  16486. renderer.autoClear = originalAutoClear;
  16487. scene.background = background;
  16488. }
  16489. _textureToCubeUV( texture, cubeUVRenderTarget ) {
  16490. const renderer = this._renderer;
  16491. const isCubeTexture = ( texture.mapping === CubeReflectionMapping || texture.mapping === CubeRefractionMapping );
  16492. if ( isCubeTexture ) {
  16493. if ( this._cubemapMaterial === null ) {
  16494. this._cubemapMaterial = _getCubemapMaterial( texture );
  16495. }
  16496. } else {
  16497. if ( this._equirectMaterial === null ) {
  16498. this._equirectMaterial = _getEquirectMaterial( texture );
  16499. }
  16500. }
  16501. const material = isCubeTexture ? this._cubemapMaterial : this._equirectMaterial;
  16502. material.fragmentNode.value = texture;
  16503. const mesh = this._lodMeshes[ 0 ];
  16504. mesh.material = material;
  16505. const size = this._cubeSize;
  16506. _setViewport( cubeUVRenderTarget, 0, 0, 3 * size, 2 * size );
  16507. renderer.setRenderTarget( cubeUVRenderTarget );
  16508. renderer.render( mesh, _flatCamera );
  16509. }
  16510. _applyPMREM( cubeUVRenderTarget ) {
  16511. const renderer = this._renderer;
  16512. const autoClear = renderer.autoClear;
  16513. renderer.autoClear = false;
  16514. const n = this._lodPlanes.length;
  16515. for ( let i = 1; i < n; i ++ ) {
  16516. const sigma = Math.sqrt( this._sigmas[ i ] * this._sigmas[ i ] - this._sigmas[ i - 1 ] * this._sigmas[ i - 1 ] );
  16517. const poleAxis = _axisDirections[ ( n - i - 1 ) % _axisDirections.length ];
  16518. this._blur( cubeUVRenderTarget, i - 1, i, sigma, poleAxis );
  16519. }
  16520. renderer.autoClear = autoClear;
  16521. }
  16522. /**
  16523. * This is a two-pass Gaussian blur for a cubemap. Normally this is done
  16524. * vertically and horizontally, but this breaks down on a cube. Here we apply
  16525. * the blur latitudinally (around the poles), and then longitudinally (towards
  16526. * the poles) to approximate the orthogonally-separable blur. It is least
  16527. * accurate at the poles, but still does a decent job.
  16528. *
  16529. * @private
  16530. * @param {RenderTarget} cubeUVRenderTarget - The cubemap render target.
  16531. * @param {number} lodIn - The input level-of-detail.
  16532. * @param {number} lodOut - The output level-of-detail.
  16533. * @param {number} sigma - The blur radius in radians.
  16534. * @param {Vector3} [poleAxis] - The pole axis.
  16535. */
  16536. _blur( cubeUVRenderTarget, lodIn, lodOut, sigma, poleAxis ) {
  16537. const pingPongRenderTarget = this._pingPongRenderTarget;
  16538. this._halfBlur(
  16539. cubeUVRenderTarget,
  16540. pingPongRenderTarget,
  16541. lodIn,
  16542. lodOut,
  16543. sigma,
  16544. 'latitudinal',
  16545. poleAxis );
  16546. this._halfBlur(
  16547. pingPongRenderTarget,
  16548. cubeUVRenderTarget,
  16549. lodOut,
  16550. lodOut,
  16551. sigma,
  16552. 'longitudinal',
  16553. poleAxis );
  16554. }
  16555. _halfBlur( targetIn, targetOut, lodIn, lodOut, sigmaRadians, direction, poleAxis ) {
  16556. const renderer = this._renderer;
  16557. const blurMaterial = this._blurMaterial;
  16558. if ( direction !== 'latitudinal' && direction !== 'longitudinal' ) {
  16559. console.error( 'blur direction must be either latitudinal or longitudinal!' );
  16560. }
  16561. // Number of standard deviations at which to cut off the discrete approximation.
  16562. const STANDARD_DEVIATIONS = 3;
  16563. const blurMesh = this._lodMeshes[ lodOut ];
  16564. blurMesh.material = blurMaterial;
  16565. const blurUniforms = _uniformsMap.get( blurMaterial );
  16566. const pixels = this._sizeLods[ lodIn ] - 1;
  16567. const radiansPerPixel = isFinite( sigmaRadians ) ? Math.PI / ( 2 * pixels ) : 2 * Math.PI / ( 2 * MAX_SAMPLES - 1 );
  16568. const sigmaPixels = sigmaRadians / radiansPerPixel;
  16569. const samples = isFinite( sigmaRadians ) ? 1 + Math.floor( STANDARD_DEVIATIONS * sigmaPixels ) : MAX_SAMPLES;
  16570. if ( samples > MAX_SAMPLES ) {
  16571. console.warn( `sigmaRadians, ${
  16572. sigmaRadians}, is too large and will clip, as it requested ${
  16573. samples} samples when the maximum is set to ${MAX_SAMPLES}` );
  16574. }
  16575. const weights = [];
  16576. let sum = 0;
  16577. for ( let i = 0; i < MAX_SAMPLES; ++ i ) {
  16578. const x = i / sigmaPixels;
  16579. const weight = Math.exp( - x * x / 2 );
  16580. weights.push( weight );
  16581. if ( i === 0 ) {
  16582. sum += weight;
  16583. } else if ( i < samples ) {
  16584. sum += 2 * weight;
  16585. }
  16586. }
  16587. for ( let i = 0; i < weights.length; i ++ ) {
  16588. weights[ i ] = weights[ i ] / sum;
  16589. }
  16590. targetIn.texture.frame = ( targetIn.texture.frame || 0 ) + 1;
  16591. blurUniforms.envMap.value = targetIn.texture;
  16592. blurUniforms.samples.value = samples;
  16593. blurUniforms.weights.array = weights;
  16594. blurUniforms.latitudinal.value = direction === 'latitudinal' ? 1 : 0;
  16595. if ( poleAxis ) {
  16596. blurUniforms.poleAxis.value = poleAxis;
  16597. }
  16598. const { _lodMax } = this;
  16599. blurUniforms.dTheta.value = radiansPerPixel;
  16600. blurUniforms.mipInt.value = _lodMax - lodIn;
  16601. const outputSize = this._sizeLods[ lodOut ];
  16602. const x = 3 * outputSize * ( lodOut > _lodMax - LOD_MIN ? lodOut - _lodMax + LOD_MIN : 0 );
  16603. const y = 4 * ( this._cubeSize - outputSize );
  16604. _setViewport( targetOut, x, y, 3 * outputSize, 2 * outputSize );
  16605. renderer.setRenderTarget( targetOut );
  16606. renderer.render( blurMesh, _flatCamera );
  16607. }
  16608. }
  16609. function _createPlanes( lodMax ) {
  16610. const lodPlanes = [];
  16611. const sizeLods = [];
  16612. const sigmas = [];
  16613. const lodMeshes = [];
  16614. let lod = lodMax;
  16615. const totalLods = lodMax - LOD_MIN + 1 + EXTRA_LOD_SIGMA.length;
  16616. for ( let i = 0; i < totalLods; i ++ ) {
  16617. const sizeLod = Math.pow( 2, lod );
  16618. sizeLods.push( sizeLod );
  16619. let sigma = 1.0 / sizeLod;
  16620. if ( i > lodMax - LOD_MIN ) {
  16621. sigma = EXTRA_LOD_SIGMA[ i - lodMax + LOD_MIN - 1 ];
  16622. } else if ( i === 0 ) {
  16623. sigma = 0;
  16624. }
  16625. sigmas.push( sigma );
  16626. const texelSize = 1.0 / ( sizeLod - 2 );
  16627. const min = - texelSize;
  16628. const max = 1 + texelSize;
  16629. const uv1 = [ min, min, max, min, max, max, min, min, max, max, min, max ];
  16630. const cubeFaces = 6;
  16631. const vertices = 6;
  16632. const positionSize = 3;
  16633. const uvSize = 2;
  16634. const faceIndexSize = 1;
  16635. const position = new Float32Array( positionSize * vertices * cubeFaces );
  16636. const uv = new Float32Array( uvSize * vertices * cubeFaces );
  16637. const faceIndex = new Float32Array( faceIndexSize * vertices * cubeFaces );
  16638. for ( let face = 0; face < cubeFaces; face ++ ) {
  16639. const x = ( face % 3 ) * 2 / 3 - 1;
  16640. const y = face > 2 ? 0 : -1;
  16641. const coordinates = [
  16642. x, y, 0,
  16643. x + 2 / 3, y, 0,
  16644. x + 2 / 3, y + 1, 0,
  16645. x, y, 0,
  16646. x + 2 / 3, y + 1, 0,
  16647. x, y + 1, 0
  16648. ];
  16649. const faceIdx = _faceLib[ face ];
  16650. position.set( coordinates, positionSize * vertices * faceIdx );
  16651. uv.set( uv1, uvSize * vertices * faceIdx );
  16652. const fill = [ faceIdx, faceIdx, faceIdx, faceIdx, faceIdx, faceIdx ];
  16653. faceIndex.set( fill, faceIndexSize * vertices * faceIdx );
  16654. }
  16655. const planes = new BufferGeometry();
  16656. planes.setAttribute( 'position', new BufferAttribute( position, positionSize ) );
  16657. planes.setAttribute( 'uv', new BufferAttribute( uv, uvSize ) );
  16658. planes.setAttribute( 'faceIndex', new BufferAttribute( faceIndex, faceIndexSize ) );
  16659. lodPlanes.push( planes );
  16660. lodMeshes.push( new Mesh( planes, null ) );
  16661. if ( lod > LOD_MIN ) {
  16662. lod --;
  16663. }
  16664. }
  16665. return { lodPlanes, sizeLods, sigmas, lodMeshes };
  16666. }
  16667. function _createRenderTarget( width, height ) {
  16668. const params = {
  16669. magFilter: LinearFilter,
  16670. minFilter: LinearFilter,
  16671. generateMipmaps: false,
  16672. type: HalfFloatType,
  16673. format: RGBAFormat,
  16674. colorSpace: LinearSRGBColorSpace,
  16675. //depthBuffer: false
  16676. };
  16677. const cubeUVRenderTarget = new RenderTarget( width, height, params );
  16678. cubeUVRenderTarget.texture.mapping = CubeUVReflectionMapping;
  16679. cubeUVRenderTarget.texture.name = 'PMREM.cubeUv';
  16680. cubeUVRenderTarget.texture.isPMREMTexture = true;
  16681. cubeUVRenderTarget.scissorTest = true;
  16682. return cubeUVRenderTarget;
  16683. }
  16684. function _setViewport( target, x, y, width, height ) {
  16685. target.viewport.set( x, y, width, height );
  16686. target.scissor.set( x, y, width, height );
  16687. }
  16688. function _getMaterial( type ) {
  16689. const material = new NodeMaterial();
  16690. material.depthTest = false;
  16691. material.depthWrite = false;
  16692. material.blending = NoBlending;
  16693. material.name = `PMREM_${ type }`;
  16694. return material;
  16695. }
  16696. function _getBlurShader( lodMax, width, height ) {
  16697. const weights = uniformArray( new Array( MAX_SAMPLES ).fill( 0 ) );
  16698. const poleAxis = uniform( new Vector3( 0, 1, 0 ) );
  16699. const dTheta = uniform( 0 );
  16700. const n = float( MAX_SAMPLES );
  16701. const latitudinal = uniform( 0 ); // false, bool
  16702. const samples = uniform( 1 ); // int
  16703. const envMap = texture( null );
  16704. const mipInt = uniform( 0 ); // int
  16705. const CUBEUV_TEXEL_WIDTH = float( 1 / width );
  16706. const CUBEUV_TEXEL_HEIGHT = float( 1 / height );
  16707. const CUBEUV_MAX_MIP = float( lodMax );
  16708. const materialUniforms = {
  16709. n,
  16710. latitudinal,
  16711. weights,
  16712. poleAxis,
  16713. outputDirection: _outputDirection,
  16714. dTheta,
  16715. samples,
  16716. envMap,
  16717. mipInt,
  16718. CUBEUV_TEXEL_WIDTH,
  16719. CUBEUV_TEXEL_HEIGHT,
  16720. CUBEUV_MAX_MIP
  16721. };
  16722. const material = _getMaterial( 'blur' );
  16723. material.fragmentNode = blur( { ...materialUniforms, latitudinal: latitudinal.equal( 1 ) } );
  16724. _uniformsMap.set( material, materialUniforms );
  16725. return material;
  16726. }
  16727. function _getCubemapMaterial( envTexture ) {
  16728. const material = _getMaterial( 'cubemap' );
  16729. material.fragmentNode = cubeTexture( envTexture, _outputDirection );
  16730. return material;
  16731. }
  16732. function _getEquirectMaterial( envTexture ) {
  16733. const material = _getMaterial( 'equirect' );
  16734. material.fragmentNode = texture( envTexture, equirectUV( _outputDirection ), 0 );
  16735. return material;
  16736. }
  16737. const _cache = new WeakMap();
  16738. /**
  16739. * Generates the cubeUV size based on the given image height.
  16740. *
  16741. * @private
  16742. * @param {number} imageHeight - The image height.
  16743. * @return {{texelWidth: number,texelHeight: number, maxMip: number}} The result object.
  16744. */
  16745. function _generateCubeUVSize( imageHeight ) {
  16746. const maxMip = Math.log2( imageHeight ) - 2;
  16747. const texelHeight = 1.0 / imageHeight;
  16748. const texelWidth = 1.0 / ( 3 * Math.max( Math.pow( 2, maxMip ), 7 * 16 ) );
  16749. return { texelWidth, texelHeight, maxMip };
  16750. }
  16751. /**
  16752. * Generates a PMREM from the given texture.
  16753. *
  16754. * @private
  16755. * @param {Texture} texture - The texture to create the PMREM for.
  16756. * @param {Renderer} renderer - The renderer.
  16757. * @param {PMREMGenerator} generator - The PMREM generator.
  16758. * @return {?Texture} The PMREM.
  16759. */
  16760. function _getPMREMFromTexture( texture, renderer, generator ) {
  16761. const cache = _getCache( renderer );
  16762. let cacheTexture = cache.get( texture );
  16763. const pmremVersion = cacheTexture !== undefined ? cacheTexture.pmremVersion : -1;
  16764. if ( pmremVersion !== texture.pmremVersion ) {
  16765. const image = texture.image;
  16766. if ( texture.isCubeTexture ) {
  16767. if ( isCubeMapReady( image ) ) {
  16768. cacheTexture = generator.fromCubemap( texture, cacheTexture );
  16769. } else {
  16770. return null;
  16771. }
  16772. } else {
  16773. if ( isEquirectangularMapReady( image ) ) {
  16774. cacheTexture = generator.fromEquirectangular( texture, cacheTexture );
  16775. } else {
  16776. return null;
  16777. }
  16778. }
  16779. cacheTexture.pmremVersion = texture.pmremVersion;
  16780. cache.set( texture, cacheTexture );
  16781. }
  16782. return cacheTexture.texture;
  16783. }
  16784. /**
  16785. * Returns a cache that stores generated PMREMs for the respective textures.
  16786. * A cache must be maintained per renderer since PMREMs are render target textures
  16787. * which can't be shared across render contexts.
  16788. *
  16789. * @private
  16790. * @param {Renderer} renderer - The renderer.
  16791. * @return {WeakMap<Texture, Texture>} The PMREM cache.
  16792. */
  16793. function _getCache( renderer ) {
  16794. let rendererCache = _cache.get( renderer );
  16795. if ( rendererCache === undefined ) {
  16796. rendererCache = new WeakMap();
  16797. _cache.set( renderer, rendererCache );
  16798. }
  16799. return rendererCache;
  16800. }
  16801. /**
  16802. * This node represents a PMREM which is a special type of preprocessed
  16803. * environment map intended for PBR materials.
  16804. *
  16805. * ```js
  16806. * const material = new MeshStandardNodeMaterial();
  16807. * material.envNode = pmremTexture( envMap );
  16808. * ```
  16809. *
  16810. * @augments TempNode
  16811. */
  16812. class PMREMNode extends TempNode {
  16813. static get type() {
  16814. return 'PMREMNode';
  16815. }
  16816. /**
  16817. * Constructs a new function overloading node.
  16818. *
  16819. * @param {Texture} value - The input texture.
  16820. * @param {Node<vec2>} [uvNode=null] - The uv node.
  16821. * @param {Node<float>} [levelNode=null] - The level node.
  16822. */
  16823. constructor( value, uvNode = null, levelNode = null ) {
  16824. super( 'vec3' );
  16825. /**
  16826. * Reference to the input texture.
  16827. *
  16828. * @private
  16829. * @type {Texture}
  16830. */
  16831. this._value = value;
  16832. /**
  16833. * Reference to the generated PMREM.
  16834. *
  16835. * @private
  16836. * @type {Texture | null}
  16837. * @default null
  16838. */
  16839. this._pmrem = null;
  16840. /**
  16841. * The uv node.
  16842. *
  16843. * @type {Node<vec2>}
  16844. */
  16845. this.uvNode = uvNode;
  16846. /**
  16847. * The level node.
  16848. *
  16849. * @type {Node<float>}
  16850. */
  16851. this.levelNode = levelNode;
  16852. /**
  16853. * Reference to a PMREM generator.
  16854. *
  16855. * @private
  16856. * @type {?PMREMGenerator}
  16857. * @default null
  16858. */
  16859. this._generator = null;
  16860. const defaultTexture = new Texture();
  16861. defaultTexture.isRenderTargetTexture = true;
  16862. /**
  16863. * The texture node holding the generated PMREM.
  16864. *
  16865. * @private
  16866. * @type {TextureNode}
  16867. */
  16868. this._texture = texture( defaultTexture );
  16869. /**
  16870. * A uniform representing the PMREM's width.
  16871. *
  16872. * @private
  16873. * @type {UniformNode<float>}
  16874. */
  16875. this._width = uniform( 0 );
  16876. /**
  16877. * A uniform representing the PMREM's height.
  16878. *
  16879. * @private
  16880. * @type {UniformNode<float>}
  16881. */
  16882. this._height = uniform( 0 );
  16883. /**
  16884. * A uniform representing the PMREM's max Mip.
  16885. *
  16886. * @private
  16887. * @type {UniformNode<float>}
  16888. */
  16889. this._maxMip = uniform( 0 );
  16890. /**
  16891. * The `updateBeforeType` is set to `NodeUpdateType.RENDER`.
  16892. *
  16893. * @type {string}
  16894. * @default 'render'
  16895. */
  16896. this.updateBeforeType = NodeUpdateType.RENDER;
  16897. }
  16898. set value( value ) {
  16899. this._value = value;
  16900. this._pmrem = null;
  16901. }
  16902. /**
  16903. * The node's texture value.
  16904. *
  16905. * @type {Texture}
  16906. */
  16907. get value() {
  16908. return this._value;
  16909. }
  16910. /**
  16911. * Uses the given PMREM texture to update internal values.
  16912. *
  16913. * @param {Texture} texture - The PMREM texture.
  16914. */
  16915. updateFromTexture( texture ) {
  16916. const cubeUVSize = _generateCubeUVSize( texture.image.height );
  16917. this._texture.value = texture;
  16918. this._width.value = cubeUVSize.texelWidth;
  16919. this._height.value = cubeUVSize.texelHeight;
  16920. this._maxMip.value = cubeUVSize.maxMip;
  16921. }
  16922. updateBefore( frame ) {
  16923. let pmrem = this._pmrem;
  16924. const pmremVersion = pmrem ? pmrem.pmremVersion : -1;
  16925. const texture = this._value;
  16926. if ( pmremVersion !== texture.pmremVersion ) {
  16927. if ( texture.isPMREMTexture === true ) {
  16928. pmrem = texture;
  16929. } else {
  16930. pmrem = _getPMREMFromTexture( texture, frame.renderer, this._generator );
  16931. }
  16932. if ( pmrem !== null ) {
  16933. this._pmrem = pmrem;
  16934. this.updateFromTexture( pmrem );
  16935. }
  16936. }
  16937. }
  16938. setup( builder ) {
  16939. if ( this._generator === null ) {
  16940. this._generator = new PMREMGenerator( builder.renderer );
  16941. }
  16942. this.updateBefore( builder );
  16943. //
  16944. let uvNode = this.uvNode;
  16945. if ( uvNode === null && builder.context.getUV ) {
  16946. uvNode = builder.context.getUV( this );
  16947. }
  16948. //
  16949. uvNode = materialEnvRotation.mul( vec3( uvNode.x, uvNode.y.negate(), uvNode.z ) );
  16950. //
  16951. let levelNode = this.levelNode;
  16952. if ( levelNode === null && builder.context.getTextureLevel ) {
  16953. levelNode = builder.context.getTextureLevel( this );
  16954. }
  16955. //
  16956. return textureCubeUV( this._texture, uvNode, levelNode, this._width, this._height, this._maxMip );
  16957. }
  16958. dispose() {
  16959. super.dispose();
  16960. if ( this._generator !== null ) this._generator.dispose();
  16961. }
  16962. }
  16963. /**
  16964. * Returns `true` if the given cube map image has been fully loaded.
  16965. *
  16966. * @private
  16967. * @param {?Array<(Image|Object)>} [image] - The cube map image.
  16968. * @return {boolean} Whether the given cube map is ready or not.
  16969. */
  16970. function isCubeMapReady( image ) {
  16971. if ( image === null || image === undefined ) return false;
  16972. let count = 0;
  16973. const length = 6;
  16974. for ( let i = 0; i < length; i ++ ) {
  16975. if ( image[ i ] !== undefined ) count ++;
  16976. }
  16977. return count === length;
  16978. }
  16979. /**
  16980. * Returns `true` if the given equirectangular image has been fully loaded.
  16981. *
  16982. * @private
  16983. * @param {(Image|Object)} image - The equirectangular image.
  16984. * @return {boolean} Whether the given cube map is ready or not.
  16985. */
  16986. function isEquirectangularMapReady( image ) {
  16987. if ( image === null || image === undefined ) return false;
  16988. return image.height > 0;
  16989. }
  16990. /**
  16991. * TSL function for creating a PMREM node.
  16992. *
  16993. * @tsl
  16994. * @function
  16995. * @param {Texture} value - The input texture.
  16996. * @param {?Node<vec2>} [uvNode=null] - The uv node.
  16997. * @param {?Node<float>} [levelNode=null] - The level node.
  16998. * @returns {PMREMNode}
  16999. */
  17000. const pmremTexture = /*@__PURE__*/ nodeProxy( PMREMNode ).setParameterLength( 1, 3 );
  17001. const _envNodeCache = new WeakMap();
  17002. /**
  17003. * Represents a physical model for Image-based lighting (IBL). The environment
  17004. * is defined via environment maps in the equirectangular, cube map or cubeUV (PMREM) format.
  17005. * `EnvironmentNode` is intended for PBR materials like {@link MeshStandardNodeMaterial}.
  17006. *
  17007. * @augments LightingNode
  17008. */
  17009. class EnvironmentNode extends LightingNode {
  17010. static get type() {
  17011. return 'EnvironmentNode';
  17012. }
  17013. /**
  17014. * Constructs a new environment node.
  17015. *
  17016. * @param {Node} [envNode=null] - A node representing the environment.
  17017. */
  17018. constructor( envNode = null ) {
  17019. super();
  17020. /**
  17021. * A node representing the environment.
  17022. *
  17023. * @type {?Node}
  17024. * @default null
  17025. */
  17026. this.envNode = envNode;
  17027. }
  17028. setup( builder ) {
  17029. const { material } = builder;
  17030. let envNode = this.envNode;
  17031. if ( envNode.isTextureNode || envNode.isMaterialReferenceNode ) {
  17032. const value = ( envNode.isTextureNode ) ? envNode.value : material[ envNode.property ];
  17033. let cacheEnvNode = _envNodeCache.get( value );
  17034. if ( cacheEnvNode === undefined ) {
  17035. cacheEnvNode = pmremTexture( value );
  17036. _envNodeCache.set( value, cacheEnvNode );
  17037. }
  17038. envNode = cacheEnvNode;
  17039. }
  17040. //
  17041. const useAnisotropy = material.useAnisotropy === true || material.anisotropy > 0;
  17042. const radianceNormalView = useAnisotropy ? transformedBentNormalView : transformedNormalView;
  17043. const radiance = envNode.context( createRadianceContext( roughness, radianceNormalView ) ).mul( materialEnvIntensity );
  17044. const irradiance = envNode.context( createIrradianceContext( transformedNormalWorld ) ).mul( Math.PI ).mul( materialEnvIntensity );
  17045. const isolateRadiance = cache( radiance );
  17046. const isolateIrradiance = cache( irradiance );
  17047. //
  17048. builder.context.radiance.addAssign( isolateRadiance );
  17049. builder.context.iblIrradiance.addAssign( isolateIrradiance );
  17050. //
  17051. const clearcoatRadiance = builder.context.lightingModel.clearcoatRadiance;
  17052. if ( clearcoatRadiance ) {
  17053. const clearcoatRadianceContext = envNode.context( createRadianceContext( clearcoatRoughness, transformedClearcoatNormalView ) ).mul( materialEnvIntensity );
  17054. const isolateClearcoatRadiance = cache( clearcoatRadianceContext );
  17055. clearcoatRadiance.addAssign( isolateClearcoatRadiance );
  17056. }
  17057. }
  17058. }
  17059. const createRadianceContext = ( roughnessNode, normalViewNode ) => {
  17060. let reflectVec = null;
  17061. return {
  17062. getUV: () => {
  17063. if ( reflectVec === null ) {
  17064. reflectVec = positionViewDirection.negate().reflect( normalViewNode );
  17065. // Mixing the reflection with the normal is more accurate and keeps rough objects from gathering light from behind their tangent plane.
  17066. reflectVec = roughnessNode.mul( roughnessNode ).mix( reflectVec, normalViewNode ).normalize();
  17067. reflectVec = reflectVec.transformDirection( cameraViewMatrix );
  17068. }
  17069. return reflectVec;
  17070. },
  17071. getTextureLevel: () => {
  17072. return roughnessNode;
  17073. }
  17074. };
  17075. };
  17076. const createIrradianceContext = ( normalWorldNode ) => {
  17077. return {
  17078. getUV: () => {
  17079. return normalWorldNode;
  17080. },
  17081. getTextureLevel: () => {
  17082. return float( 1.0 );
  17083. }
  17084. };
  17085. };
  17086. const _defaultValues$6 = /*@__PURE__*/ new MeshStandardMaterial();
  17087. /**
  17088. * Node material version of {@link MeshStandardMaterial}.
  17089. *
  17090. * @augments NodeMaterial
  17091. */
  17092. class MeshStandardNodeMaterial extends NodeMaterial {
  17093. static get type() {
  17094. return 'MeshStandardNodeMaterial';
  17095. }
  17096. /**
  17097. * Constructs a new mesh standard node material.
  17098. *
  17099. * @param {Object} [parameters] - The configuration parameter.
  17100. */
  17101. constructor( parameters ) {
  17102. super();
  17103. /**
  17104. * This flag can be used for type testing.
  17105. *
  17106. * @type {boolean}
  17107. * @readonly
  17108. * @default true
  17109. */
  17110. this.isMeshStandardNodeMaterial = true;
  17111. /**
  17112. * Set to `true` because standard materials react on lights.
  17113. *
  17114. * @type {boolean}
  17115. * @default true
  17116. */
  17117. this.lights = true;
  17118. /**
  17119. * The emissive color of standard materials is by default inferred from the `emissive`,
  17120. * `emissiveIntensity` and `emissiveMap` properties. This node property allows to
  17121. * overwrite the default and define the emissive color with a node instead.
  17122. *
  17123. * If you don't want to overwrite the emissive color but modify the existing
  17124. * value instead, use {@link materialEmissive}.
  17125. *
  17126. * @type {?Node<vec3>}
  17127. * @default null
  17128. */
  17129. this.emissiveNode = null;
  17130. /**
  17131. * The metalness of standard materials is by default inferred from the `metalness`,
  17132. * and `metalnessMap` properties. This node property allows to
  17133. * overwrite the default and define the metalness with a node instead.
  17134. *
  17135. * If you don't want to overwrite the metalness but modify the existing
  17136. * value instead, use {@link materialMetalness}.
  17137. *
  17138. * @type {?Node<float>}
  17139. * @default null
  17140. */
  17141. this.metalnessNode = null;
  17142. /**
  17143. * The roughness of standard materials is by default inferred from the `roughness`,
  17144. * and `roughnessMap` properties. This node property allows to
  17145. * overwrite the default and define the roughness with a node instead.
  17146. *
  17147. * If you don't want to overwrite the roughness but modify the existing
  17148. * value instead, use {@link materialRoughness}.
  17149. *
  17150. * @type {?Node<float>}
  17151. * @default null
  17152. */
  17153. this.roughnessNode = null;
  17154. this.setDefaultValues( _defaultValues$6 );
  17155. this.setValues( parameters );
  17156. }
  17157. /**
  17158. * Overwritten since this type of material uses {@link EnvironmentNode}
  17159. * to implement the PBR (PMREM based) environment mapping. Besides, the
  17160. * method honors `Scene.environment`.
  17161. *
  17162. * @param {NodeBuilder} builder - The current node builder.
  17163. * @return {?EnvironmentNode<vec3>} The environment node.
  17164. */
  17165. setupEnvironment( builder ) {
  17166. let envNode = super.setupEnvironment( builder );
  17167. if ( envNode === null && builder.environmentNode ) {
  17168. envNode = builder.environmentNode;
  17169. }
  17170. return envNode ? new EnvironmentNode( envNode ) : null;
  17171. }
  17172. /**
  17173. * Setups the lighting model.
  17174. *
  17175. * @return {PhysicalLightingModel} The lighting model.
  17176. */
  17177. setupLightingModel( /*builder*/ ) {
  17178. return new PhysicalLightingModel();
  17179. }
  17180. /**
  17181. * Setups the specular related node variables.
  17182. */
  17183. setupSpecular() {
  17184. const specularColorNode = mix( vec3( 0.04 ), diffuseColor.rgb, metalness );
  17185. specularColor.assign( specularColorNode );
  17186. specularF90.assign( 1.0 );
  17187. }
  17188. /**
  17189. * Setups the standard specific node variables.
  17190. *
  17191. * @param {NodeBuilder} builder - The current node builder.
  17192. */
  17193. setupVariants() {
  17194. // METALNESS
  17195. const metalnessNode = this.metalnessNode ? float( this.metalnessNode ) : materialMetalness;
  17196. metalness.assign( metalnessNode );
  17197. // ROUGHNESS
  17198. let roughnessNode = this.roughnessNode ? float( this.roughnessNode ) : materialRoughness;
  17199. roughnessNode = getRoughness( { roughness: roughnessNode } );
  17200. roughness.assign( roughnessNode );
  17201. // SPECULAR COLOR
  17202. this.setupSpecular();
  17203. // DIFFUSE COLOR
  17204. diffuseColor.assign( vec4( diffuseColor.rgb.mul( metalnessNode.oneMinus() ), diffuseColor.a ) );
  17205. }
  17206. copy( source ) {
  17207. this.emissiveNode = source.emissiveNode;
  17208. this.metalnessNode = source.metalnessNode;
  17209. this.roughnessNode = source.roughnessNode;
  17210. return super.copy( source );
  17211. }
  17212. }
  17213. const _defaultValues$5 = /*@__PURE__*/ new MeshPhysicalMaterial();
  17214. /**
  17215. * Node material version of {@link MeshPhysicalMaterial}.
  17216. *
  17217. * @augments MeshStandardNodeMaterial
  17218. */
  17219. class MeshPhysicalNodeMaterial extends MeshStandardNodeMaterial {
  17220. static get type() {
  17221. return 'MeshPhysicalNodeMaterial';
  17222. }
  17223. /**
  17224. * Constructs a new mesh physical node material.
  17225. *
  17226. * @param {Object} [parameters] - The configuration parameter.
  17227. */
  17228. constructor( parameters ) {
  17229. super();
  17230. /**
  17231. * This flag can be used for type testing.
  17232. *
  17233. * @type {boolean}
  17234. * @readonly
  17235. * @default true
  17236. */
  17237. this.isMeshPhysicalNodeMaterial = true;
  17238. /**
  17239. * The clearcoat of physical materials is by default inferred from the `clearcoat`
  17240. * and `clearcoatMap` properties. This node property allows to overwrite the default
  17241. * and define the clearcoat with a node instead.
  17242. *
  17243. * If you don't want to overwrite the clearcoat but modify the existing
  17244. * value instead, use {@link materialClearcoat}.
  17245. *
  17246. * @type {?Node<float>}
  17247. * @default null
  17248. */
  17249. this.clearcoatNode = null;
  17250. /**
  17251. * The clearcoat roughness of physical materials is by default inferred from the `clearcoatRoughness`
  17252. * and `clearcoatRoughnessMap` properties. This node property allows to overwrite the default
  17253. * and define the clearcoat roughness with a node instead.
  17254. *
  17255. * If you don't want to overwrite the clearcoat roughness but modify the existing
  17256. * value instead, use {@link materialClearcoatRoughness}.
  17257. *
  17258. * @type {?Node<float>}
  17259. * @default null
  17260. */
  17261. this.clearcoatRoughnessNode = null;
  17262. /**
  17263. * The clearcoat normal of physical materials is by default inferred from the `clearcoatNormalMap`
  17264. * property. This node property allows to overwrite the default
  17265. * and define the clearcoat normal with a node instead.
  17266. *
  17267. * If you don't want to overwrite the clearcoat normal but modify the existing
  17268. * value instead, use {@link materialClearcoatNormal}.
  17269. *
  17270. * @type {?Node<vec3>}
  17271. * @default null
  17272. */
  17273. this.clearcoatNormalNode = null;
  17274. /**
  17275. * The sheen of physical materials is by default inferred from the `sheen`, `sheenColor`
  17276. * and `sheenColorMap` properties. This node property allows to overwrite the default
  17277. * and define the sheen with a node instead.
  17278. *
  17279. * If you don't want to overwrite the sheen but modify the existing
  17280. * value instead, use {@link materialSheen}.
  17281. *
  17282. * @type {?Node<vec3>}
  17283. * @default null
  17284. */
  17285. this.sheenNode = null;
  17286. /**
  17287. * The sheen roughness of physical materials is by default inferred from the `sheenRoughness` and
  17288. * `sheenRoughnessMap` properties. This node property allows to overwrite the default
  17289. * and define the sheen roughness with a node instead.
  17290. *
  17291. * If you don't want to overwrite the sheen roughness but modify the existing
  17292. * value instead, use {@link materialSheenRoughness}.
  17293. *
  17294. * @type {?Node<float>}
  17295. * @default null
  17296. */
  17297. this.sheenRoughnessNode = null;
  17298. /**
  17299. * The iridescence of physical materials is by default inferred from the `iridescence`
  17300. * property. This node property allows to overwrite the default
  17301. * and define the iridescence with a node instead.
  17302. *
  17303. * If you don't want to overwrite the iridescence but modify the existing
  17304. * value instead, use {@link materialIridescence}.
  17305. *
  17306. * @type {?Node<float>}
  17307. * @default null
  17308. */
  17309. this.iridescenceNode = null;
  17310. /**
  17311. * The iridescence IOR of physical materials is by default inferred from the `iridescenceIOR`
  17312. * property. This node property allows to overwrite the default
  17313. * and define the iridescence IOR with a node instead.
  17314. *
  17315. * If you don't want to overwrite the iridescence IOR but modify the existing
  17316. * value instead, use {@link materialIridescenceIOR}.
  17317. *
  17318. * @type {?Node<float>}
  17319. * @default null
  17320. */
  17321. this.iridescenceIORNode = null;
  17322. /**
  17323. * The iridescence thickness of physical materials is by default inferred from the `iridescenceThicknessRange`
  17324. * and `iridescenceThicknessMap` properties. This node property allows to overwrite the default
  17325. * and define the iridescence thickness with a node instead.
  17326. *
  17327. * If you don't want to overwrite the iridescence thickness but modify the existing
  17328. * value instead, use {@link materialIridescenceThickness}.
  17329. *
  17330. * @type {?Node<float>}
  17331. * @default null
  17332. */
  17333. this.iridescenceThicknessNode = null;
  17334. /**
  17335. * The specular intensity of physical materials is by default inferred from the `specularIntensity`
  17336. * and `specularIntensityMap` properties. This node property allows to overwrite the default
  17337. * and define the specular intensity with a node instead.
  17338. *
  17339. * If you don't want to overwrite the specular intensity but modify the existing
  17340. * value instead, use {@link materialSpecularIntensity}.
  17341. *
  17342. * @type {?Node<float>}
  17343. * @default null
  17344. */
  17345. this.specularIntensityNode = null;
  17346. /**
  17347. * The specular color of physical materials is by default inferred from the `specularColor`
  17348. * and `specularColorMap` properties. This node property allows to overwrite the default
  17349. * and define the specular color with a node instead.
  17350. *
  17351. * If you don't want to overwrite the specular color but modify the existing
  17352. * value instead, use {@link materialSpecularColor}.
  17353. *
  17354. * @type {?Node<vec3>}
  17355. * @default null
  17356. */
  17357. this.specularColorNode = null;
  17358. /**
  17359. * The ior of physical materials is by default inferred from the `ior`
  17360. * property. This node property allows to overwrite the default
  17361. * and define the ior with a node instead.
  17362. *
  17363. * If you don't want to overwrite the ior but modify the existing
  17364. * value instead, use {@link materialIOR}.
  17365. *
  17366. * @type {?Node<float>}
  17367. * @default null
  17368. */
  17369. this.iorNode = null;
  17370. /**
  17371. * The transmission of physical materials is by default inferred from the `transmission` and
  17372. * `transmissionMap` properties. This node property allows to overwrite the default
  17373. * and define the transmission with a node instead.
  17374. *
  17375. * If you don't want to overwrite the transmission but modify the existing
  17376. * value instead, use {@link materialTransmission}.
  17377. *
  17378. * @type {?Node<float>}
  17379. * @default null
  17380. */
  17381. this.transmissionNode = null;
  17382. /**
  17383. * The thickness of physical materials is by default inferred from the `thickness` and
  17384. * `thicknessMap` properties. This node property allows to overwrite the default
  17385. * and define the thickness with a node instead.
  17386. *
  17387. * If you don't want to overwrite the thickness but modify the existing
  17388. * value instead, use {@link materialThickness}.
  17389. *
  17390. * @type {?Node<float>}
  17391. * @default null
  17392. */
  17393. this.thicknessNode = null;
  17394. /**
  17395. * The attenuation distance of physical materials is by default inferred from the
  17396. * `attenuationDistance` property. This node property allows to overwrite the default
  17397. * and define the attenuation distance with a node instead.
  17398. *
  17399. * If you don't want to overwrite the attenuation distance but modify the existing
  17400. * value instead, use {@link materialAttenuationDistance}.
  17401. *
  17402. * @type {?Node<float>}
  17403. * @default null
  17404. */
  17405. this.attenuationDistanceNode = null;
  17406. /**
  17407. * The attenuation color of physical materials is by default inferred from the
  17408. * `attenuationColor` property. This node property allows to overwrite the default
  17409. * and define the attenuation color with a node instead.
  17410. *
  17411. * If you don't want to overwrite the attenuation color but modify the existing
  17412. * value instead, use {@link materialAttenuationColor}.
  17413. *
  17414. * @type {?Node<vec3>}
  17415. * @default null
  17416. */
  17417. this.attenuationColorNode = null;
  17418. /**
  17419. * The dispersion of physical materials is by default inferred from the
  17420. * `dispersion` property. This node property allows to overwrite the default
  17421. * and define the dispersion with a node instead.
  17422. *
  17423. * If you don't want to overwrite the dispersion but modify the existing
  17424. * value instead, use {@link materialDispersion}.
  17425. *
  17426. * @type {?Node<float>}
  17427. * @default null
  17428. */
  17429. this.dispersionNode = null;
  17430. /**
  17431. * The anisotropy of physical materials is by default inferred from the
  17432. * `anisotropy` property. This node property allows to overwrite the default
  17433. * and define the anisotropy with a node instead.
  17434. *
  17435. * If you don't want to overwrite the anisotropy but modify the existing
  17436. * value instead, use {@link materialAnisotropy}.
  17437. *
  17438. * @type {?Node<float>}
  17439. * @default null
  17440. */
  17441. this.anisotropyNode = null;
  17442. this.setDefaultValues( _defaultValues$5 );
  17443. this.setValues( parameters );
  17444. }
  17445. /**
  17446. * Whether the lighting model should use clearcoat or not.
  17447. *
  17448. * @type {boolean}
  17449. * @default true
  17450. */
  17451. get useClearcoat() {
  17452. return this.clearcoat > 0 || this.clearcoatNode !== null;
  17453. }
  17454. /**
  17455. * Whether the lighting model should use iridescence or not.
  17456. *
  17457. * @type {boolean}
  17458. * @default true
  17459. */
  17460. get useIridescence() {
  17461. return this.iridescence > 0 || this.iridescenceNode !== null;
  17462. }
  17463. /**
  17464. * Whether the lighting model should use sheen or not.
  17465. *
  17466. * @type {boolean}
  17467. * @default true
  17468. */
  17469. get useSheen() {
  17470. return this.sheen > 0 || this.sheenNode !== null;
  17471. }
  17472. /**
  17473. * Whether the lighting model should use anisotropy or not.
  17474. *
  17475. * @type {boolean}
  17476. * @default true
  17477. */
  17478. get useAnisotropy() {
  17479. return this.anisotropy > 0 || this.anisotropyNode !== null;
  17480. }
  17481. /**
  17482. * Whether the lighting model should use transmission or not.
  17483. *
  17484. * @type {boolean}
  17485. * @default true
  17486. */
  17487. get useTransmission() {
  17488. return this.transmission > 0 || this.transmissionNode !== null;
  17489. }
  17490. /**
  17491. * Whether the lighting model should use dispersion or not.
  17492. *
  17493. * @type {boolean}
  17494. * @default true
  17495. */
  17496. get useDispersion() {
  17497. return this.dispersion > 0 || this.dispersionNode !== null;
  17498. }
  17499. /**
  17500. * Setups the specular related node variables.
  17501. */
  17502. setupSpecular() {
  17503. const iorNode = this.iorNode ? float( this.iorNode ) : materialIOR;
  17504. ior.assign( iorNode );
  17505. 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 ) );
  17506. specularF90.assign( mix( materialSpecularIntensity, 1.0, metalness ) );
  17507. }
  17508. /**
  17509. * Setups the lighting model.
  17510. *
  17511. * @return {PhysicalLightingModel} The lighting model.
  17512. */
  17513. setupLightingModel( /*builder*/ ) {
  17514. return new PhysicalLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion );
  17515. }
  17516. /**
  17517. * Setups the physical specific node variables.
  17518. *
  17519. * @param {NodeBuilder} builder - The current node builder.
  17520. */
  17521. setupVariants( builder ) {
  17522. super.setupVariants( builder );
  17523. // CLEARCOAT
  17524. if ( this.useClearcoat ) {
  17525. const clearcoatNode = this.clearcoatNode ? float( this.clearcoatNode ) : materialClearcoat;
  17526. const clearcoatRoughnessNode = this.clearcoatRoughnessNode ? float( this.clearcoatRoughnessNode ) : materialClearcoatRoughness;
  17527. clearcoat.assign( clearcoatNode );
  17528. clearcoatRoughness.assign( getRoughness( { roughness: clearcoatRoughnessNode } ) );
  17529. }
  17530. // SHEEN
  17531. if ( this.useSheen ) {
  17532. const sheenNode = this.sheenNode ? vec3( this.sheenNode ) : materialSheen;
  17533. const sheenRoughnessNode = this.sheenRoughnessNode ? float( this.sheenRoughnessNode ) : materialSheenRoughness;
  17534. sheen.assign( sheenNode );
  17535. sheenRoughness.assign( sheenRoughnessNode );
  17536. }
  17537. // IRIDESCENCE
  17538. if ( this.useIridescence ) {
  17539. const iridescenceNode = this.iridescenceNode ? float( this.iridescenceNode ) : materialIridescence;
  17540. const iridescenceIORNode = this.iridescenceIORNode ? float( this.iridescenceIORNode ) : materialIridescenceIOR;
  17541. const iridescenceThicknessNode = this.iridescenceThicknessNode ? float( this.iridescenceThicknessNode ) : materialIridescenceThickness;
  17542. iridescence.assign( iridescenceNode );
  17543. iridescenceIOR.assign( iridescenceIORNode );
  17544. iridescenceThickness.assign( iridescenceThicknessNode );
  17545. }
  17546. // ANISOTROPY
  17547. if ( this.useAnisotropy ) {
  17548. const anisotropyV = ( this.anisotropyNode ? vec2( this.anisotropyNode ) : materialAnisotropy ).toVar();
  17549. anisotropy.assign( anisotropyV.length() );
  17550. If( anisotropy.equal( 0.0 ), () => {
  17551. anisotropyV.assign( vec2( 1.0, 0.0 ) );
  17552. } ).Else( () => {
  17553. anisotropyV.divAssign( vec2( anisotropy ) );
  17554. anisotropy.assign( anisotropy.saturate() );
  17555. } );
  17556. // Roughness along the anisotropy bitangent is the material roughness, while the tangent roughness increases with anisotropy.
  17557. alphaT.assign( anisotropy.pow2().mix( roughness.pow2(), 1.0 ) );
  17558. anisotropyT.assign( TBNViewMatrix[ 0 ].mul( anisotropyV.x ).add( TBNViewMatrix[ 1 ].mul( anisotropyV.y ) ) );
  17559. anisotropyB.assign( TBNViewMatrix[ 1 ].mul( anisotropyV.x ).sub( TBNViewMatrix[ 0 ].mul( anisotropyV.y ) ) );
  17560. }
  17561. // TRANSMISSION
  17562. if ( this.useTransmission ) {
  17563. const transmissionNode = this.transmissionNode ? float( this.transmissionNode ) : materialTransmission;
  17564. const thicknessNode = this.thicknessNode ? float( this.thicknessNode ) : materialThickness;
  17565. const attenuationDistanceNode = this.attenuationDistanceNode ? float( this.attenuationDistanceNode ) : materialAttenuationDistance;
  17566. const attenuationColorNode = this.attenuationColorNode ? vec3( this.attenuationColorNode ) : materialAttenuationColor;
  17567. transmission.assign( transmissionNode );
  17568. thickness.assign( thicknessNode );
  17569. attenuationDistance.assign( attenuationDistanceNode );
  17570. attenuationColor.assign( attenuationColorNode );
  17571. if ( this.useDispersion ) {
  17572. const dispersionNode = this.dispersionNode ? float( this.dispersionNode ) : materialDispersion;
  17573. dispersion.assign( dispersionNode );
  17574. }
  17575. }
  17576. }
  17577. /**
  17578. * Setups the clearcoat normal node.
  17579. *
  17580. * @return {Node<vec3>} The clearcoat normal.
  17581. */
  17582. setupClearcoatNormal() {
  17583. return this.clearcoatNormalNode ? vec3( this.clearcoatNormalNode ) : materialClearcoatNormal;
  17584. }
  17585. setup( builder ) {
  17586. builder.context.setupClearcoatNormal = () => this.setupClearcoatNormal( builder );
  17587. super.setup( builder );
  17588. }
  17589. copy( source ) {
  17590. this.clearcoatNode = source.clearcoatNode;
  17591. this.clearcoatRoughnessNode = source.clearcoatRoughnessNode;
  17592. this.clearcoatNormalNode = source.clearcoatNormalNode;
  17593. this.sheenNode = source.sheenNode;
  17594. this.sheenRoughnessNode = source.sheenRoughnessNode;
  17595. this.iridescenceNode = source.iridescenceNode;
  17596. this.iridescenceIORNode = source.iridescenceIORNode;
  17597. this.iridescenceThicknessNode = source.iridescenceThicknessNode;
  17598. this.specularIntensityNode = source.specularIntensityNode;
  17599. this.specularColorNode = source.specularColorNode;
  17600. this.transmissionNode = source.transmissionNode;
  17601. this.thicknessNode = source.thicknessNode;
  17602. this.attenuationDistanceNode = source.attenuationDistanceNode;
  17603. this.attenuationColorNode = source.attenuationColorNode;
  17604. this.dispersionNode = source.dispersionNode;
  17605. this.anisotropyNode = source.anisotropyNode;
  17606. return super.copy( source );
  17607. }
  17608. }
  17609. /**
  17610. * Represents the lighting model for {@link MeshSSSNodeMaterial}.
  17611. *
  17612. * @augments PhysicalLightingModel
  17613. */
  17614. class SSSLightingModel extends PhysicalLightingModel {
  17615. /**
  17616. * Constructs a new physical lighting model.
  17617. *
  17618. * @param {boolean} [clearcoat=false] - Whether clearcoat is supported or not.
  17619. * @param {boolean} [sheen=false] - Whether sheen is supported or not.
  17620. * @param {boolean} [iridescence=false] - Whether iridescence is supported or not.
  17621. * @param {boolean} [anisotropy=false] - Whether anisotropy is supported or not.
  17622. * @param {boolean} [transmission=false] - Whether transmission is supported or not.
  17623. * @param {boolean} [dispersion=false] - Whether dispersion is supported or not.
  17624. * @param {boolean} [sss=false] - Whether SSS is supported or not.
  17625. */
  17626. constructor( clearcoat = false, sheen = false, iridescence = false, anisotropy = false, transmission = false, dispersion = false, sss = false ) {
  17627. super( clearcoat, sheen, iridescence, anisotropy, transmission, dispersion );
  17628. /**
  17629. * Whether the lighting model should use SSS or not.
  17630. *
  17631. * @type {boolean}
  17632. * @default false
  17633. */
  17634. this.useSSS = sss;
  17635. }
  17636. /**
  17637. * Extends the default implementation with a SSS term.
  17638. *
  17639. * 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/}
  17640. *
  17641. * @param {Object} input - The input data.
  17642. * @param {NodeBuilder} builder - The current node builder.
  17643. */
  17644. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  17645. if ( this.useSSS === true ) {
  17646. const material = builder.material;
  17647. const { thicknessColorNode, thicknessDistortionNode, thicknessAmbientNode, thicknessAttenuationNode, thicknessPowerNode, thicknessScaleNode } = material;
  17648. const scatteringHalf = lightDirection.add( transformedNormalView.mul( thicknessDistortionNode ) ).normalize();
  17649. const scatteringDot = float( positionViewDirection.dot( scatteringHalf.negate() ).saturate().pow( thicknessPowerNode ).mul( thicknessScaleNode ) );
  17650. const scatteringIllu = vec3( scatteringDot.add( thicknessAmbientNode ).mul( thicknessColorNode ) );
  17651. reflectedLight.directDiffuse.addAssign( scatteringIllu.mul( thicknessAttenuationNode.mul( lightColor ) ) );
  17652. }
  17653. super.direct( { lightDirection, lightColor, reflectedLight }, builder );
  17654. }
  17655. }
  17656. /**
  17657. * This node material is an experimental extension of {@link MeshPhysicalNodeMaterial}
  17658. * that implements a Subsurface scattering (SSS) term.
  17659. *
  17660. * @augments MeshPhysicalNodeMaterial
  17661. */
  17662. class MeshSSSNodeMaterial extends MeshPhysicalNodeMaterial {
  17663. static get type() {
  17664. return 'MeshSSSNodeMaterial';
  17665. }
  17666. /**
  17667. * Constructs a new mesh SSS node material.
  17668. *
  17669. * @param {Object} [parameters] - The configuration parameter.
  17670. */
  17671. constructor( parameters ) {
  17672. super( parameters );
  17673. /**
  17674. * Represents the thickness color.
  17675. *
  17676. * @type {?Node<vec3>}
  17677. * @default null
  17678. */
  17679. this.thicknessColorNode = null;
  17680. /**
  17681. * Represents the distortion factor.
  17682. *
  17683. * @type {?Node<float>}
  17684. */
  17685. this.thicknessDistortionNode = float( 0.1 );
  17686. /**
  17687. * Represents the thickness ambient factor.
  17688. *
  17689. * @type {?Node<float>}
  17690. */
  17691. this.thicknessAmbientNode = float( 0.0 );
  17692. /**
  17693. * Represents the thickness attenuation.
  17694. *
  17695. * @type {?Node<float>}
  17696. */
  17697. this.thicknessAttenuationNode = float( .1 );
  17698. /**
  17699. * Represents the thickness power.
  17700. *
  17701. * @type {?Node<float>}
  17702. */
  17703. this.thicknessPowerNode = float( 2.0 );
  17704. /**
  17705. * Represents the thickness scale.
  17706. *
  17707. * @type {?Node<float>}
  17708. */
  17709. this.thicknessScaleNode = float( 10.0 );
  17710. }
  17711. /**
  17712. * Whether the lighting model should use SSS or not.
  17713. *
  17714. * @type {boolean}
  17715. * @default true
  17716. */
  17717. get useSSS() {
  17718. return this.thicknessColorNode !== null;
  17719. }
  17720. /**
  17721. * Setups the lighting model.
  17722. *
  17723. * @return {SSSLightingModel} The lighting model.
  17724. */
  17725. setupLightingModel( /*builder*/ ) {
  17726. return new SSSLightingModel( this.useClearcoat, this.useSheen, this.useIridescence, this.useAnisotropy, this.useTransmission, this.useDispersion, this.useSSS );
  17727. }
  17728. copy( source ) {
  17729. this.thicknessColorNode = source.thicknessColorNode;
  17730. this.thicknessDistortionNode = source.thicknessDistortionNode;
  17731. this.thicknessAmbientNode = source.thicknessAmbientNode;
  17732. this.thicknessAttenuationNode = source.thicknessAttenuationNode;
  17733. this.thicknessPowerNode = source.thicknessPowerNode;
  17734. this.thicknessScaleNode = source.thicknessScaleNode;
  17735. return super.copy( source );
  17736. }
  17737. }
  17738. const getGradientIrradiance = /*@__PURE__*/ Fn( ( { normal, lightDirection, builder } ) => {
  17739. // dotNL will be from -1.0 to 1.0
  17740. const dotNL = normal.dot( lightDirection );
  17741. const coord = vec2( dotNL.mul( 0.5 ).add( 0.5 ), 0.0 );
  17742. if ( builder.material.gradientMap ) {
  17743. const gradientMap = materialReference( 'gradientMap', 'texture' ).context( { getUV: () => coord } );
  17744. return vec3( gradientMap.r );
  17745. } else {
  17746. const fw = coord.fwidth().mul( 0.5 );
  17747. return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( float( 0.7 ).sub( fw.x ), float( 0.7 ).add( fw.x ), coord.x ) );
  17748. }
  17749. } );
  17750. /**
  17751. * Represents the lighting model for a toon material. Used in {@link MeshToonNodeMaterial}.
  17752. *
  17753. * @augments LightingModel
  17754. */
  17755. class ToonLightingModel extends LightingModel {
  17756. /**
  17757. * Implements the direct lighting. Instead of using a conventional smooth irradiance, the irradiance is
  17758. * reduced to a small number of discrete shades to create a comic-like, flat look.
  17759. *
  17760. * @param {Object} lightData - The light data.
  17761. * @param {NodeBuilder} builder - The current node builder.
  17762. */
  17763. direct( { lightDirection, lightColor, reflectedLight }, builder ) {
  17764. const irradiance = getGradientIrradiance( { normal: normalGeometry, lightDirection, builder } ).mul( lightColor );
  17765. reflectedLight.directDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor: diffuseColor.rgb } ) ) );
  17766. }
  17767. /**
  17768. * Implements the indirect lighting.
  17769. *
  17770. * @param {NodeBuilder} builder - The current node builder.
  17771. */
  17772. indirect( builder ) {
  17773. const { ambientOcclusion, irradiance, reflectedLight } = builder.context;
  17774. reflectedLight.indirectDiffuse.addAssign( irradiance.mul( BRDF_Lambert( { diffuseColor } ) ) );
  17775. reflectedLight.indirectDiffuse.mulAssign( ambientOcclusion );
  17776. }
  17777. }
  17778. const _defaultValues$4 = /*@__PURE__*/ new MeshToonMaterial();
  17779. /**
  17780. * Node material version of {@link MeshToonMaterial}.
  17781. *
  17782. * @augments NodeMaterial
  17783. */
  17784. class MeshToonNodeMaterial extends NodeMaterial {
  17785. static get type() {
  17786. return 'MeshToonNodeMaterial';
  17787. }
  17788. /**
  17789. * Constructs a new mesh toon node material.
  17790. *
  17791. * @param {Object} [parameters] - The configuration parameter.
  17792. */
  17793. constructor( parameters ) {
  17794. super();
  17795. /**
  17796. * This flag can be used for type testing.
  17797. *
  17798. * @type {boolean}
  17799. * @readonly
  17800. * @default true
  17801. */
  17802. this.isMeshToonNodeMaterial = true;
  17803. /**
  17804. * Set to `true` because toon materials react on lights.
  17805. *
  17806. * @type {boolean}
  17807. * @default true
  17808. */
  17809. this.lights = true;
  17810. this.setDefaultValues( _defaultValues$4 );
  17811. this.setValues( parameters );
  17812. }
  17813. /**
  17814. * Setups the lighting model.
  17815. *
  17816. * @return {ToonLightingModel} The lighting model.
  17817. */
  17818. setupLightingModel( /*builder*/ ) {
  17819. return new ToonLightingModel();
  17820. }
  17821. }
  17822. /**
  17823. * Can be used to compute texture coordinates for projecting a
  17824. * matcap onto a mesh. Used by {@link MeshMatcapNodeMaterial}.
  17825. *
  17826. * @augments TempNode
  17827. */
  17828. class MatcapUVNode extends TempNode {
  17829. static get type() {
  17830. return 'MatcapUVNode';
  17831. }
  17832. /**
  17833. * Constructs a new matcap uv node.
  17834. */
  17835. constructor() {
  17836. super( 'vec2' );
  17837. }
  17838. setup() {
  17839. const x = vec3( positionViewDirection.z, 0, positionViewDirection.x.negate() ).normalize();
  17840. const y = positionViewDirection.cross( x );
  17841. return vec2( x.dot( transformedNormalView ), y.dot( transformedNormalView ) ).mul( 0.495 ).add( 0.5 ); // 0.495 to remove artifacts caused by undersized matcap disks
  17842. }
  17843. }
  17844. /**
  17845. * TSL function for creating a matcap uv node.
  17846. *
  17847. * @tsl
  17848. * @function
  17849. * @returns {MatcapUVNode}
  17850. */
  17851. const matcapUV = /*@__PURE__*/ nodeImmutable( MatcapUVNode );
  17852. const _defaultValues$3 = /*@__PURE__*/ new MeshMatcapMaterial();
  17853. /**
  17854. * Node material version of {@link MeshMatcapMaterial}.
  17855. *
  17856. * @augments NodeMaterial
  17857. */
  17858. class MeshMatcapNodeMaterial extends NodeMaterial {
  17859. static get type() {
  17860. return 'MeshMatcapNodeMaterial';
  17861. }
  17862. /**
  17863. * Constructs a new mesh normal node material.
  17864. *
  17865. * @param {Object} [parameters] - The configuration parameter.
  17866. */
  17867. constructor( parameters ) {
  17868. super();
  17869. /**
  17870. * This flag can be used for type testing.
  17871. *
  17872. * @type {boolean}
  17873. * @readonly
  17874. * @default true
  17875. */
  17876. this.isMeshMatcapNodeMaterial = true;
  17877. this.setDefaultValues( _defaultValues$3 );
  17878. this.setValues( parameters );
  17879. }
  17880. /**
  17881. * Setups the matcap specific node variables.
  17882. *
  17883. * @param {NodeBuilder} builder - The current node builder.
  17884. */
  17885. setupVariants( builder ) {
  17886. const uv = matcapUV;
  17887. let matcapColor;
  17888. if ( builder.material.matcap ) {
  17889. matcapColor = materialReference( 'matcap', 'texture' ).context( { getUV: () => uv } );
  17890. } else {
  17891. matcapColor = vec3( mix( 0.2, 0.8, uv.y ) ); // default if matcap is missing
  17892. }
  17893. diffuseColor.rgb.mulAssign( matcapColor.rgb );
  17894. }
  17895. }
  17896. /**
  17897. * Applies a rotation to the given position node.
  17898. *
  17899. * @augments TempNode
  17900. */
  17901. class RotateNode extends TempNode {
  17902. static get type() {
  17903. return 'RotateNode';
  17904. }
  17905. /**
  17906. * Constructs a new rotate node.
  17907. *
  17908. * @param {Node} positionNode - The position node.
  17909. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  17910. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  17911. */
  17912. constructor( positionNode, rotationNode ) {
  17913. super();
  17914. /**
  17915. * The position node.
  17916. *
  17917. * @type {Node}
  17918. */
  17919. this.positionNode = positionNode;
  17920. /**
  17921. * Represents the rotation that is applied to the position node.
  17922. * Depending on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  17923. *
  17924. * @type {Node}
  17925. */
  17926. this.rotationNode = rotationNode;
  17927. }
  17928. /**
  17929. * The type of the {@link RotateNode#positionNode} defines the node's type.
  17930. *
  17931. * @param {NodeBuilder} builder - The current node builder.
  17932. * @return {string} The node's type.
  17933. */
  17934. getNodeType( builder ) {
  17935. return this.positionNode.getNodeType( builder );
  17936. }
  17937. setup( builder ) {
  17938. const { rotationNode, positionNode } = this;
  17939. const nodeType = this.getNodeType( builder );
  17940. if ( nodeType === 'vec2' ) {
  17941. const cosAngle = rotationNode.cos();
  17942. const sinAngle = rotationNode.sin();
  17943. const rotationMatrix = mat2(
  17944. cosAngle, sinAngle,
  17945. sinAngle.negate(), cosAngle
  17946. );
  17947. return rotationMatrix.mul( positionNode );
  17948. } else {
  17949. const rotation = rotationNode;
  17950. 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 ) );
  17951. 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 ) );
  17952. 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 ) );
  17953. return rotationXMatrix.mul( rotationYMatrix ).mul( rotationZMatrix ).mul( vec4( positionNode, 1.0 ) ).xyz;
  17954. }
  17955. }
  17956. }
  17957. /**
  17958. * TSL function for creating a rotate node.
  17959. *
  17960. * @tsl
  17961. * @function
  17962. * @param {Node} positionNode - The position node.
  17963. * @param {Node} rotationNode - Represents the rotation that is applied to the position node. Depending
  17964. * on whether the position data are 2D or 3D, the rotation is expressed a single float value or an Euler value.
  17965. * @returns {RotateNode}
  17966. */
  17967. const rotate = /*@__PURE__*/ nodeProxy( RotateNode ).setParameterLength( 2 );
  17968. const _defaultValues$2 = /*@__PURE__*/ new SpriteMaterial();
  17969. /**
  17970. * Node material version of {@link SpriteMaterial}.
  17971. *
  17972. * @augments NodeMaterial
  17973. */
  17974. class SpriteNodeMaterial extends NodeMaterial {
  17975. static get type() {
  17976. return 'SpriteNodeMaterial';
  17977. }
  17978. /**
  17979. * Constructs a new sprite node material.
  17980. *
  17981. * @param {Object} [parameters] - The configuration parameter.
  17982. */
  17983. constructor( parameters ) {
  17984. super();
  17985. /**
  17986. * This flag can be used for type testing.
  17987. *
  17988. * @type {boolean}
  17989. * @readonly
  17990. * @default true
  17991. */
  17992. this.isSpriteNodeMaterial = true;
  17993. this._useSizeAttenuation = true;
  17994. /**
  17995. * This property makes it possible to define the position of the sprite with a
  17996. * node. That can be useful when the material is used with instanced rendering
  17997. * and node data are defined with an instanced attribute node:
  17998. * ```js
  17999. * const positionAttribute = new InstancedBufferAttribute( new Float32Array( positions ), 3 );
  18000. * material.positionNode = instancedBufferAttribute( positionAttribute );
  18001. * ```
  18002. * Another possibility is to compute the instanced data with a compute shader:
  18003. * ```js
  18004. * const positionBuffer = instancedArray( particleCount, 'vec3' );
  18005. * particleMaterial.positionNode = positionBuffer.toAttribute();
  18006. * ```
  18007. *
  18008. * @type {?Node<vec2>}
  18009. * @default null
  18010. */
  18011. this.positionNode = null;
  18012. /**
  18013. * The rotation of sprite materials is by default inferred from the `rotation`,
  18014. * property. This node property allows to overwrite the default and define
  18015. * the rotation with a node instead.
  18016. *
  18017. * If you don't want to overwrite the rotation but modify the existing
  18018. * value instead, use {@link materialRotation}.
  18019. *
  18020. * @type {?Node<float>}
  18021. * @default null
  18022. */
  18023. this.rotationNode = null;
  18024. /**
  18025. * This node property provides an additional way to scale sprites next to
  18026. * `Object3D.scale`. The scale transformation based in `Object3D.scale`
  18027. * is multiplied with the scale value of this node in the vertex shader.
  18028. *
  18029. * @type {?Node<vec2>}
  18030. * @default null
  18031. */
  18032. this.scaleNode = null;
  18033. /**
  18034. * In Sprites, the transparent property is enabled by default.
  18035. *
  18036. * @type {boolean}
  18037. * @default true
  18038. */
  18039. this.transparent = true;
  18040. this.setDefaultValues( _defaultValues$2 );
  18041. this.setValues( parameters );
  18042. }
  18043. /**
  18044. * Setups the position node in view space. This method implements
  18045. * the sprite specific vertex shader.
  18046. *
  18047. * @param {NodeBuilder} builder - The current node builder.
  18048. * @return {Node<vec3>} The position in view space.
  18049. */
  18050. setupPositionView( builder ) {
  18051. const { object, camera } = builder;
  18052. const sizeAttenuation = this.sizeAttenuation;
  18053. const { positionNode, rotationNode, scaleNode } = this;
  18054. const mvPosition = modelViewMatrix.mul( vec3( positionNode || 0 ) );
  18055. let scale = vec2( modelWorldMatrix[ 0 ].xyz.length(), modelWorldMatrix[ 1 ].xyz.length() );
  18056. if ( scaleNode !== null ) {
  18057. scale = scale.mul( vec2( scaleNode ) );
  18058. }
  18059. if ( sizeAttenuation === false ) {
  18060. if ( camera.isPerspectiveCamera ) {
  18061. scale = scale.mul( mvPosition.z.negate() );
  18062. } else {
  18063. const orthoScale = float( 2.0 ).div( cameraProjectionMatrix.element( 1 ).element( 1 ) );
  18064. scale = scale.mul( orthoScale.mul( 2 ) );
  18065. }
  18066. }
  18067. let alignedPosition = positionGeometry.xy;
  18068. if ( object.center && object.center.isVector2 === true ) {
  18069. const center = reference$1( 'center', 'vec2', object );
  18070. alignedPosition = alignedPosition.sub( center.sub( 0.5 ) );
  18071. }
  18072. alignedPosition = alignedPosition.mul( scale );
  18073. const rotation = float( rotationNode || materialRotation );
  18074. const rotatedPosition = rotate( alignedPosition, rotation );
  18075. return vec4( mvPosition.xy.add( rotatedPosition ), mvPosition.zw );
  18076. }
  18077. copy( source ) {
  18078. this.positionNode = source.positionNode;
  18079. this.rotationNode = source.rotationNode;
  18080. this.scaleNode = source.scaleNode;
  18081. return super.copy( source );
  18082. }
  18083. /**
  18084. * Whether to use size attenuation or not.
  18085. *
  18086. * @type {boolean}
  18087. * @default true
  18088. */
  18089. get sizeAttenuation() {
  18090. return this._useSizeAttenuation;
  18091. }
  18092. set sizeAttenuation( value ) {
  18093. if ( this._useSizeAttenuation !== value ) {
  18094. this._useSizeAttenuation = value;
  18095. this.needsUpdate = true;
  18096. }
  18097. }
  18098. }
  18099. const _defaultValues$1 = /*@__PURE__*/ new PointsMaterial();
  18100. /**
  18101. * Node material version of {@link PointsMaterial}.
  18102. *
  18103. * @augments SpriteNodeMaterial
  18104. */
  18105. class PointsNodeMaterial extends SpriteNodeMaterial {
  18106. static get type() {
  18107. return 'PointsNodeMaterial';
  18108. }
  18109. /**
  18110. * Constructs a new points node material.
  18111. *
  18112. * @param {Object} [parameters] - The configuration parameter.
  18113. */
  18114. constructor( parameters ) {
  18115. super();
  18116. /**
  18117. * This node property provides an additional way to set the point size.
  18118. *
  18119. * @type {?Node<vec2>}
  18120. * @default null
  18121. */
  18122. this.sizeNode = null;
  18123. /**
  18124. * This flag can be used for type testing.
  18125. *
  18126. * @type {boolean}
  18127. * @readonly
  18128. * @default true
  18129. */
  18130. this.isPointsNodeMaterial = true;
  18131. this.setDefaultValues( _defaultValues$1 );
  18132. this.setValues( parameters );
  18133. }
  18134. setupPositionView() {
  18135. const { positionNode } = this;
  18136. return modelViewMatrix.mul( vec3( positionNode || positionLocal ) ).xyz;
  18137. }
  18138. setupVertex( builder ) {
  18139. const mvp = super.setupVertex( builder );
  18140. // skip further processing if the material is not a node material
  18141. if ( builder.material.isNodeMaterial !== true ) {
  18142. return mvp;
  18143. }
  18144. // ndc space
  18145. const { rotationNode, scaleNode, sizeNode } = this;
  18146. const alignedPosition = positionGeometry.xy.toVar();
  18147. const aspect = viewport.z.div( viewport.w );
  18148. // rotation
  18149. if ( rotationNode && rotationNode.isNode ) {
  18150. const rotation = float( rotationNode );
  18151. alignedPosition.assign( rotate( alignedPosition, rotation ) );
  18152. }
  18153. // point size
  18154. let pointSize = sizeNode !== null ? vec2( sizeNode ) : materialPointSize;
  18155. if ( this.sizeAttenuation === true ) {
  18156. pointSize = pointSize.mul( pointSize.div( positionView.z.negate() ) );
  18157. }
  18158. // scale
  18159. if ( scaleNode && scaleNode.isNode ) {
  18160. pointSize = pointSize.mul( vec2( scaleNode ) );
  18161. }
  18162. alignedPosition.mulAssign( pointSize.mul( 2 ) );
  18163. alignedPosition.assign( alignedPosition.div( viewport.z ) );
  18164. alignedPosition.y.assign( alignedPosition.y.mul( aspect ) );
  18165. // back to clip space
  18166. alignedPosition.assign( alignedPosition.mul( mvp.w ) );
  18167. //clipPos.xy += offset;
  18168. mvp.addAssign( vec4( alignedPosition, 0, 0 ) );
  18169. return mvp;
  18170. }
  18171. /**
  18172. * Whether alpha to coverage should be used or not.
  18173. *
  18174. * @type {boolean}
  18175. * @default true
  18176. */
  18177. get alphaToCoverage() {
  18178. return this._useAlphaToCoverage;
  18179. }
  18180. set alphaToCoverage( value ) {
  18181. if ( this._useAlphaToCoverage !== value ) {
  18182. this._useAlphaToCoverage = value;
  18183. this.needsUpdate = true;
  18184. }
  18185. }
  18186. }
  18187. /**
  18188. * Represents lighting model for a shadow material. Used in {@link ShadowNodeMaterial}.
  18189. *
  18190. * @augments LightingModel
  18191. */
  18192. class ShadowMaskModel extends LightingModel {
  18193. /**
  18194. * Constructs a new shadow mask model.
  18195. */
  18196. constructor() {
  18197. super();
  18198. /**
  18199. * The shadow mask node.
  18200. *
  18201. * @type {Node}
  18202. */
  18203. this.shadowNode = float( 1 ).toVar( 'shadowMask' );
  18204. }
  18205. /**
  18206. * Only used to save the shadow mask.
  18207. *
  18208. * @param {Object} input - The input data.
  18209. */
  18210. direct( { lightNode } ) {
  18211. if ( lightNode.shadowNode !== null ) {
  18212. this.shadowNode.mulAssign( lightNode.shadowNode );
  18213. }
  18214. }
  18215. /**
  18216. * Uses the shadow mask to produce the final color.
  18217. *
  18218. * @param {NodeBuilder} builder - The current node builder.
  18219. */
  18220. finish( { context } ) {
  18221. diffuseColor.a.mulAssign( this.shadowNode.oneMinus() );
  18222. context.outgoingLight.rgb.assign( diffuseColor.rgb ); // TODO: Optimize LightsNode to avoid this assignment
  18223. }
  18224. }
  18225. const _defaultValues = /*@__PURE__*/ new ShadowMaterial();
  18226. /**
  18227. * Node material version of {@link ShadowMaterial}.
  18228. *
  18229. * @augments NodeMaterial
  18230. */
  18231. class ShadowNodeMaterial extends NodeMaterial {
  18232. static get type() {
  18233. return 'ShadowNodeMaterial';
  18234. }
  18235. /**
  18236. * Constructs a new shadow node material.
  18237. *
  18238. * @param {Object} [parameters] - The configuration parameter.
  18239. */
  18240. constructor( parameters ) {
  18241. super();
  18242. /**
  18243. * This flag can be used for type testing.
  18244. *
  18245. * @type {boolean}
  18246. * @readonly
  18247. * @default true
  18248. */
  18249. this.isShadowNodeMaterial = true;
  18250. /**
  18251. * Set to `true` because so it's possible to implement
  18252. * the shadow mask effect.
  18253. *
  18254. * @type {boolean}
  18255. * @default true
  18256. */
  18257. this.lights = true;
  18258. /**
  18259. * Overwritten since shadow materials are transparent
  18260. * by default.
  18261. *
  18262. * @type {boolean}
  18263. * @default true
  18264. */
  18265. this.transparent = true;
  18266. this.setDefaultValues( _defaultValues );
  18267. this.setValues( parameters );
  18268. }
  18269. /**
  18270. * Setups the lighting model.
  18271. *
  18272. * @return {ShadowMaskModel} The lighting model.
  18273. */
  18274. setupLightingModel( /*builder*/ ) {
  18275. return new ShadowMaskModel();
  18276. }
  18277. }
  18278. const scatteringDensity = property( 'vec3' );
  18279. const linearDepthRay = property( 'vec3' );
  18280. const outgoingRayLight = property( 'vec3' );
  18281. /**
  18282. * VolumetricLightingModel class extends the LightingModel to implement volumetric lighting effects.
  18283. * This model calculates the scattering and transmittance of light through a volumetric medium.
  18284. * It dynamically adjusts the direction of the ray based on the camera and object positions.
  18285. * The model supports custom scattering and depth nodes to enhance the lighting effects.
  18286. *
  18287. * @augments LightingModel
  18288. */
  18289. class VolumetricLightingModel extends LightingModel {
  18290. constructor() {
  18291. super();
  18292. }
  18293. start( builder ) {
  18294. const { material, context } = builder;
  18295. const startPos = property( 'vec3' );
  18296. const endPos = property( 'vec3' );
  18297. // This approach dynamically changes the direction of the ray,
  18298. // 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.
  18299. If( cameraPosition.sub( positionWorld ).length().greaterThan( modelRadius.mul( 2 ) ), () => {
  18300. startPos.assign( cameraPosition );
  18301. endPos.assign( positionWorld );
  18302. } ).Else( () => {
  18303. startPos.assign( positionWorld );
  18304. endPos.assign( cameraPosition );
  18305. } );
  18306. //
  18307. const viewVector = endPos.sub( startPos );
  18308. const steps = uniform( 'int' ).onRenderUpdate( ( { material } ) => material.steps );
  18309. const stepSize = viewVector.length().div( steps ).toVar();
  18310. const rayDir = viewVector.normalize().toVar(); // TODO: toVar() should be automatic here ( in loop )
  18311. const distTravelled = float( 0.0 ).toVar();
  18312. const transmittance = vec3( 1 ).toVar();
  18313. if ( material.offsetNode ) {
  18314. // reduce banding
  18315. distTravelled.addAssign( material.offsetNode.mul( stepSize ) );
  18316. }
  18317. Loop( steps, () => {
  18318. const positionRay = startPos.add( rayDir.mul( distTravelled ) );
  18319. const positionViewRay = cameraViewMatrix.mul( vec4( positionRay, 1 ) ).xyz;
  18320. if ( material.depthNode !== null ) {
  18321. linearDepthRay.assign( linearDepth( viewZToPerspectiveDepth( positionViewRay.z, cameraNear, cameraFar ) ) );
  18322. context.sceneDepthNode = linearDepth( material.depthNode ).toVar();
  18323. }
  18324. context.positionWorld = positionRay;
  18325. context.shadowPositionWorld = positionRay;
  18326. context.positionView = positionViewRay;
  18327. scatteringDensity.assign( 0 );
  18328. let scatteringNode;
  18329. if ( material.scatteringNode ) {
  18330. scatteringNode = material.scatteringNode( {
  18331. positionRay
  18332. } );
  18333. }
  18334. super.start( builder );
  18335. if ( scatteringNode ) {
  18336. scatteringDensity.mulAssign( scatteringNode );
  18337. }
  18338. // beer's law
  18339. const falloff = scatteringDensity.mul( .01 ).negate().mul( stepSize ).exp();
  18340. transmittance.mulAssign( falloff );
  18341. // move along the ray
  18342. distTravelled.addAssign( stepSize );
  18343. } );
  18344. outgoingRayLight.addAssign( transmittance.saturate().oneMinus() );
  18345. }
  18346. scatteringLight( lightColor, builder ) {
  18347. const sceneDepthNode = builder.context.sceneDepthNode;
  18348. if ( sceneDepthNode ) {
  18349. If( sceneDepthNode.greaterThanEqual( linearDepthRay ), () => {
  18350. scatteringDensity.addAssign( lightColor );
  18351. } );
  18352. } else {
  18353. scatteringDensity.addAssign( lightColor );
  18354. }
  18355. }
  18356. direct( { lightNode, lightColor }, builder ) {
  18357. // Ignore lights with infinite distance
  18358. if ( lightNode.light.distance === undefined ) return;
  18359. // TODO: We need a viewportOpaque*() ( output, depth ) to fit with modern rendering approaches
  18360. const directLight = lightColor.xyz.toVar();
  18361. directLight.mulAssign( lightNode.shadowNode ); // it no should be necessary if used in the same render pass
  18362. this.scatteringLight( directLight, builder );
  18363. }
  18364. directRectArea( { lightColor, lightPosition, halfWidth, halfHeight }, builder ) {
  18365. const p0 = lightPosition.add( halfWidth ).sub( halfHeight ); // counterclockwise; light shines in local neg z direction
  18366. const p1 = lightPosition.sub( halfWidth ).sub( halfHeight );
  18367. const p2 = lightPosition.sub( halfWidth ).add( halfHeight );
  18368. const p3 = lightPosition.add( halfWidth ).add( halfHeight );
  18369. const P = builder.context.positionView;
  18370. const directLight = lightColor.xyz.mul( LTC_Evaluate_Volume( { P, p0, p1, p2, p3 } ) ).pow( 1.5 );
  18371. this.scatteringLight( directLight, builder );
  18372. }
  18373. finish( builder ) {
  18374. builder.context.outgoingLight.assign( outgoingRayLight );
  18375. }
  18376. }
  18377. /**
  18378. * Volume node material.
  18379. *
  18380. * @augments NodeMaterial
  18381. */
  18382. class VolumeNodeMaterial extends NodeMaterial {
  18383. static get type() {
  18384. return 'VolumeNodeMaterial';
  18385. }
  18386. /**
  18387. * Constructs a new volume node material.
  18388. *
  18389. * @param {Object} [parameters] - The configuration parameter.
  18390. */
  18391. constructor( parameters ) {
  18392. super();
  18393. /**
  18394. * This flag can be used for type testing.
  18395. *
  18396. * @type {boolean}
  18397. * @readonly
  18398. * @default true
  18399. */
  18400. this.isVolumeNodeMaterial = true;
  18401. /**
  18402. * Number of steps used for raymarching.
  18403. *
  18404. * @type {number}
  18405. * @default 25
  18406. */
  18407. this.steps = 25;
  18408. /**
  18409. * Offsets the distance a ray has been traveled through a volume.
  18410. * Can be used to implement dithering to reduce banding.
  18411. *
  18412. * @type {Node<float>}
  18413. * @default null
  18414. */
  18415. this.offsetNode = null;
  18416. /**
  18417. * Node used for scattering calculations.
  18418. *
  18419. * @type {Function|FunctionNode<vec4>}
  18420. * @default null
  18421. */
  18422. this.scatteringNode = null;
  18423. this.lights = true;
  18424. this.transparent = true;
  18425. this.side = BackSide;
  18426. this.depthTest = false;
  18427. this.depthWrite = false;
  18428. this.setValues( parameters );
  18429. }
  18430. setupLightingModel() {
  18431. return new VolumetricLightingModel();
  18432. }
  18433. }
  18434. /**
  18435. * This module manages the internal animation loop of the renderer.
  18436. *
  18437. * @private
  18438. */
  18439. class Animation {
  18440. /**
  18441. * Constructs a new animation loop management component.
  18442. *
  18443. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18444. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  18445. */
  18446. constructor( nodes, info ) {
  18447. /**
  18448. * Renderer component for managing nodes related logic.
  18449. *
  18450. * @type {Nodes}
  18451. */
  18452. this.nodes = nodes;
  18453. /**
  18454. * Renderer component for managing metrics and monitoring data.
  18455. *
  18456. * @type {Info}
  18457. */
  18458. this.info = info;
  18459. /**
  18460. * A reference to the context from `requestAnimationFrame()` can
  18461. * be called (usually `window`).
  18462. *
  18463. * @type {?(Window|XRSession)}
  18464. */
  18465. this._context = typeof self !== 'undefined' ? self : null;
  18466. /**
  18467. * The user-defined animation loop.
  18468. *
  18469. * @type {?Function}
  18470. * @default null
  18471. */
  18472. this._animationLoop = null;
  18473. /**
  18474. * The requestId which is returned from the `requestAnimationFrame()` call.
  18475. * Can be used to cancel the stop the animation loop.
  18476. *
  18477. * @type {?number}
  18478. * @default null
  18479. */
  18480. this._requestId = null;
  18481. }
  18482. /**
  18483. * Starts the internal animation loop.
  18484. */
  18485. start() {
  18486. const update = ( time, xrFrame ) => {
  18487. this._requestId = this._context.requestAnimationFrame( update );
  18488. if ( this.info.autoReset === true ) this.info.reset();
  18489. this.nodes.nodeFrame.update();
  18490. this.info.frame = this.nodes.nodeFrame.frameId;
  18491. if ( this._animationLoop !== null ) this._animationLoop( time, xrFrame );
  18492. };
  18493. update();
  18494. }
  18495. /**
  18496. * Stops the internal animation loop.
  18497. */
  18498. stop() {
  18499. this._context.cancelAnimationFrame( this._requestId );
  18500. this._requestId = null;
  18501. }
  18502. /**
  18503. * Returns the user-level animation loop.
  18504. *
  18505. * @return {?Function} The animation loop.
  18506. */
  18507. getAnimationLoop() {
  18508. return this._animationLoop;
  18509. }
  18510. /**
  18511. * Defines the user-level animation loop.
  18512. *
  18513. * @param {?Function} callback - The animation loop.
  18514. */
  18515. setAnimationLoop( callback ) {
  18516. this._animationLoop = callback;
  18517. }
  18518. /**
  18519. * Returns the animation context.
  18520. *
  18521. * @return {Window|XRSession} The animation context.
  18522. */
  18523. getContext() {
  18524. return this._context;
  18525. }
  18526. /**
  18527. * Defines the context in which `requestAnimationFrame()` is executed.
  18528. *
  18529. * @param {Window|XRSession} context - The context to set.
  18530. */
  18531. setContext( context ) {
  18532. this._context = context;
  18533. }
  18534. /**
  18535. * Frees all internal resources and stops the animation loop.
  18536. */
  18537. dispose() {
  18538. this.stop();
  18539. }
  18540. }
  18541. /**
  18542. * Data structure for the renderer. It allows defining values
  18543. * with chained, hierarchical keys. Keys are meant to be
  18544. * objects since the module internally works with Weak Maps
  18545. * for performance reasons.
  18546. *
  18547. * @private
  18548. */
  18549. class ChainMap {
  18550. /**
  18551. * Constructs a new Chain Map.
  18552. */
  18553. constructor() {
  18554. /**
  18555. * The root Weak Map.
  18556. *
  18557. * @type {WeakMap}
  18558. */
  18559. this.weakMap = new WeakMap();
  18560. }
  18561. /**
  18562. * Returns the value for the given array of keys.
  18563. *
  18564. * @param {Array<Object>} keys - List of keys.
  18565. * @return {any} The value. Returns `undefined` if no value was found.
  18566. */
  18567. get( keys ) {
  18568. let map = this.weakMap;
  18569. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18570. map = map.get( keys[ i ] );
  18571. if ( map === undefined ) return undefined;
  18572. }
  18573. return map.get( keys[ keys.length - 1 ] );
  18574. }
  18575. /**
  18576. * Sets the value for the given keys.
  18577. *
  18578. * @param {Array<Object>} keys - List of keys.
  18579. * @param {any} value - The value to set.
  18580. * @return {ChainMap} A reference to this Chain Map.
  18581. */
  18582. set( keys, value ) {
  18583. let map = this.weakMap;
  18584. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18585. const key = keys[ i ];
  18586. if ( map.has( key ) === false ) map.set( key, new WeakMap() );
  18587. map = map.get( key );
  18588. }
  18589. map.set( keys[ keys.length - 1 ], value );
  18590. return this;
  18591. }
  18592. /**
  18593. * Deletes a value for the given keys.
  18594. *
  18595. * @param {Array<Object>} keys - The keys.
  18596. * @return {boolean} Returns `true` if the value has been removed successfully and `false` if the value has not be found.
  18597. */
  18598. delete( keys ) {
  18599. let map = this.weakMap;
  18600. for ( let i = 0; i < keys.length - 1; i ++ ) {
  18601. map = map.get( keys[ i ] );
  18602. if ( map === undefined ) return false;
  18603. }
  18604. return map.delete( keys[ keys.length - 1 ] );
  18605. }
  18606. }
  18607. let _id$9 = 0;
  18608. function getKeys( obj ) {
  18609. const keys = Object.keys( obj );
  18610. let proto = Object.getPrototypeOf( obj );
  18611. while ( proto ) {
  18612. const descriptors = Object.getOwnPropertyDescriptors( proto );
  18613. for ( const key in descriptors ) {
  18614. if ( descriptors[ key ] !== undefined ) {
  18615. const descriptor = descriptors[ key ];
  18616. if ( descriptor && typeof descriptor.get === 'function' ) {
  18617. keys.push( key );
  18618. }
  18619. }
  18620. }
  18621. proto = Object.getPrototypeOf( proto );
  18622. }
  18623. return keys;
  18624. }
  18625. /**
  18626. * A render object is the renderer's representation of single entity that gets drawn
  18627. * with a draw command. There is no unique mapping of render objects to 3D objects in the
  18628. * scene since render objects also depend from the used material, the current render context
  18629. * and the current scene's lighting.
  18630. *
  18631. * In general, the basic process of the renderer is:
  18632. *
  18633. * - Analyze the 3D objects in the scene and generate render lists containing render items.
  18634. * - Process the render lists by calling one or more render commands for each render item.
  18635. * - For each render command, request a render object and perform the draw.
  18636. *
  18637. * The module provides an interface to get data required for the draw command like the actual
  18638. * draw parameters or vertex buffers. It also holds a series of caching related methods since
  18639. * creating render objects should only be done when necessary.
  18640. *
  18641. * @private
  18642. */
  18643. class RenderObject {
  18644. /**
  18645. * Constructs a new render object.
  18646. *
  18647. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  18648. * @param {Geometries} geometries - Renderer component for managing geometries.
  18649. * @param {Renderer} renderer - The renderer.
  18650. * @param {Object3D} object - The 3D object.
  18651. * @param {Material} material - The 3D object's material.
  18652. * @param {Scene} scene - The scene the 3D object belongs to.
  18653. * @param {Camera} camera - The camera the object should be rendered with.
  18654. * @param {LightsNode} lightsNode - The lights node.
  18655. * @param {RenderContext} renderContext - The render context.
  18656. * @param {ClippingContext} clippingContext - The clipping context.
  18657. */
  18658. constructor( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext ) {
  18659. this.id = _id$9 ++;
  18660. /**
  18661. * Renderer component for managing nodes related logic.
  18662. *
  18663. * @type {Nodes}
  18664. * @private
  18665. */
  18666. this._nodes = nodes;
  18667. /**
  18668. * Renderer component for managing geometries.
  18669. *
  18670. * @type {Geometries}
  18671. * @private
  18672. */
  18673. this._geometries = geometries;
  18674. /**
  18675. * The renderer.
  18676. *
  18677. * @type {Renderer}
  18678. */
  18679. this.renderer = renderer;
  18680. /**
  18681. * The 3D object.
  18682. *
  18683. * @type {Object3D}
  18684. */
  18685. this.object = object;
  18686. /**
  18687. * The 3D object's material.
  18688. *
  18689. * @type {Material}
  18690. */
  18691. this.material = material;
  18692. /**
  18693. * The scene the 3D object belongs to.
  18694. *
  18695. * @type {Scene}
  18696. */
  18697. this.scene = scene;
  18698. /**
  18699. * The camera the 3D object should be rendered with.
  18700. *
  18701. * @type {Camera}
  18702. */
  18703. this.camera = camera;
  18704. /**
  18705. * The lights node.
  18706. *
  18707. * @type {LightsNode}
  18708. */
  18709. this.lightsNode = lightsNode;
  18710. /**
  18711. * The render context.
  18712. *
  18713. * @type {RenderContext}
  18714. */
  18715. this.context = renderContext;
  18716. /**
  18717. * The 3D object's geometry.
  18718. *
  18719. * @type {BufferGeometry}
  18720. */
  18721. this.geometry = object.geometry;
  18722. /**
  18723. * The render object's version.
  18724. *
  18725. * @type {number}
  18726. */
  18727. this.version = material.version;
  18728. /**
  18729. * The draw range of the geometry.
  18730. *
  18731. * @type {?Object}
  18732. * @default null
  18733. */
  18734. this.drawRange = null;
  18735. /**
  18736. * An array holding the buffer attributes
  18737. * of the render object. This entails attribute
  18738. * definitions on geometry and node level.
  18739. *
  18740. * @type {?Array<BufferAttribute>}
  18741. * @default null
  18742. */
  18743. this.attributes = null;
  18744. /**
  18745. * An object holding the version of the
  18746. * attributes. The keys are the attribute names
  18747. * and the values are the attribute versions.
  18748. *
  18749. * @type {?Object<string, number>}
  18750. * @default null
  18751. */
  18752. this.attributesId = null;
  18753. /**
  18754. * A reference to a render pipeline the render
  18755. * object is processed with.
  18756. *
  18757. * @type {RenderPipeline}
  18758. * @default null
  18759. */
  18760. this.pipeline = null;
  18761. /**
  18762. * Only relevant for objects using
  18763. * multiple materials. This represents a group entry
  18764. * from the respective `BufferGeometry`.
  18765. *
  18766. * @type {?{start: number, count: number}}
  18767. * @default null
  18768. */
  18769. this.group = null;
  18770. /**
  18771. * An array holding the vertex buffers which can
  18772. * be buffer attributes but also interleaved buffers.
  18773. *
  18774. * @type {?Array<BufferAttribute|InterleavedBuffer>}
  18775. * @default null
  18776. */
  18777. this.vertexBuffers = null;
  18778. /**
  18779. * The parameters for the draw command.
  18780. *
  18781. * @type {?Object}
  18782. * @default null
  18783. */
  18784. this.drawParams = null;
  18785. /**
  18786. * If this render object is used inside a render bundle,
  18787. * this property points to the respective bundle group.
  18788. *
  18789. * @type {?BundleGroup}
  18790. * @default null
  18791. */
  18792. this.bundle = null;
  18793. /**
  18794. * The clipping context.
  18795. *
  18796. * @type {ClippingContext}
  18797. */
  18798. this.clippingContext = clippingContext;
  18799. /**
  18800. * The clipping context's cache key.
  18801. *
  18802. * @type {string}
  18803. */
  18804. this.clippingContextCacheKey = clippingContext !== null ? clippingContext.cacheKey : '';
  18805. /**
  18806. * The initial node cache key.
  18807. *
  18808. * @type {number}
  18809. */
  18810. this.initialNodesCacheKey = this.getDynamicCacheKey();
  18811. /**
  18812. * The initial cache key.
  18813. *
  18814. * @type {number}
  18815. */
  18816. this.initialCacheKey = this.getCacheKey();
  18817. /**
  18818. * The node builder state.
  18819. *
  18820. * @type {?NodeBuilderState}
  18821. * @private
  18822. * @default null
  18823. */
  18824. this._nodeBuilderState = null;
  18825. /**
  18826. * An array of bindings.
  18827. *
  18828. * @type {?Array<BindGroup>}
  18829. * @private
  18830. * @default null
  18831. */
  18832. this._bindings = null;
  18833. /**
  18834. * Reference to the node material observer.
  18835. *
  18836. * @type {?NodeMaterialObserver}
  18837. * @private
  18838. * @default null
  18839. */
  18840. this._monitor = null;
  18841. /**
  18842. * An event listener which is defined by `RenderObjects`. It performs
  18843. * clean up tasks when `dispose()` on this render object.
  18844. *
  18845. * @method
  18846. */
  18847. this.onDispose = null;
  18848. /**
  18849. * This flag can be used for type testing.
  18850. *
  18851. * @type {boolean}
  18852. * @readonly
  18853. * @default true
  18854. */
  18855. this.isRenderObject = true;
  18856. /**
  18857. * An event listener which is executed when `dispose()` is called on
  18858. * the material of this render object.
  18859. *
  18860. * @method
  18861. */
  18862. this.onMaterialDispose = () => {
  18863. this.dispose();
  18864. };
  18865. /**
  18866. * An event listener which is executed when `dispose()` is called on
  18867. * the geometry of this render object.
  18868. *
  18869. * @method
  18870. */
  18871. this.onGeometryDispose = () => {
  18872. // clear geometry cache attributes
  18873. this.attributes = null;
  18874. this.attributesId = null;
  18875. };
  18876. this.material.addEventListener( 'dispose', this.onMaterialDispose );
  18877. this.geometry.addEventListener( 'dispose', this.onGeometryDispose );
  18878. }
  18879. /**
  18880. * Updates the clipping context.
  18881. *
  18882. * @param {ClippingContext} context - The clipping context to set.
  18883. */
  18884. updateClipping( context ) {
  18885. this.clippingContext = context;
  18886. }
  18887. /**
  18888. * Whether the clipping requires an update or not.
  18889. *
  18890. * @type {boolean}
  18891. * @readonly
  18892. */
  18893. get clippingNeedsUpdate() {
  18894. if ( this.clippingContext === null || this.clippingContext.cacheKey === this.clippingContextCacheKey ) return false;
  18895. this.clippingContextCacheKey = this.clippingContext.cacheKey;
  18896. return true;
  18897. }
  18898. /**
  18899. * The number of clipping planes defined in context of hardware clipping.
  18900. *
  18901. * @type {number}
  18902. * @readonly
  18903. */
  18904. get hardwareClippingPlanes() {
  18905. return this.material.hardwareClipping === true ? this.clippingContext.unionClippingCount : 0;
  18906. }
  18907. /**
  18908. * Returns the node builder state of this render object.
  18909. *
  18910. * @return {NodeBuilderState} The node builder state.
  18911. */
  18912. getNodeBuilderState() {
  18913. return this._nodeBuilderState || ( this._nodeBuilderState = this._nodes.getForRender( this ) );
  18914. }
  18915. /**
  18916. * Returns the node material observer of this render object.
  18917. *
  18918. * @return {NodeMaterialObserver} The node material observer.
  18919. */
  18920. getMonitor() {
  18921. return this._monitor || ( this._monitor = this.getNodeBuilderState().observer );
  18922. }
  18923. /**
  18924. * Returns an array of bind groups of this render object.
  18925. *
  18926. * @return {Array<BindGroup>} The bindings.
  18927. */
  18928. getBindings() {
  18929. return this._bindings || ( this._bindings = this.getNodeBuilderState().createBindings() );
  18930. }
  18931. /**
  18932. * Returns a binding group by group name of this render object.
  18933. *
  18934. * @param {string} name - The name of the binding group.
  18935. * @return {?BindGroup} The bindings.
  18936. */
  18937. getBindingGroup( name ) {
  18938. for ( const bindingGroup of this.getBindings() ) {
  18939. if ( bindingGroup.name === name ) {
  18940. return bindingGroup;
  18941. }
  18942. }
  18943. }
  18944. /**
  18945. * Returns the index of the render object's geometry.
  18946. *
  18947. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  18948. */
  18949. getIndex() {
  18950. return this._geometries.getIndex( this );
  18951. }
  18952. /**
  18953. * Returns the indirect buffer attribute.
  18954. *
  18955. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  18956. */
  18957. getIndirect() {
  18958. return this._geometries.getIndirect( this );
  18959. }
  18960. /**
  18961. * Returns an array that acts as a key for identifying the render object in a chain map.
  18962. *
  18963. * @return {Array<Object>} An array with object references.
  18964. */
  18965. getChainArray() {
  18966. return [ this.object, this.material, this.context, this.lightsNode ];
  18967. }
  18968. /**
  18969. * This method is used when the geometry of a 3D object has been exchanged and the
  18970. * respective render object now requires an update.
  18971. *
  18972. * @param {BufferGeometry} geometry - The geometry to set.
  18973. */
  18974. setGeometry( geometry ) {
  18975. this.geometry = geometry;
  18976. this.attributes = null;
  18977. this.attributesId = null;
  18978. }
  18979. /**
  18980. * Returns the buffer attributes of the render object. The returned array holds
  18981. * attribute definitions on geometry and node level.
  18982. *
  18983. * @return {Array<BufferAttribute>} An array with buffer attributes.
  18984. */
  18985. getAttributes() {
  18986. if ( this.attributes !== null ) return this.attributes;
  18987. const nodeAttributes = this.getNodeBuilderState().nodeAttributes;
  18988. const geometry = this.geometry;
  18989. const attributes = [];
  18990. const vertexBuffers = new Set();
  18991. const attributesId = {};
  18992. for ( const nodeAttribute of nodeAttributes ) {
  18993. let attribute;
  18994. if ( nodeAttribute.node && nodeAttribute.node.attribute ) {
  18995. // node attribute
  18996. attribute = nodeAttribute.node.attribute;
  18997. } else {
  18998. // geometry attribute
  18999. attribute = geometry.getAttribute( nodeAttribute.name );
  19000. attributesId[ nodeAttribute.name ] = attribute.version;
  19001. }
  19002. if ( attribute === undefined ) continue;
  19003. attributes.push( attribute );
  19004. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  19005. vertexBuffers.add( bufferAttribute );
  19006. }
  19007. this.attributes = attributes;
  19008. this.attributesId = attributesId;
  19009. this.vertexBuffers = Array.from( vertexBuffers.values() );
  19010. return attributes;
  19011. }
  19012. /**
  19013. * Returns the vertex buffers of the render object.
  19014. *
  19015. * @return {Array<BufferAttribute|InterleavedBuffer>} An array with buffer attribute or interleaved buffers.
  19016. */
  19017. getVertexBuffers() {
  19018. if ( this.vertexBuffers === null ) this.getAttributes();
  19019. return this.vertexBuffers;
  19020. }
  19021. /**
  19022. * Returns the draw parameters for the render object.
  19023. *
  19024. * @return {?{vertexCount: number, firstVertex: number, instanceCount: number, firstInstance: number}} The draw parameters.
  19025. */
  19026. getDrawParameters() {
  19027. const { object, material, geometry, group, drawRange } = this;
  19028. const drawParams = this.drawParams || ( this.drawParams = {
  19029. vertexCount: 0,
  19030. firstVertex: 0,
  19031. instanceCount: 0,
  19032. firstInstance: 0
  19033. } );
  19034. const index = this.getIndex();
  19035. const hasIndex = ( index !== null );
  19036. let instanceCount = 1;
  19037. if ( geometry.isInstancedBufferGeometry === true ) {
  19038. instanceCount = geometry.instanceCount;
  19039. } else if ( object.count !== undefined ) {
  19040. instanceCount = Math.max( 0, object.count );
  19041. }
  19042. if ( instanceCount === 0 ) return null;
  19043. drawParams.instanceCount = instanceCount;
  19044. if ( object.isBatchedMesh === true ) return drawParams;
  19045. let rangeFactor = 1;
  19046. if ( material.wireframe === true && ! object.isPoints && ! object.isLineSegments && ! object.isLine && ! object.isLineLoop ) {
  19047. rangeFactor = 2;
  19048. }
  19049. let firstVertex = drawRange.start * rangeFactor;
  19050. let lastVertex = ( drawRange.start + drawRange.count ) * rangeFactor;
  19051. if ( group !== null ) {
  19052. firstVertex = Math.max( firstVertex, group.start * rangeFactor );
  19053. lastVertex = Math.min( lastVertex, ( group.start + group.count ) * rangeFactor );
  19054. }
  19055. const position = geometry.attributes.position;
  19056. let itemCount = Infinity;
  19057. if ( hasIndex ) {
  19058. itemCount = index.count;
  19059. } else if ( position !== undefined && position !== null ) {
  19060. itemCount = position.count;
  19061. }
  19062. firstVertex = Math.max( firstVertex, 0 );
  19063. lastVertex = Math.min( lastVertex, itemCount );
  19064. const count = lastVertex - firstVertex;
  19065. if ( count < 0 || count === Infinity ) return null;
  19066. drawParams.vertexCount = count;
  19067. drawParams.firstVertex = firstVertex;
  19068. return drawParams;
  19069. }
  19070. /**
  19071. * Returns the render object's geometry cache key.
  19072. *
  19073. * The geometry cache key is part of the material cache key.
  19074. *
  19075. * @return {string} The geometry cache key.
  19076. */
  19077. getGeometryCacheKey() {
  19078. const { geometry } = this;
  19079. let cacheKey = '';
  19080. for ( const name of Object.keys( geometry.attributes ).sort() ) {
  19081. const attribute = geometry.attributes[ name ];
  19082. cacheKey += name + ',';
  19083. if ( attribute.data ) cacheKey += attribute.data.stride + ',';
  19084. if ( attribute.offset ) cacheKey += attribute.offset + ',';
  19085. if ( attribute.itemSize ) cacheKey += attribute.itemSize + ',';
  19086. if ( attribute.normalized ) cacheKey += 'n,';
  19087. }
  19088. // structural equality isn't sufficient for morph targets since the
  19089. // data are maintained in textures. only if the targets are all equal
  19090. // the texture and thus the instance of `MorphNode` can be shared.
  19091. for ( const name of Object.keys( geometry.morphAttributes ).sort() ) {
  19092. const targets = geometry.morphAttributes[ name ];
  19093. cacheKey += 'morph-' + name + ',';
  19094. for ( let i = 0, l = targets.length; i < l; i ++ ) {
  19095. const attribute = targets[ i ];
  19096. cacheKey += attribute.id + ',';
  19097. }
  19098. }
  19099. if ( geometry.index ) {
  19100. cacheKey += 'index,';
  19101. }
  19102. return cacheKey;
  19103. }
  19104. /**
  19105. * Returns the render object's material cache key.
  19106. *
  19107. * The material cache key is part of the render object cache key.
  19108. *
  19109. * @return {number} The material cache key.
  19110. */
  19111. getMaterialCacheKey() {
  19112. const { object, material } = this;
  19113. let cacheKey = material.customProgramCacheKey();
  19114. for ( const property of getKeys( material ) ) {
  19115. if ( /^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test( property ) ) continue;
  19116. const value = material[ property ];
  19117. let valueKey;
  19118. if ( value !== null ) {
  19119. // some material values require a formatting
  19120. const type = typeof value;
  19121. if ( type === 'number' ) {
  19122. valueKey = value !== 0 ? '1' : '0'; // Convert to on/off, important for clearcoat, transmission, etc
  19123. } else if ( type === 'object' ) {
  19124. valueKey = '{';
  19125. if ( value.isTexture ) {
  19126. valueKey += value.mapping;
  19127. }
  19128. valueKey += '}';
  19129. } else {
  19130. valueKey = String( value );
  19131. }
  19132. } else {
  19133. valueKey = String( value );
  19134. }
  19135. cacheKey += /*property + ':' +*/ valueKey + ',';
  19136. }
  19137. cacheKey += this.clippingContextCacheKey + ',';
  19138. if ( object.geometry ) {
  19139. cacheKey += this.getGeometryCacheKey();
  19140. }
  19141. if ( object.skeleton ) {
  19142. cacheKey += object.skeleton.bones.length + ',';
  19143. }
  19144. if ( object.isBatchedMesh ) {
  19145. cacheKey += object._matricesTexture.uuid + ',';
  19146. if ( object._colorsTexture !== null ) {
  19147. cacheKey += object._colorsTexture.uuid + ',';
  19148. }
  19149. }
  19150. if ( object.count > 1 ) {
  19151. // TODO: https://github.com/mrdoob/three.js/pull/29066#issuecomment-2269400850
  19152. cacheKey += object.uuid + ',';
  19153. }
  19154. cacheKey += object.receiveShadow + ',';
  19155. return hashString( cacheKey );
  19156. }
  19157. /**
  19158. * Whether the geometry requires an update or not.
  19159. *
  19160. * @type {boolean}
  19161. * @readonly
  19162. */
  19163. get needsGeometryUpdate() {
  19164. if ( this.geometry.id !== this.object.geometry.id ) return true;
  19165. if ( this.attributes !== null ) {
  19166. const attributesId = this.attributesId;
  19167. for ( const name in attributesId ) {
  19168. const attribute = this.geometry.getAttribute( name );
  19169. if ( attribute === undefined || attributesId[ name ] !== attribute.id ) {
  19170. return true;
  19171. }
  19172. }
  19173. }
  19174. return false;
  19175. }
  19176. /**
  19177. * Whether the render object requires an update or not.
  19178. *
  19179. * Note: There are two distinct places where render objects are checked for an update.
  19180. *
  19181. * 1. In `RenderObjects.get()` which is executed when the render object is request. This
  19182. * method checks the `needsUpdate` flag and recreates the render object if necessary.
  19183. * 2. In `Renderer._renderObjectDirect()` right after getting the render object via
  19184. * `RenderObjects.get()`. The render object's NodeMaterialObserver is then used to detect
  19185. * a need for a refresh due to material, geometry or object related value changes.
  19186. *
  19187. * TODO: Investigate if it's possible to merge both steps so there is only a single place
  19188. * that performs the 'needsUpdate' check.
  19189. *
  19190. * @type {boolean}
  19191. * @readonly
  19192. */
  19193. get needsUpdate() {
  19194. return /*this.object.static !== true &&*/ ( this.initialNodesCacheKey !== this.getDynamicCacheKey() || this.clippingNeedsUpdate );
  19195. }
  19196. /**
  19197. * Returns the dynamic cache key which represents a key that is computed per draw command.
  19198. *
  19199. * @return {number} The cache key.
  19200. */
  19201. getDynamicCacheKey() {
  19202. let cacheKey = 0;
  19203. // `Nodes.getCacheKey()` returns an environment cache key which is not relevant when
  19204. // the renderer is inside a shadow pass.
  19205. if ( this.material.isShadowPassMaterial !== true ) {
  19206. cacheKey = this._nodes.getCacheKey( this.scene, this.lightsNode );
  19207. }
  19208. if ( this.camera.isArrayCamera ) {
  19209. cacheKey = hash$1( cacheKey, this.camera.cameras.length );
  19210. }
  19211. if ( this.object.receiveShadow ) {
  19212. cacheKey = hash$1( cacheKey, 1 );
  19213. }
  19214. return cacheKey;
  19215. }
  19216. /**
  19217. * Returns the render object's cache key.
  19218. *
  19219. * @return {number} The cache key.
  19220. */
  19221. getCacheKey() {
  19222. return this.getMaterialCacheKey() + this.getDynamicCacheKey();
  19223. }
  19224. /**
  19225. * Frees internal resources.
  19226. */
  19227. dispose() {
  19228. this.material.removeEventListener( 'dispose', this.onMaterialDispose );
  19229. this.geometry.removeEventListener( 'dispose', this.onGeometryDispose );
  19230. this.onDispose();
  19231. }
  19232. }
  19233. const _chainKeys$5 = [];
  19234. /**
  19235. * This module manages the render objects of the renderer.
  19236. *
  19237. * @private
  19238. */
  19239. class RenderObjects {
  19240. /**
  19241. * Constructs a new render object management component.
  19242. *
  19243. * @param {Renderer} renderer - The renderer.
  19244. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19245. * @param {Geometries} geometries - Renderer component for managing geometries.
  19246. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  19247. * @param {Bindings} bindings - Renderer component for managing bindings.
  19248. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19249. */
  19250. constructor( renderer, nodes, geometries, pipelines, bindings, info ) {
  19251. /**
  19252. * The renderer.
  19253. *
  19254. * @type {Renderer}
  19255. */
  19256. this.renderer = renderer;
  19257. /**
  19258. * Renderer component for managing nodes related logic.
  19259. *
  19260. * @type {Nodes}
  19261. */
  19262. this.nodes = nodes;
  19263. /**
  19264. * Renderer component for managing geometries.
  19265. *
  19266. * @type {Geometries}
  19267. */
  19268. this.geometries = geometries;
  19269. /**
  19270. * Renderer component for managing pipelines.
  19271. *
  19272. * @type {Pipelines}
  19273. */
  19274. this.pipelines = pipelines;
  19275. /**
  19276. * Renderer component for managing bindings.
  19277. *
  19278. * @type {Bindings}
  19279. */
  19280. this.bindings = bindings;
  19281. /**
  19282. * Renderer component for managing metrics and monitoring data.
  19283. *
  19284. * @type {Info}
  19285. */
  19286. this.info = info;
  19287. /**
  19288. * A dictionary that manages render contexts in chain maps
  19289. * for each pass ID.
  19290. *
  19291. * @type {Object<string,ChainMap>}
  19292. */
  19293. this.chainMaps = {};
  19294. }
  19295. /**
  19296. * Returns a render object for the given object and state data.
  19297. *
  19298. * @param {Object3D} object - The 3D object.
  19299. * @param {Material} material - The 3D object's material.
  19300. * @param {Scene} scene - The scene the 3D object belongs to.
  19301. * @param {Camera} camera - The camera the 3D object should be rendered with.
  19302. * @param {LightsNode} lightsNode - The lights node.
  19303. * @param {RenderContext} renderContext - The render context.
  19304. * @param {ClippingContext} clippingContext - The clipping context.
  19305. * @param {string} [passId] - An optional ID for identifying the pass.
  19306. * @return {RenderObject} The render object.
  19307. */
  19308. get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  19309. const chainMap = this.getChainMap( passId );
  19310. // reuse chainArray
  19311. _chainKeys$5[ 0 ] = object;
  19312. _chainKeys$5[ 1 ] = material;
  19313. _chainKeys$5[ 2 ] = renderContext;
  19314. _chainKeys$5[ 3 ] = lightsNode;
  19315. let renderObject = chainMap.get( _chainKeys$5 );
  19316. if ( renderObject === undefined ) {
  19317. renderObject = this.createRenderObject( this.nodes, this.geometries, this.renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  19318. chainMap.set( _chainKeys$5, renderObject );
  19319. } else {
  19320. renderObject.updateClipping( clippingContext );
  19321. if ( renderObject.needsGeometryUpdate ) {
  19322. renderObject.setGeometry( object.geometry );
  19323. }
  19324. if ( renderObject.version !== material.version || renderObject.needsUpdate ) {
  19325. if ( renderObject.initialCacheKey !== renderObject.getCacheKey() ) {
  19326. renderObject.dispose();
  19327. renderObject = this.get( object, material, scene, camera, lightsNode, renderContext, clippingContext, passId );
  19328. } else {
  19329. renderObject.version = material.version;
  19330. }
  19331. }
  19332. }
  19333. _chainKeys$5.length = 0;
  19334. return renderObject;
  19335. }
  19336. /**
  19337. * Returns a chain map for the given pass ID.
  19338. *
  19339. * @param {string} [passId='default'] - The pass ID.
  19340. * @return {ChainMap} The chain map.
  19341. */
  19342. getChainMap( passId = 'default' ) {
  19343. return this.chainMaps[ passId ] || ( this.chainMaps[ passId ] = new ChainMap() );
  19344. }
  19345. /**
  19346. * Frees internal resources.
  19347. */
  19348. dispose() {
  19349. this.chainMaps = {};
  19350. }
  19351. /**
  19352. * Factory method for creating render objects with the given list of parameters.
  19353. *
  19354. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  19355. * @param {Geometries} geometries - Renderer component for managing geometries.
  19356. * @param {Renderer} renderer - The renderer.
  19357. * @param {Object3D} object - The 3D object.
  19358. * @param {Material} material - The object's material.
  19359. * @param {Scene} scene - The scene the 3D object belongs to.
  19360. * @param {Camera} camera - The camera the object should be rendered with.
  19361. * @param {LightsNode} lightsNode - The lights node.
  19362. * @param {RenderContext} renderContext - The render context.
  19363. * @param {ClippingContext} clippingContext - The clipping context.
  19364. * @param {string} [passId] - An optional ID for identifying the pass.
  19365. * @return {RenderObject} The render object.
  19366. */
  19367. createRenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext, passId ) {
  19368. const chainMap = this.getChainMap( passId );
  19369. const renderObject = new RenderObject( nodes, geometries, renderer, object, material, scene, camera, lightsNode, renderContext, clippingContext );
  19370. renderObject.onDispose = () => {
  19371. this.pipelines.delete( renderObject );
  19372. this.bindings.delete( renderObject );
  19373. this.nodes.delete( renderObject );
  19374. chainMap.delete( renderObject.getChainArray() );
  19375. };
  19376. return renderObject;
  19377. }
  19378. }
  19379. /**
  19380. * Data structure for the renderer. It is intended to manage
  19381. * data of objects in dictionaries.
  19382. *
  19383. * @private
  19384. */
  19385. class DataMap {
  19386. /**
  19387. * Constructs a new data map.
  19388. */
  19389. constructor() {
  19390. /**
  19391. * `DataMap` internally uses a weak map
  19392. * to manage its data.
  19393. *
  19394. * @type {WeakMap}
  19395. */
  19396. this.data = new WeakMap();
  19397. }
  19398. /**
  19399. * Returns the dictionary for the given object.
  19400. *
  19401. * @param {Object} object - The object.
  19402. * @return {Object} The dictionary.
  19403. */
  19404. get( object ) {
  19405. let map = this.data.get( object );
  19406. if ( map === undefined ) {
  19407. map = {};
  19408. this.data.set( object, map );
  19409. }
  19410. return map;
  19411. }
  19412. /**
  19413. * Deletes the dictionary for the given object.
  19414. *
  19415. * @param {Object} object - The object.
  19416. * @return {?Object} The deleted dictionary.
  19417. */
  19418. delete( object ) {
  19419. let map = null;
  19420. if ( this.data.has( object ) ) {
  19421. map = this.data.get( object );
  19422. this.data.delete( object );
  19423. }
  19424. return map;
  19425. }
  19426. /**
  19427. * Returns `true` if the given object has a dictionary defined.
  19428. *
  19429. * @param {Object} object - The object to test.
  19430. * @return {boolean} Whether a dictionary is defined or not.
  19431. */
  19432. has( object ) {
  19433. return this.data.has( object );
  19434. }
  19435. /**
  19436. * Frees internal resources.
  19437. */
  19438. dispose() {
  19439. this.data = new WeakMap();
  19440. }
  19441. }
  19442. const AttributeType = {
  19443. VERTEX: 1,
  19444. INDEX: 2,
  19445. STORAGE: 3,
  19446. INDIRECT: 4
  19447. };
  19448. // size of a chunk in bytes (STD140 layout)
  19449. const GPU_CHUNK_BYTES = 16;
  19450. // @TODO: Move to src/constants.js
  19451. const BlendColorFactor = 211;
  19452. const OneMinusBlendColorFactor = 212;
  19453. /**
  19454. * This renderer module manages geometry attributes.
  19455. *
  19456. * @private
  19457. * @augments DataMap
  19458. */
  19459. class Attributes extends DataMap {
  19460. /**
  19461. * Constructs a new attribute management component.
  19462. *
  19463. * @param {Backend} backend - The renderer's backend.
  19464. */
  19465. constructor( backend ) {
  19466. super();
  19467. /**
  19468. * The renderer's backend.
  19469. *
  19470. * @type {Backend}
  19471. */
  19472. this.backend = backend;
  19473. }
  19474. /**
  19475. * Deletes the data for the given attribute.
  19476. *
  19477. * @param {BufferAttribute} attribute - The attribute.
  19478. * @return {Object|null} The deleted attribute data.
  19479. */
  19480. delete( attribute ) {
  19481. const attributeData = super.delete( attribute );
  19482. if ( attributeData !== null ) {
  19483. this.backend.destroyAttribute( attribute );
  19484. }
  19485. return attributeData;
  19486. }
  19487. /**
  19488. * Updates the given attribute. This method creates attribute buffers
  19489. * for new attributes and updates data for existing ones.
  19490. *
  19491. * @param {BufferAttribute} attribute - The attribute to update.
  19492. * @param {number} type - The attribute type.
  19493. */
  19494. update( attribute, type ) {
  19495. const data = this.get( attribute );
  19496. if ( data.version === undefined ) {
  19497. if ( type === AttributeType.VERTEX ) {
  19498. this.backend.createAttribute( attribute );
  19499. } else if ( type === AttributeType.INDEX ) {
  19500. this.backend.createIndexAttribute( attribute );
  19501. } else if ( type === AttributeType.STORAGE ) {
  19502. this.backend.createStorageAttribute( attribute );
  19503. } else if ( type === AttributeType.INDIRECT ) {
  19504. this.backend.createIndirectStorageAttribute( attribute );
  19505. }
  19506. data.version = this._getBufferAttribute( attribute ).version;
  19507. } else {
  19508. const bufferAttribute = this._getBufferAttribute( attribute );
  19509. if ( data.version < bufferAttribute.version || bufferAttribute.usage === DynamicDrawUsage ) {
  19510. this.backend.updateAttribute( attribute );
  19511. data.version = bufferAttribute.version;
  19512. }
  19513. }
  19514. }
  19515. /**
  19516. * Utility method for handling interleaved buffer attributes correctly.
  19517. * To process them, their `InterleavedBuffer` is returned.
  19518. *
  19519. * @param {BufferAttribute} attribute - The attribute.
  19520. * @return {BufferAttribute|InterleavedBuffer}
  19521. */
  19522. _getBufferAttribute( attribute ) {
  19523. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  19524. return attribute;
  19525. }
  19526. }
  19527. /**
  19528. * Returns the wireframe version for the given geometry.
  19529. *
  19530. * @private
  19531. * @function
  19532. * @param {BufferGeometry} geometry - The geometry.
  19533. * @return {number} The version.
  19534. */
  19535. function getWireframeVersion( geometry ) {
  19536. return ( geometry.index !== null ) ? geometry.index.version : geometry.attributes.position.version;
  19537. }
  19538. /**
  19539. * Returns a wireframe index attribute for the given geometry.
  19540. *
  19541. * @private
  19542. * @function
  19543. * @param {BufferGeometry} geometry - The geometry.
  19544. * @return {BufferAttribute} The wireframe index attribute.
  19545. */
  19546. function getWireframeIndex( geometry ) {
  19547. const indices = [];
  19548. const geometryIndex = geometry.index;
  19549. const geometryPosition = geometry.attributes.position;
  19550. if ( geometryIndex !== null ) {
  19551. const array = geometryIndex.array;
  19552. for ( let i = 0, l = array.length; i < l; i += 3 ) {
  19553. const a = array[ i + 0 ];
  19554. const b = array[ i + 1 ];
  19555. const c = array[ i + 2 ];
  19556. indices.push( a, b, b, c, c, a );
  19557. }
  19558. } else {
  19559. const array = geometryPosition.array;
  19560. for ( let i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  19561. const a = i + 0;
  19562. const b = i + 1;
  19563. const c = i + 2;
  19564. indices.push( a, b, b, c, c, a );
  19565. }
  19566. }
  19567. const attribute = new ( arrayNeedsUint32( indices ) ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  19568. attribute.version = getWireframeVersion( geometry );
  19569. return attribute;
  19570. }
  19571. /**
  19572. * This renderer module manages geometries.
  19573. *
  19574. * @private
  19575. * @augments DataMap
  19576. */
  19577. class Geometries extends DataMap {
  19578. /**
  19579. * Constructs a new geometry management component.
  19580. *
  19581. * @param {Attributes} attributes - Renderer component for managing attributes.
  19582. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  19583. */
  19584. constructor( attributes, info ) {
  19585. super();
  19586. /**
  19587. * Renderer component for managing attributes.
  19588. *
  19589. * @type {Attributes}
  19590. */
  19591. this.attributes = attributes;
  19592. /**
  19593. * Renderer component for managing metrics and monitoring data.
  19594. *
  19595. * @type {Info}
  19596. */
  19597. this.info = info;
  19598. /**
  19599. * Weak Map for managing attributes for wireframe rendering.
  19600. *
  19601. * @type {WeakMap<BufferGeometry,BufferAttribute>}
  19602. */
  19603. this.wireframes = new WeakMap();
  19604. /**
  19605. * This Weak Map is used to make sure buffer attributes are
  19606. * updated only once per render call.
  19607. *
  19608. * @type {WeakMap<BufferAttribute,number>}
  19609. */
  19610. this.attributeCall = new WeakMap();
  19611. }
  19612. /**
  19613. * Returns `true` if the given render object has an initialized geometry.
  19614. *
  19615. * @param {RenderObject} renderObject - The render object.
  19616. * @return {boolean} Whether if the given render object has an initialized geometry or not.
  19617. */
  19618. has( renderObject ) {
  19619. const geometry = renderObject.geometry;
  19620. return super.has( geometry ) && this.get( geometry ).initialized === true;
  19621. }
  19622. /**
  19623. * Prepares the geometry of the given render object for rendering.
  19624. *
  19625. * @param {RenderObject} renderObject - The render object.
  19626. */
  19627. updateForRender( renderObject ) {
  19628. if ( this.has( renderObject ) === false ) this.initGeometry( renderObject );
  19629. this.updateAttributes( renderObject );
  19630. }
  19631. /**
  19632. * Initializes the geometry of the given render object.
  19633. *
  19634. * @param {RenderObject} renderObject - The render object.
  19635. */
  19636. initGeometry( renderObject ) {
  19637. const geometry = renderObject.geometry;
  19638. const geometryData = this.get( geometry );
  19639. geometryData.initialized = true;
  19640. this.info.memory.geometries ++;
  19641. const onDispose = () => {
  19642. this.info.memory.geometries --;
  19643. const index = geometry.index;
  19644. const geometryAttributes = renderObject.getAttributes();
  19645. if ( index !== null ) {
  19646. this.attributes.delete( index );
  19647. }
  19648. for ( const geometryAttribute of geometryAttributes ) {
  19649. this.attributes.delete( geometryAttribute );
  19650. }
  19651. const wireframeAttribute = this.wireframes.get( geometry );
  19652. if ( wireframeAttribute !== undefined ) {
  19653. this.attributes.delete( wireframeAttribute );
  19654. }
  19655. geometry.removeEventListener( 'dispose', onDispose );
  19656. };
  19657. geometry.addEventListener( 'dispose', onDispose );
  19658. }
  19659. /**
  19660. * Updates the geometry attributes of the given render object.
  19661. *
  19662. * @param {RenderObject} renderObject - The render object.
  19663. */
  19664. updateAttributes( renderObject ) {
  19665. // attributes
  19666. const attributes = renderObject.getAttributes();
  19667. for ( const attribute of attributes ) {
  19668. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  19669. this.updateAttribute( attribute, AttributeType.STORAGE );
  19670. } else {
  19671. this.updateAttribute( attribute, AttributeType.VERTEX );
  19672. }
  19673. }
  19674. // indexes
  19675. const index = this.getIndex( renderObject );
  19676. if ( index !== null ) {
  19677. this.updateAttribute( index, AttributeType.INDEX );
  19678. }
  19679. // indirect
  19680. const indirect = renderObject.geometry.indirect;
  19681. if ( indirect !== null ) {
  19682. this.updateAttribute( indirect, AttributeType.INDIRECT );
  19683. }
  19684. }
  19685. /**
  19686. * Updates the given attribute.
  19687. *
  19688. * @param {BufferAttribute} attribute - The attribute to update.
  19689. * @param {number} type - The attribute type.
  19690. */
  19691. updateAttribute( attribute, type ) {
  19692. const callId = this.info.render.calls;
  19693. if ( ! attribute.isInterleavedBufferAttribute ) {
  19694. if ( this.attributeCall.get( attribute ) !== callId ) {
  19695. this.attributes.update( attribute, type );
  19696. this.attributeCall.set( attribute, callId );
  19697. }
  19698. } else {
  19699. if ( this.attributeCall.get( attribute ) === undefined ) {
  19700. this.attributes.update( attribute, type );
  19701. this.attributeCall.set( attribute, callId );
  19702. } else if ( this.attributeCall.get( attribute.data ) !== callId ) {
  19703. this.attributes.update( attribute, type );
  19704. this.attributeCall.set( attribute.data, callId );
  19705. this.attributeCall.set( attribute, callId );
  19706. }
  19707. }
  19708. }
  19709. /**
  19710. * Returns the indirect buffer attribute of the given render object.
  19711. *
  19712. * @param {RenderObject} renderObject - The render object.
  19713. * @return {?BufferAttribute} The indirect attribute. `null` if no indirect drawing is used.
  19714. */
  19715. getIndirect( renderObject ) {
  19716. return renderObject.geometry.indirect;
  19717. }
  19718. /**
  19719. * Returns the index of the given render object's geometry. This is implemented
  19720. * in a method to return a wireframe index if necessary.
  19721. *
  19722. * @param {RenderObject} renderObject - The render object.
  19723. * @return {?BufferAttribute} The index. Returns `null` for non-indexed geometries.
  19724. */
  19725. getIndex( renderObject ) {
  19726. const { geometry, material } = renderObject;
  19727. let index = geometry.index;
  19728. if ( material.wireframe === true ) {
  19729. const wireframes = this.wireframes;
  19730. let wireframeAttribute = wireframes.get( geometry );
  19731. if ( wireframeAttribute === undefined ) {
  19732. wireframeAttribute = getWireframeIndex( geometry );
  19733. wireframes.set( geometry, wireframeAttribute );
  19734. } else if ( wireframeAttribute.version !== getWireframeVersion( geometry ) ) {
  19735. this.attributes.delete( wireframeAttribute );
  19736. wireframeAttribute = getWireframeIndex( geometry );
  19737. wireframes.set( geometry, wireframeAttribute );
  19738. }
  19739. index = wireframeAttribute;
  19740. }
  19741. return index;
  19742. }
  19743. }
  19744. /**
  19745. * This renderer module provides a series of statistical information
  19746. * about the GPU memory and the rendering process. Useful for debugging
  19747. * and monitoring.
  19748. */
  19749. class Info {
  19750. /**
  19751. * Constructs a new info component.
  19752. */
  19753. constructor() {
  19754. /**
  19755. * Whether frame related metrics should automatically
  19756. * be resetted or not. This property should be set to `false`
  19757. * by apps which manage their own animation loop. They must
  19758. * then call `renderer.info.reset()` once per frame manually.
  19759. *
  19760. * @type {boolean}
  19761. * @default true
  19762. */
  19763. this.autoReset = true;
  19764. /**
  19765. * The current frame ID. This ID is managed
  19766. * by `NodeFrame`.
  19767. *
  19768. * @type {number}
  19769. * @readonly
  19770. * @default 0
  19771. */
  19772. this.frame = 0;
  19773. /**
  19774. * The number of render calls since the
  19775. * app has been started.
  19776. *
  19777. * @type {number}
  19778. * @readonly
  19779. * @default 0
  19780. */
  19781. this.calls = 0;
  19782. /**
  19783. * Render related metrics.
  19784. *
  19785. * @type {Object}
  19786. * @readonly
  19787. * @property {number} calls - The number of render calls since the app has been started.
  19788. * @property {number} frameCalls - The number of render calls of the current frame.
  19789. * @property {number} drawCalls - The number of draw calls of the current frame.
  19790. * @property {number} triangles - The number of rendered triangle primitives of the current frame.
  19791. * @property {number} points - The number of rendered point primitives of the current frame.
  19792. * @property {number} lines - The number of rendered line primitives of the current frame.
  19793. * @property {number} timestamp - The timestamp of the frame when using `renderer.renderAsync()`.
  19794. */
  19795. this.render = {
  19796. calls: 0,
  19797. frameCalls: 0,
  19798. drawCalls: 0,
  19799. triangles: 0,
  19800. points: 0,
  19801. lines: 0,
  19802. timestamp: 0,
  19803. };
  19804. /**
  19805. * Compute related metrics.
  19806. *
  19807. * @type {Object}
  19808. * @readonly
  19809. * @property {number} calls - The number of compute calls since the app has been started.
  19810. * @property {number} frameCalls - The number of compute calls of the current frame.
  19811. * @property {number} timestamp - The timestamp of the frame when using `renderer.computeAsync()`.
  19812. */
  19813. this.compute = {
  19814. calls: 0,
  19815. frameCalls: 0,
  19816. timestamp: 0
  19817. };
  19818. /**
  19819. * Memory related metrics.
  19820. *
  19821. * @type {Object}
  19822. * @readonly
  19823. * @property {number} geometries - The number of active geometries.
  19824. * @property {number} frameCalls - The number of active textures.
  19825. */
  19826. this.memory = {
  19827. geometries: 0,
  19828. textures: 0
  19829. };
  19830. }
  19831. /**
  19832. * This method should be executed per draw call and updates the corresponding metrics.
  19833. *
  19834. * @param {Object3D} object - The 3D object that is going to be rendered.
  19835. * @param {number} count - The vertex or index count.
  19836. * @param {number} instanceCount - The instance count.
  19837. */
  19838. update( object, count, instanceCount ) {
  19839. this.render.drawCalls ++;
  19840. if ( object.isMesh || object.isSprite ) {
  19841. this.render.triangles += instanceCount * ( count / 3 );
  19842. } else if ( object.isPoints ) {
  19843. this.render.points += instanceCount * count;
  19844. } else if ( object.isLineSegments ) {
  19845. this.render.lines += instanceCount * ( count / 2 );
  19846. } else if ( object.isLine ) {
  19847. this.render.lines += instanceCount * ( count - 1 );
  19848. } else {
  19849. console.error( 'THREE.WebGPUInfo: Unknown object type.' );
  19850. }
  19851. }
  19852. /**
  19853. * Resets frame related metrics.
  19854. */
  19855. reset() {
  19856. this.render.drawCalls = 0;
  19857. this.render.frameCalls = 0;
  19858. this.compute.frameCalls = 0;
  19859. this.render.triangles = 0;
  19860. this.render.points = 0;
  19861. this.render.lines = 0;
  19862. }
  19863. /**
  19864. * Performs a complete reset of the object.
  19865. */
  19866. dispose() {
  19867. this.reset();
  19868. this.calls = 0;
  19869. this.render.calls = 0;
  19870. this.compute.calls = 0;
  19871. this.render.timestamp = 0;
  19872. this.compute.timestamp = 0;
  19873. this.memory.geometries = 0;
  19874. this.memory.textures = 0;
  19875. }
  19876. }
  19877. /**
  19878. * Abstract class for representing pipelines.
  19879. *
  19880. * @private
  19881. * @abstract
  19882. */
  19883. class Pipeline {
  19884. /**
  19885. * Constructs a new pipeline.
  19886. *
  19887. * @param {string} cacheKey - The pipeline's cache key.
  19888. */
  19889. constructor( cacheKey ) {
  19890. /**
  19891. * The pipeline's cache key.
  19892. *
  19893. * @type {string}
  19894. */
  19895. this.cacheKey = cacheKey;
  19896. /**
  19897. * How often the pipeline is currently in use.
  19898. *
  19899. * @type {number}
  19900. * @default 0
  19901. */
  19902. this.usedTimes = 0;
  19903. }
  19904. }
  19905. /**
  19906. * Class for representing render pipelines.
  19907. *
  19908. * @private
  19909. * @augments Pipeline
  19910. */
  19911. class RenderPipeline extends Pipeline {
  19912. /**
  19913. * Constructs a new render pipeline.
  19914. *
  19915. * @param {string} cacheKey - The pipeline's cache key.
  19916. * @param {ProgrammableStage} vertexProgram - The pipeline's vertex shader.
  19917. * @param {ProgrammableStage} fragmentProgram - The pipeline's fragment shader.
  19918. */
  19919. constructor( cacheKey, vertexProgram, fragmentProgram ) {
  19920. super( cacheKey );
  19921. /**
  19922. * The pipeline's vertex shader.
  19923. *
  19924. * @type {ProgrammableStage}
  19925. */
  19926. this.vertexProgram = vertexProgram;
  19927. /**
  19928. * The pipeline's fragment shader.
  19929. *
  19930. * @type {ProgrammableStage}
  19931. */
  19932. this.fragmentProgram = fragmentProgram;
  19933. }
  19934. }
  19935. /**
  19936. * Class for representing compute pipelines.
  19937. *
  19938. * @private
  19939. * @augments Pipeline
  19940. */
  19941. class ComputePipeline extends Pipeline {
  19942. /**
  19943. * Constructs a new render pipeline.
  19944. *
  19945. * @param {string} cacheKey - The pipeline's cache key.
  19946. * @param {ProgrammableStage} computeProgram - The pipeline's compute shader.
  19947. */
  19948. constructor( cacheKey, computeProgram ) {
  19949. super( cacheKey );
  19950. /**
  19951. * The pipeline's compute shader.
  19952. *
  19953. * @type {ProgrammableStage}
  19954. */
  19955. this.computeProgram = computeProgram;
  19956. /**
  19957. * This flag can be used for type testing.
  19958. *
  19959. * @type {boolean}
  19960. * @readonly
  19961. * @default true
  19962. */
  19963. this.isComputePipeline = true;
  19964. }
  19965. }
  19966. let _id$8 = 0;
  19967. /**
  19968. * Class for representing programmable stages which are vertex,
  19969. * fragment or compute shaders. Unlike fixed-function states (like blending),
  19970. * they represent the programmable part of a pipeline.
  19971. *
  19972. * @private
  19973. */
  19974. class ProgrammableStage {
  19975. /**
  19976. * Constructs a new programmable stage.
  19977. *
  19978. * @param {string} code - The shader code.
  19979. * @param {('vertex'|'fragment'|'compute')} stage - The type of stage.
  19980. * @param {string} name - The name of the shader.
  19981. * @param {?Array<Object>} [transforms=null] - The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19982. * @param {?Array<Object>} [attributes=null] - The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  19983. */
  19984. constructor( code, stage, name, transforms = null, attributes = null ) {
  19985. /**
  19986. * The id of the programmable stage.
  19987. *
  19988. * @type {number}
  19989. */
  19990. this.id = _id$8 ++;
  19991. /**
  19992. * The shader code.
  19993. *
  19994. * @type {string}
  19995. */
  19996. this.code = code;
  19997. /**
  19998. * The type of stage.
  19999. *
  20000. * @type {string}
  20001. */
  20002. this.stage = stage;
  20003. /**
  20004. * The name of the stage.
  20005. * This is used for debugging purposes.
  20006. *
  20007. * @type {string}
  20008. */
  20009. this.name = name;
  20010. /**
  20011. * The transforms (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20012. *
  20013. * @type {?Array<Object>}
  20014. */
  20015. this.transforms = transforms;
  20016. /**
  20017. * The attributes (only relevant for compute stages with WebGL 2 which uses Transform Feedback).
  20018. *
  20019. * @type {?Array<Object>}
  20020. */
  20021. this.attributes = attributes;
  20022. /**
  20023. * How often the programmable stage is currently in use.
  20024. *
  20025. * @type {number}
  20026. * @default 0
  20027. */
  20028. this.usedTimes = 0;
  20029. }
  20030. }
  20031. /**
  20032. * This renderer module manages the pipelines of the renderer.
  20033. *
  20034. * @private
  20035. * @augments DataMap
  20036. */
  20037. class Pipelines extends DataMap {
  20038. /**
  20039. * Constructs a new pipeline management component.
  20040. *
  20041. * @param {Backend} backend - The renderer's backend.
  20042. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20043. */
  20044. constructor( backend, nodes ) {
  20045. super();
  20046. /**
  20047. * The renderer's backend.
  20048. *
  20049. * @type {Backend}
  20050. */
  20051. this.backend = backend;
  20052. /**
  20053. * Renderer component for managing nodes related logic.
  20054. *
  20055. * @type {Nodes}
  20056. */
  20057. this.nodes = nodes;
  20058. /**
  20059. * A references to the bindings management component.
  20060. * This reference will be set inside the `Bindings`
  20061. * constructor.
  20062. *
  20063. * @type {?Bindings}
  20064. * @default null
  20065. */
  20066. this.bindings = null;
  20067. /**
  20068. * Internal cache for maintaining pipelines.
  20069. * The key of the map is a cache key, the value the pipeline.
  20070. *
  20071. * @type {Map<string,Pipeline>}
  20072. */
  20073. this.caches = new Map();
  20074. /**
  20075. * This dictionary maintains for each shader stage type (vertex,
  20076. * fragment and compute) the programmable stage objects which
  20077. * represent the actual shader code.
  20078. *
  20079. * @type {Object<string,Map>}
  20080. */
  20081. this.programs = {
  20082. vertex: new Map(),
  20083. fragment: new Map(),
  20084. compute: new Map()
  20085. };
  20086. }
  20087. /**
  20088. * Returns a compute pipeline for the given compute node.
  20089. *
  20090. * @param {Node} computeNode - The compute node.
  20091. * @param {Array<BindGroup>} bindings - The bindings.
  20092. * @return {ComputePipeline} The compute pipeline.
  20093. */
  20094. getForCompute( computeNode, bindings ) {
  20095. const { backend } = this;
  20096. const data = this.get( computeNode );
  20097. if ( this._needsComputeUpdate( computeNode ) ) {
  20098. const previousPipeline = data.pipeline;
  20099. if ( previousPipeline ) {
  20100. previousPipeline.usedTimes --;
  20101. previousPipeline.computeProgram.usedTimes --;
  20102. }
  20103. // get shader
  20104. const nodeBuilderState = this.nodes.getForCompute( computeNode );
  20105. // programmable stage
  20106. let stageCompute = this.programs.compute.get( nodeBuilderState.computeShader );
  20107. if ( stageCompute === undefined ) {
  20108. if ( previousPipeline && previousPipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.computeProgram );
  20109. stageCompute = new ProgrammableStage( nodeBuilderState.computeShader, 'compute', computeNode.name, nodeBuilderState.transforms, nodeBuilderState.nodeAttributes );
  20110. this.programs.compute.set( nodeBuilderState.computeShader, stageCompute );
  20111. backend.createProgram( stageCompute );
  20112. }
  20113. // determine compute pipeline
  20114. const cacheKey = this._getComputeCacheKey( computeNode, stageCompute );
  20115. let pipeline = this.caches.get( cacheKey );
  20116. if ( pipeline === undefined ) {
  20117. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  20118. pipeline = this._getComputePipeline( computeNode, stageCompute, cacheKey, bindings );
  20119. }
  20120. // keep track of all used times
  20121. pipeline.usedTimes ++;
  20122. stageCompute.usedTimes ++;
  20123. //
  20124. data.version = computeNode.version;
  20125. data.pipeline = pipeline;
  20126. }
  20127. return data.pipeline;
  20128. }
  20129. /**
  20130. * Returns a render pipeline for the given render object.
  20131. *
  20132. * @param {RenderObject} renderObject - The render object.
  20133. * @param {?Array<Promise>} [promises=null] - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  20134. * @return {RenderPipeline} The render pipeline.
  20135. */
  20136. getForRender( renderObject, promises = null ) {
  20137. const { backend } = this;
  20138. const data = this.get( renderObject );
  20139. if ( this._needsRenderUpdate( renderObject ) ) {
  20140. const previousPipeline = data.pipeline;
  20141. if ( previousPipeline ) {
  20142. previousPipeline.usedTimes --;
  20143. previousPipeline.vertexProgram.usedTimes --;
  20144. previousPipeline.fragmentProgram.usedTimes --;
  20145. }
  20146. // get shader
  20147. const nodeBuilderState = renderObject.getNodeBuilderState();
  20148. const name = renderObject.material ? renderObject.material.name : '';
  20149. // programmable stages
  20150. let stageVertex = this.programs.vertex.get( nodeBuilderState.vertexShader );
  20151. if ( stageVertex === undefined ) {
  20152. if ( previousPipeline && previousPipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.vertexProgram );
  20153. stageVertex = new ProgrammableStage( nodeBuilderState.vertexShader, 'vertex', name );
  20154. this.programs.vertex.set( nodeBuilderState.vertexShader, stageVertex );
  20155. backend.createProgram( stageVertex );
  20156. }
  20157. let stageFragment = this.programs.fragment.get( nodeBuilderState.fragmentShader );
  20158. if ( stageFragment === undefined ) {
  20159. if ( previousPipeline && previousPipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( previousPipeline.fragmentProgram );
  20160. stageFragment = new ProgrammableStage( nodeBuilderState.fragmentShader, 'fragment', name );
  20161. this.programs.fragment.set( nodeBuilderState.fragmentShader, stageFragment );
  20162. backend.createProgram( stageFragment );
  20163. }
  20164. // determine render pipeline
  20165. const cacheKey = this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  20166. let pipeline = this.caches.get( cacheKey );
  20167. if ( pipeline === undefined ) {
  20168. if ( previousPipeline && previousPipeline.usedTimes === 0 ) this._releasePipeline( previousPipeline );
  20169. pipeline = this._getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises );
  20170. } else {
  20171. renderObject.pipeline = pipeline;
  20172. }
  20173. // keep track of all used times
  20174. pipeline.usedTimes ++;
  20175. stageVertex.usedTimes ++;
  20176. stageFragment.usedTimes ++;
  20177. //
  20178. data.pipeline = pipeline;
  20179. }
  20180. return data.pipeline;
  20181. }
  20182. /**
  20183. * Deletes the pipeline for the given render object.
  20184. *
  20185. * @param {RenderObject} object - The render object.
  20186. * @return {?Object} The deleted dictionary.
  20187. */
  20188. delete( object ) {
  20189. const pipeline = this.get( object ).pipeline;
  20190. if ( pipeline ) {
  20191. // pipeline
  20192. pipeline.usedTimes --;
  20193. if ( pipeline.usedTimes === 0 ) this._releasePipeline( pipeline );
  20194. // programs
  20195. if ( pipeline.isComputePipeline ) {
  20196. pipeline.computeProgram.usedTimes --;
  20197. if ( pipeline.computeProgram.usedTimes === 0 ) this._releaseProgram( pipeline.computeProgram );
  20198. } else {
  20199. pipeline.fragmentProgram.usedTimes --;
  20200. pipeline.vertexProgram.usedTimes --;
  20201. if ( pipeline.vertexProgram.usedTimes === 0 ) this._releaseProgram( pipeline.vertexProgram );
  20202. if ( pipeline.fragmentProgram.usedTimes === 0 ) this._releaseProgram( pipeline.fragmentProgram );
  20203. }
  20204. }
  20205. return super.delete( object );
  20206. }
  20207. /**
  20208. * Frees internal resources.
  20209. */
  20210. dispose() {
  20211. super.dispose();
  20212. this.caches = new Map();
  20213. this.programs = {
  20214. vertex: new Map(),
  20215. fragment: new Map(),
  20216. compute: new Map()
  20217. };
  20218. }
  20219. /**
  20220. * Updates the pipeline for the given render object.
  20221. *
  20222. * @param {RenderObject} renderObject - The render object.
  20223. */
  20224. updateForRender( renderObject ) {
  20225. this.getForRender( renderObject );
  20226. }
  20227. /**
  20228. * Returns a compute pipeline for the given parameters.
  20229. *
  20230. * @private
  20231. * @param {Node} computeNode - The compute node.
  20232. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  20233. * @param {string} cacheKey - The cache key.
  20234. * @param {Array<BindGroup>} bindings - The bindings.
  20235. * @return {ComputePipeline} The compute pipeline.
  20236. */
  20237. _getComputePipeline( computeNode, stageCompute, cacheKey, bindings ) {
  20238. // check for existing pipeline
  20239. cacheKey = cacheKey || this._getComputeCacheKey( computeNode, stageCompute );
  20240. let pipeline = this.caches.get( cacheKey );
  20241. if ( pipeline === undefined ) {
  20242. pipeline = new ComputePipeline( cacheKey, stageCompute );
  20243. this.caches.set( cacheKey, pipeline );
  20244. this.backend.createComputePipeline( pipeline, bindings );
  20245. }
  20246. return pipeline;
  20247. }
  20248. /**
  20249. * Returns a render pipeline for the given parameters.
  20250. *
  20251. * @private
  20252. * @param {RenderObject} renderObject - The render object.
  20253. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  20254. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  20255. * @param {string} cacheKey - The cache key.
  20256. * @param {?Array<Promise>} promises - An array of compilation promises which is only relevant in context of `Renderer.compileAsync()`.
  20257. * @return {ComputePipeline} The compute pipeline.
  20258. */
  20259. _getRenderPipeline( renderObject, stageVertex, stageFragment, cacheKey, promises ) {
  20260. // check for existing pipeline
  20261. cacheKey = cacheKey || this._getRenderCacheKey( renderObject, stageVertex, stageFragment );
  20262. let pipeline = this.caches.get( cacheKey );
  20263. if ( pipeline === undefined ) {
  20264. pipeline = new RenderPipeline( cacheKey, stageVertex, stageFragment );
  20265. this.caches.set( cacheKey, pipeline );
  20266. renderObject.pipeline = pipeline;
  20267. // The `promises` array is `null` by default and only set to an empty array when
  20268. // `Renderer.compileAsync()` is used. The next call actually fills the array with
  20269. // pending promises that resolve when the render pipelines are ready for rendering.
  20270. this.backend.createRenderPipeline( renderObject, promises );
  20271. }
  20272. return pipeline;
  20273. }
  20274. /**
  20275. * Computes a cache key representing a compute pipeline.
  20276. *
  20277. * @private
  20278. * @param {Node} computeNode - The compute node.
  20279. * @param {ProgrammableStage} stageCompute - The programmable stage representing the compute shader.
  20280. * @return {string} The cache key.
  20281. */
  20282. _getComputeCacheKey( computeNode, stageCompute ) {
  20283. return computeNode.id + ',' + stageCompute.id;
  20284. }
  20285. /**
  20286. * Computes a cache key representing a render pipeline.
  20287. *
  20288. * @private
  20289. * @param {RenderObject} renderObject - The render object.
  20290. * @param {ProgrammableStage} stageVertex - The programmable stage representing the vertex shader.
  20291. * @param {ProgrammableStage} stageFragment - The programmable stage representing the fragment shader.
  20292. * @return {string} The cache key.
  20293. */
  20294. _getRenderCacheKey( renderObject, stageVertex, stageFragment ) {
  20295. return stageVertex.id + ',' + stageFragment.id + ',' + this.backend.getRenderCacheKey( renderObject );
  20296. }
  20297. /**
  20298. * Releases the given pipeline.
  20299. *
  20300. * @private
  20301. * @param {Pipeline} pipeline - The pipeline to release.
  20302. */
  20303. _releasePipeline( pipeline ) {
  20304. this.caches.delete( pipeline.cacheKey );
  20305. }
  20306. /**
  20307. * Releases the shader program.
  20308. *
  20309. * @private
  20310. * @param {Object} program - The shader program to release.
  20311. */
  20312. _releaseProgram( program ) {
  20313. const code = program.code;
  20314. const stage = program.stage;
  20315. this.programs[ stage ].delete( code );
  20316. }
  20317. /**
  20318. * Returns `true` if the compute pipeline for the given compute node requires an update.
  20319. *
  20320. * @private
  20321. * @param {Node} computeNode - The compute node.
  20322. * @return {boolean} Whether the compute pipeline for the given compute node requires an update or not.
  20323. */
  20324. _needsComputeUpdate( computeNode ) {
  20325. const data = this.get( computeNode );
  20326. return data.pipeline === undefined || data.version !== computeNode.version;
  20327. }
  20328. /**
  20329. * Returns `true` if the render pipeline for the given render object requires an update.
  20330. *
  20331. * @private
  20332. * @param {RenderObject} renderObject - The render object.
  20333. * @return {boolean} Whether the render object for the given render object requires an update or not.
  20334. */
  20335. _needsRenderUpdate( renderObject ) {
  20336. const data = this.get( renderObject );
  20337. return data.pipeline === undefined || this.backend.needsRenderUpdate( renderObject );
  20338. }
  20339. }
  20340. /**
  20341. * This renderer module manages the bindings of the renderer.
  20342. *
  20343. * @private
  20344. * @augments DataMap
  20345. */
  20346. class Bindings extends DataMap {
  20347. /**
  20348. * Constructs a new bindings management component.
  20349. *
  20350. * @param {Backend} backend - The renderer's backend.
  20351. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  20352. * @param {Textures} textures - Renderer component for managing textures.
  20353. * @param {Attributes} attributes - Renderer component for managing attributes.
  20354. * @param {Pipelines} pipelines - Renderer component for managing pipelines.
  20355. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  20356. */
  20357. constructor( backend, nodes, textures, attributes, pipelines, info ) {
  20358. super();
  20359. /**
  20360. * The renderer's backend.
  20361. *
  20362. * @type {Backend}
  20363. */
  20364. this.backend = backend;
  20365. /**
  20366. * Renderer component for managing textures.
  20367. *
  20368. * @type {Textures}
  20369. */
  20370. this.textures = textures;
  20371. /**
  20372. * Renderer component for managing pipelines.
  20373. *
  20374. * @type {Pipelines}
  20375. */
  20376. this.pipelines = pipelines;
  20377. /**
  20378. * Renderer component for managing attributes.
  20379. *
  20380. * @type {Attributes}
  20381. */
  20382. this.attributes = attributes;
  20383. /**
  20384. * Renderer component for managing nodes related logic.
  20385. *
  20386. * @type {Nodes}
  20387. */
  20388. this.nodes = nodes;
  20389. /**
  20390. * Renderer component for managing metrics and monitoring data.
  20391. *
  20392. * @type {Info}
  20393. */
  20394. this.info = info;
  20395. this.pipelines.bindings = this; // assign bindings to pipelines
  20396. }
  20397. /**
  20398. * Returns the bind groups for the given render object.
  20399. *
  20400. * @param {RenderObject} renderObject - The render object.
  20401. * @return {Array<BindGroup>} The bind groups.
  20402. */
  20403. getForRender( renderObject ) {
  20404. const bindings = renderObject.getBindings();
  20405. for ( const bindGroup of bindings ) {
  20406. const groupData = this.get( bindGroup );
  20407. if ( groupData.bindGroup === undefined ) {
  20408. // each object defines an array of bindings (ubos, textures, samplers etc.)
  20409. this._init( bindGroup );
  20410. this.backend.createBindings( bindGroup, bindings, 0 );
  20411. groupData.bindGroup = bindGroup;
  20412. }
  20413. }
  20414. return bindings;
  20415. }
  20416. /**
  20417. * Returns the bind groups for the given compute node.
  20418. *
  20419. * @param {Node} computeNode - The compute node.
  20420. * @return {Array<BindGroup>} The bind groups.
  20421. */
  20422. getForCompute( computeNode ) {
  20423. const bindings = this.nodes.getForCompute( computeNode ).bindings;
  20424. for ( const bindGroup of bindings ) {
  20425. const groupData = this.get( bindGroup );
  20426. if ( groupData.bindGroup === undefined ) {
  20427. this._init( bindGroup );
  20428. this.backend.createBindings( bindGroup, bindings, 0 );
  20429. groupData.bindGroup = bindGroup;
  20430. }
  20431. }
  20432. return bindings;
  20433. }
  20434. /**
  20435. * Updates the bindings for the given compute node.
  20436. *
  20437. * @param {Node} computeNode - The compute node.
  20438. */
  20439. updateForCompute( computeNode ) {
  20440. this._updateBindings( this.getForCompute( computeNode ) );
  20441. }
  20442. /**
  20443. * Updates the bindings for the given render object.
  20444. *
  20445. * @param {RenderObject} renderObject - The render object.
  20446. */
  20447. updateForRender( renderObject ) {
  20448. this._updateBindings( this.getForRender( renderObject ) );
  20449. }
  20450. /**
  20451. * Updates the given array of bindings.
  20452. *
  20453. * @param {Array<BindGroup>} bindings - The bind groups.
  20454. */
  20455. _updateBindings( bindings ) {
  20456. for ( const bindGroup of bindings ) {
  20457. this._update( bindGroup, bindings );
  20458. }
  20459. }
  20460. /**
  20461. * Initializes the given bind group.
  20462. *
  20463. * @param {BindGroup} bindGroup - The bind group to initialize.
  20464. */
  20465. _init( bindGroup ) {
  20466. for ( const binding of bindGroup.bindings ) {
  20467. if ( binding.isSampledTexture ) {
  20468. this.textures.updateTexture( binding.texture );
  20469. } else if ( binding.isStorageBuffer ) {
  20470. const attribute = binding.attribute;
  20471. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  20472. this.attributes.update( attribute, attributeType );
  20473. }
  20474. }
  20475. }
  20476. /**
  20477. * Updates the given bind group.
  20478. *
  20479. * @param {BindGroup} bindGroup - The bind group to update.
  20480. * @param {Array<BindGroup>} bindings - The bind groups.
  20481. */
  20482. _update( bindGroup, bindings ) {
  20483. const { backend } = this;
  20484. let needsBindingsUpdate = false;
  20485. let cacheBindings = true;
  20486. let cacheIndex = 0;
  20487. let version = 0;
  20488. // iterate over all bindings and check if buffer updates or a new binding group is required
  20489. for ( const binding of bindGroup.bindings ) {
  20490. if ( binding.isNodeUniformsGroup ) {
  20491. const updated = this.nodes.updateGroup( binding );
  20492. // every uniforms group is a uniform buffer. So if no update is required,
  20493. // we move one with the next binding. Otherwise the next if block will update the group.
  20494. if ( updated === false ) continue;
  20495. }
  20496. if ( binding.isStorageBuffer ) {
  20497. const attribute = binding.attribute;
  20498. const attributeType = attribute.isIndirectStorageBufferAttribute ? AttributeType.INDIRECT : AttributeType.STORAGE;
  20499. this.attributes.update( attribute, attributeType );
  20500. }
  20501. if ( binding.isUniformBuffer ) {
  20502. const updated = binding.update();
  20503. if ( updated ) {
  20504. backend.updateBinding( binding );
  20505. }
  20506. } else if ( binding.isSampler ) {
  20507. binding.update();
  20508. } else if ( binding.isSampledTexture ) {
  20509. const texturesTextureData = this.textures.get( binding.texture );
  20510. if ( binding.needsBindingsUpdate( texturesTextureData.generation ) ) needsBindingsUpdate = true;
  20511. const updated = binding.update();
  20512. const texture = binding.texture;
  20513. if ( updated ) {
  20514. this.textures.updateTexture( texture );
  20515. }
  20516. const textureData = backend.get( texture );
  20517. if ( textureData.externalTexture !== undefined || texturesTextureData.isDefaultTexture ) {
  20518. cacheBindings = false;
  20519. } else {
  20520. cacheIndex = cacheIndex * 10 + texture.id;
  20521. version += texture.version;
  20522. }
  20523. if ( backend.isWebGPUBackend === true && textureData.texture === undefined && textureData.externalTexture === undefined ) {
  20524. // TODO: Remove this once we found why updated === false isn't bound to a texture in the WebGPU backend
  20525. console.error( 'Bindings._update: binding should be available:', binding, updated, texture, binding.textureNode.value, needsBindingsUpdate );
  20526. this.textures.updateTexture( texture );
  20527. needsBindingsUpdate = true;
  20528. }
  20529. if ( texture.isStorageTexture === true ) {
  20530. const textureData = this.get( texture );
  20531. if ( binding.store === true ) {
  20532. textureData.needsMipmap = true;
  20533. } else if ( this.textures.needsMipmaps( texture ) && textureData.needsMipmap === true ) {
  20534. this.backend.generateMipmaps( texture );
  20535. textureData.needsMipmap = false;
  20536. }
  20537. }
  20538. }
  20539. }
  20540. if ( needsBindingsUpdate === true ) {
  20541. this.backend.updateBindings( bindGroup, bindings, cacheBindings ? cacheIndex : 0, version );
  20542. }
  20543. }
  20544. }
  20545. /**
  20546. * Default sorting function for opaque render items.
  20547. *
  20548. * @private
  20549. * @function
  20550. * @param {Object} a - The first render item.
  20551. * @param {Object} b - The second render item.
  20552. * @return {number} A numeric value which defines the sort order.
  20553. */
  20554. function painterSortStable( a, b ) {
  20555. if ( a.groupOrder !== b.groupOrder ) {
  20556. return a.groupOrder - b.groupOrder;
  20557. } else if ( a.renderOrder !== b.renderOrder ) {
  20558. return a.renderOrder - b.renderOrder;
  20559. } else if ( a.z !== b.z ) {
  20560. return a.z - b.z;
  20561. } else {
  20562. return a.id - b.id;
  20563. }
  20564. }
  20565. /**
  20566. * Default sorting function for transparent render items.
  20567. *
  20568. * @private
  20569. * @function
  20570. * @param {Object} a - The first render item.
  20571. * @param {Object} b - The second render item.
  20572. * @return {number} A numeric value which defines the sort order.
  20573. */
  20574. function reversePainterSortStable( a, b ) {
  20575. if ( a.groupOrder !== b.groupOrder ) {
  20576. return a.groupOrder - b.groupOrder;
  20577. } else if ( a.renderOrder !== b.renderOrder ) {
  20578. return a.renderOrder - b.renderOrder;
  20579. } else if ( a.z !== b.z ) {
  20580. return b.z - a.z;
  20581. } else {
  20582. return a.id - b.id;
  20583. }
  20584. }
  20585. /**
  20586. * Returns `true` if the given transparent material requires a double pass.
  20587. *
  20588. * @private
  20589. * @function
  20590. * @param {Material} material - The transparent material.
  20591. * @return {boolean} Whether the given material requires a double pass or not.
  20592. */
  20593. function needsDoublePass( material ) {
  20594. const hasTransmission = material.transmission > 0 || material.transmissionNode;
  20595. return hasTransmission && material.side === DoubleSide && material.forceSinglePass === false;
  20596. }
  20597. /**
  20598. * When the renderer analyzes the scene at the beginning of a render call,
  20599. * it stores 3D object for further processing in render lists. Depending on the
  20600. * properties of a 3D objects (like their transformation or material state), the
  20601. * objects are maintained in ordered lists for the actual rendering.
  20602. *
  20603. * Render lists are unique per scene and camera combination.
  20604. *
  20605. * @private
  20606. * @augments Pipeline
  20607. */
  20608. class RenderList {
  20609. /**
  20610. * Constructs a render list.
  20611. *
  20612. * @param {Lighting} lighting - The lighting management component.
  20613. * @param {Scene} scene - The scene.
  20614. * @param {Camera} camera - The camera the scene is rendered with.
  20615. */
  20616. constructor( lighting, scene, camera ) {
  20617. /**
  20618. * 3D objects are transformed into render items and stored in this array.
  20619. *
  20620. * @type {Array<Object>}
  20621. */
  20622. this.renderItems = [];
  20623. /**
  20624. * The current render items index.
  20625. *
  20626. * @type {number}
  20627. * @default 0
  20628. */
  20629. this.renderItemsIndex = 0;
  20630. /**
  20631. * A list with opaque render items.
  20632. *
  20633. * @type {Array<Object>}
  20634. */
  20635. this.opaque = [];
  20636. /**
  20637. * A list with transparent render items which require
  20638. * double pass rendering (e.g. transmissive objects).
  20639. *
  20640. * @type {Array<Object>}
  20641. */
  20642. this.transparentDoublePass = [];
  20643. /**
  20644. * A list with transparent render items.
  20645. *
  20646. * @type {Array<Object>}
  20647. */
  20648. this.transparent = [];
  20649. /**
  20650. * A list with transparent render bundle data.
  20651. *
  20652. * @type {Array<Object>}
  20653. */
  20654. this.bundles = [];
  20655. /**
  20656. * The render list's lights node. This node is later
  20657. * relevant for the actual analytical light nodes which
  20658. * compute the scene's lighting in the shader.
  20659. *
  20660. * @type {LightsNode}
  20661. */
  20662. this.lightsNode = lighting.getNode( scene, camera );
  20663. /**
  20664. * The scene's lights stored in an array. This array
  20665. * is used to setup the lights node.
  20666. *
  20667. * @type {Array<Light>}
  20668. */
  20669. this.lightsArray = [];
  20670. /**
  20671. * The scene.
  20672. *
  20673. * @type {Scene}
  20674. */
  20675. this.scene = scene;
  20676. /**
  20677. * The camera the scene is rendered with.
  20678. *
  20679. * @type {Camera}
  20680. */
  20681. this.camera = camera;
  20682. /**
  20683. * How many objects perform occlusion query tests.
  20684. *
  20685. * @type {number}
  20686. * @default 0
  20687. */
  20688. this.occlusionQueryCount = 0;
  20689. }
  20690. /**
  20691. * This method is called right at the beginning of a render call
  20692. * before the scene is analyzed. It prepares the internal data
  20693. * structures for the upcoming render lists generation.
  20694. *
  20695. * @return {RenderList} A reference to this render list.
  20696. */
  20697. begin() {
  20698. this.renderItemsIndex = 0;
  20699. this.opaque.length = 0;
  20700. this.transparentDoublePass.length = 0;
  20701. this.transparent.length = 0;
  20702. this.bundles.length = 0;
  20703. this.lightsArray.length = 0;
  20704. this.occlusionQueryCount = 0;
  20705. return this;
  20706. }
  20707. /**
  20708. * Returns a render item for the giving render item state. The state is defined
  20709. * by a series of object-related parameters.
  20710. *
  20711. * The method avoids object creation by holding render items and reusing them in
  20712. * subsequent render calls (just with different property values).
  20713. *
  20714. * @param {Object3D} object - The 3D object.
  20715. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20716. * @param {Material} material - The 3D object's material.
  20717. * @param {number} groupOrder - The current group order.
  20718. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20719. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20720. * @param {ClippingContext} clippingContext - The current clipping context.
  20721. * @return {Object} The render item.
  20722. */
  20723. getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20724. let renderItem = this.renderItems[ this.renderItemsIndex ];
  20725. if ( renderItem === undefined ) {
  20726. renderItem = {
  20727. id: object.id,
  20728. object: object,
  20729. geometry: geometry,
  20730. material: material,
  20731. groupOrder: groupOrder,
  20732. renderOrder: object.renderOrder,
  20733. z: z,
  20734. group: group,
  20735. clippingContext: clippingContext
  20736. };
  20737. this.renderItems[ this.renderItemsIndex ] = renderItem;
  20738. } else {
  20739. renderItem.id = object.id;
  20740. renderItem.object = object;
  20741. renderItem.geometry = geometry;
  20742. renderItem.material = material;
  20743. renderItem.groupOrder = groupOrder;
  20744. renderItem.renderOrder = object.renderOrder;
  20745. renderItem.z = z;
  20746. renderItem.group = group;
  20747. renderItem.clippingContext = clippingContext;
  20748. }
  20749. this.renderItemsIndex ++;
  20750. return renderItem;
  20751. }
  20752. /**
  20753. * Pushes the given object as a render item to the internal render lists.
  20754. * The selected lists depend on the object properties.
  20755. *
  20756. * @param {Object3D} object - The 3D object.
  20757. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20758. * @param {Material} material - The 3D object's material.
  20759. * @param {number} groupOrder - The current group order.
  20760. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20761. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20762. * @param {ClippingContext} clippingContext - The current clipping context.
  20763. */
  20764. push( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20765. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  20766. if ( object.occlusionTest === true ) this.occlusionQueryCount ++;
  20767. if ( material.transparent === true || material.transmission > 0 ) {
  20768. if ( needsDoublePass( material ) ) this.transparentDoublePass.push( renderItem );
  20769. this.transparent.push( renderItem );
  20770. } else {
  20771. this.opaque.push( renderItem );
  20772. }
  20773. }
  20774. /**
  20775. * Inserts the given object as a render item at the start of the internal render lists.
  20776. * The selected lists depend on the object properties.
  20777. *
  20778. * @param {Object3D} object - The 3D object.
  20779. * @param {BufferGeometry} geometry - The 3D object's geometry.
  20780. * @param {Material} material - The 3D object's material.
  20781. * @param {number} groupOrder - The current group order.
  20782. * @param {number} z - Th 3D object's depth value (z value in clip space).
  20783. * @param {?number} group - {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  20784. * @param {ClippingContext} clippingContext - The current clipping context.
  20785. */
  20786. unshift( object, geometry, material, groupOrder, z, group, clippingContext ) {
  20787. const renderItem = this.getNextRenderItem( object, geometry, material, groupOrder, z, group, clippingContext );
  20788. if ( material.transparent === true || material.transmission > 0 ) {
  20789. if ( needsDoublePass( material ) ) this.transparentDoublePass.unshift( renderItem );
  20790. this.transparent.unshift( renderItem );
  20791. } else {
  20792. this.opaque.unshift( renderItem );
  20793. }
  20794. }
  20795. /**
  20796. * Pushes render bundle group data into the render list.
  20797. *
  20798. * @param {Object} group - Bundle group data.
  20799. */
  20800. pushBundle( group ) {
  20801. this.bundles.push( group );
  20802. }
  20803. /**
  20804. * Pushes a light into the render list.
  20805. *
  20806. * @param {Light} light - The light.
  20807. */
  20808. pushLight( light ) {
  20809. this.lightsArray.push( light );
  20810. }
  20811. /**
  20812. * Sorts the internal render lists.
  20813. *
  20814. * @param {?function(any, any): number} customOpaqueSort - A custom sort function for opaque objects.
  20815. * @param {?function(any, any): number} customTransparentSort - A custom sort function for transparent objects.
  20816. */
  20817. sort( customOpaqueSort, customTransparentSort ) {
  20818. if ( this.opaque.length > 1 ) this.opaque.sort( customOpaqueSort || painterSortStable );
  20819. if ( this.transparentDoublePass.length > 1 ) this.transparentDoublePass.sort( customTransparentSort || reversePainterSortStable );
  20820. if ( this.transparent.length > 1 ) this.transparent.sort( customTransparentSort || reversePainterSortStable );
  20821. }
  20822. /**
  20823. * This method performs finalizing tasks right after the render lists
  20824. * have been generated.
  20825. */
  20826. finish() {
  20827. // update lights
  20828. this.lightsNode.setLights( this.lightsArray );
  20829. // Clear references from inactive renderItems in the list
  20830. for ( let i = this.renderItemsIndex, il = this.renderItems.length; i < il; i ++ ) {
  20831. const renderItem = this.renderItems[ i ];
  20832. if ( renderItem.id === null ) break;
  20833. renderItem.id = null;
  20834. renderItem.object = null;
  20835. renderItem.geometry = null;
  20836. renderItem.material = null;
  20837. renderItem.groupOrder = null;
  20838. renderItem.renderOrder = null;
  20839. renderItem.z = null;
  20840. renderItem.group = null;
  20841. renderItem.clippingContext = null;
  20842. }
  20843. }
  20844. }
  20845. const _chainKeys$4 = [];
  20846. /**
  20847. * This renderer module manages the render lists which are unique
  20848. * per scene and camera combination.
  20849. *
  20850. * @private
  20851. */
  20852. class RenderLists {
  20853. /**
  20854. * Constructs a render lists management component.
  20855. *
  20856. * @param {Lighting} lighting - The lighting management component.
  20857. */
  20858. constructor( lighting ) {
  20859. /**
  20860. * The lighting management component.
  20861. *
  20862. * @type {Lighting}
  20863. */
  20864. this.lighting = lighting;
  20865. /**
  20866. * The internal chain map which holds the render lists.
  20867. *
  20868. * @type {ChainMap}
  20869. */
  20870. this.lists = new ChainMap();
  20871. }
  20872. /**
  20873. * Returns a render list for the given scene and camera.
  20874. *
  20875. * @param {Scene} scene - The scene.
  20876. * @param {Camera} camera - The camera.
  20877. * @return {RenderList} The render list.
  20878. */
  20879. get( scene, camera ) {
  20880. const lists = this.lists;
  20881. _chainKeys$4[ 0 ] = scene;
  20882. _chainKeys$4[ 1 ] = camera;
  20883. let list = lists.get( _chainKeys$4 );
  20884. if ( list === undefined ) {
  20885. list = new RenderList( this.lighting, scene, camera );
  20886. lists.set( _chainKeys$4, list );
  20887. }
  20888. _chainKeys$4.length = 0;
  20889. return list;
  20890. }
  20891. /**
  20892. * Frees all internal resources.
  20893. */
  20894. dispose() {
  20895. this.lists = new ChainMap();
  20896. }
  20897. }
  20898. let _id$7 = 0;
  20899. /**
  20900. * Any render or compute command is executed in a specific context that defines
  20901. * the state of the renderer and its backend. Typical examples for such context
  20902. * data are the current clear values or data from the active framebuffer. This
  20903. * module is used to represent these contexts as objects.
  20904. *
  20905. * @private
  20906. */
  20907. class RenderContext {
  20908. /**
  20909. * Constructs a new render context.
  20910. */
  20911. constructor() {
  20912. /**
  20913. * The context's ID.
  20914. *
  20915. * @type {number}
  20916. */
  20917. this.id = _id$7 ++;
  20918. /**
  20919. * Whether the current active framebuffer has a color attachment.
  20920. *
  20921. * @type {boolean}
  20922. * @default true
  20923. */
  20924. this.color = true;
  20925. /**
  20926. * Whether the color attachment should be cleared or not.
  20927. *
  20928. * @type {boolean}
  20929. * @default true
  20930. */
  20931. this.clearColor = true;
  20932. /**
  20933. * The clear color value.
  20934. *
  20935. * @type {Object}
  20936. * @default true
  20937. */
  20938. this.clearColorValue = { r: 0, g: 0, b: 0, a: 1 };
  20939. /**
  20940. * Whether the current active framebuffer has a depth attachment.
  20941. *
  20942. * @type {boolean}
  20943. * @default true
  20944. */
  20945. this.depth = true;
  20946. /**
  20947. * Whether the depth attachment should be cleared or not.
  20948. *
  20949. * @type {boolean}
  20950. * @default true
  20951. */
  20952. this.clearDepth = true;
  20953. /**
  20954. * The clear depth value.
  20955. *
  20956. * @type {number}
  20957. * @default 1
  20958. */
  20959. this.clearDepthValue = 1;
  20960. /**
  20961. * Whether the current active framebuffer has a stencil attachment.
  20962. *
  20963. * @type {boolean}
  20964. * @default false
  20965. */
  20966. this.stencil = false;
  20967. /**
  20968. * Whether the stencil attachment should be cleared or not.
  20969. *
  20970. * @type {boolean}
  20971. * @default true
  20972. */
  20973. this.clearStencil = true;
  20974. /**
  20975. * The clear stencil value.
  20976. *
  20977. * @type {number}
  20978. * @default 1
  20979. */
  20980. this.clearStencilValue = 1;
  20981. /**
  20982. * By default the viewport encloses the entire framebuffer If a smaller
  20983. * viewport is manually defined, this property is to `true` by the renderer.
  20984. *
  20985. * @type {boolean}
  20986. * @default false
  20987. */
  20988. this.viewport = false;
  20989. /**
  20990. * The viewport value. This value is in physical pixels meaning it incorporates
  20991. * the renderer's pixel ratio. The viewport property of render targets or
  20992. * the renderer is in logical pixels.
  20993. *
  20994. * @type {Vector4}
  20995. */
  20996. this.viewportValue = new Vector4();
  20997. /**
  20998. * When the scissor test is active and scissor rectangle smaller than the
  20999. * framebuffers dimensions, this property is to `true` by the renderer.
  21000. *
  21001. * @type {boolean}
  21002. * @default false
  21003. */
  21004. this.scissor = false;
  21005. /**
  21006. * The scissor rectangle.
  21007. *
  21008. * @type {Vector4}
  21009. */
  21010. this.scissorValue = new Vector4();
  21011. /**
  21012. * The active render target.
  21013. *
  21014. * @type {?RenderTarget}
  21015. * @default null
  21016. */
  21017. this.renderTarget = null;
  21018. /**
  21019. * The textures of the active render target.
  21020. * `null` when no render target is set.
  21021. *
  21022. * @type {?Array<Texture>}
  21023. * @default null
  21024. */
  21025. this.textures = null;
  21026. /**
  21027. * The depth texture of the active render target.
  21028. * `null` when no render target is set.
  21029. *
  21030. * @type {?DepthTexture}
  21031. * @default null
  21032. */
  21033. this.depthTexture = null;
  21034. /**
  21035. * The active cube face.
  21036. *
  21037. * @type {number}
  21038. * @default 0
  21039. */
  21040. this.activeCubeFace = 0;
  21041. /**
  21042. * The active mipmap level.
  21043. *
  21044. * @type {number}
  21045. * @default 0
  21046. */
  21047. this.activeMipmapLevel = 0;
  21048. /**
  21049. * The number of MSAA samples. This value is always `1` when
  21050. * MSAA isn't used.
  21051. *
  21052. * @type {number}
  21053. * @default 1
  21054. */
  21055. this.sampleCount = 1;
  21056. /**
  21057. * The active render target's width in physical pixels.
  21058. *
  21059. * @type {number}
  21060. * @default 0
  21061. */
  21062. this.width = 0;
  21063. /**
  21064. * The active render target's height in physical pixels.
  21065. *
  21066. * @type {number}
  21067. * @default 0
  21068. */
  21069. this.height = 0;
  21070. /**
  21071. * The occlusion query count.
  21072. *
  21073. * @type {number}
  21074. * @default 0
  21075. */
  21076. this.occlusionQueryCount = 0;
  21077. /**
  21078. * The current clipping context.
  21079. *
  21080. * @type {?ClippingContext}
  21081. * @default null
  21082. */
  21083. this.clippingContext = null;
  21084. /**
  21085. * This flag can be used for type testing.
  21086. *
  21087. * @type {boolean}
  21088. * @readonly
  21089. * @default true
  21090. */
  21091. this.isRenderContext = true;
  21092. }
  21093. /**
  21094. * Returns the cache key of this render context.
  21095. *
  21096. * @return {number} The cache key.
  21097. */
  21098. getCacheKey() {
  21099. return getCacheKey( this );
  21100. }
  21101. }
  21102. /**
  21103. * Computes a cache key for the given render context. This key
  21104. * should identify the render target state so it is possible to
  21105. * configure the correct attachments in the respective backend.
  21106. *
  21107. * @param {RenderContext} renderContext - The render context.
  21108. * @return {number} The cache key.
  21109. */
  21110. function getCacheKey( renderContext ) {
  21111. const { textures, activeCubeFace } = renderContext;
  21112. const values = [ activeCubeFace ];
  21113. for ( const texture of textures ) {
  21114. values.push( texture.id );
  21115. }
  21116. return hashArray( values );
  21117. }
  21118. const _chainKeys$3 = [];
  21119. const _defaultScene = /*@__PURE__*/ new Scene();
  21120. const _defaultCamera = /*@__PURE__*/ new Camera();
  21121. /**
  21122. * This module manages the render contexts of the renderer.
  21123. *
  21124. * @private
  21125. */
  21126. class RenderContexts {
  21127. /**
  21128. * Constructs a new render context management component.
  21129. */
  21130. constructor() {
  21131. /**
  21132. * A dictionary that manages render contexts in chain maps
  21133. * for each attachment state.
  21134. *
  21135. * @type {Object<string,ChainMap>}
  21136. */
  21137. this.chainMaps = {};
  21138. }
  21139. /**
  21140. * Returns a render context for the given scene, camera and render target.
  21141. *
  21142. * @param {Scene} scene - The scene.
  21143. * @param {Camera} camera - The camera that is used to render the scene.
  21144. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  21145. * @return {RenderContext} The render context.
  21146. */
  21147. get( scene, camera, renderTarget = null ) {
  21148. _chainKeys$3[ 0 ] = scene;
  21149. _chainKeys$3[ 1 ] = camera;
  21150. let attachmentState;
  21151. if ( renderTarget === null ) {
  21152. attachmentState = 'default';
  21153. } else {
  21154. const format = renderTarget.texture.format;
  21155. const count = renderTarget.textures.length;
  21156. attachmentState = `${ count }:${ format }:${ renderTarget.samples }:${ renderTarget.depthBuffer }:${ renderTarget.stencilBuffer }`;
  21157. }
  21158. const chainMap = this._getChainMap( attachmentState );
  21159. let renderState = chainMap.get( _chainKeys$3 );
  21160. if ( renderState === undefined ) {
  21161. renderState = new RenderContext();
  21162. chainMap.set( _chainKeys$3, renderState );
  21163. }
  21164. _chainKeys$3.length = 0;
  21165. if ( renderTarget !== null ) renderState.sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  21166. return renderState;
  21167. }
  21168. /**
  21169. * Returns a render context intended for clear operations.
  21170. *
  21171. * @param {?RenderTarget} [renderTarget=null] - The active render target.
  21172. * @return {RenderContext} The render context.
  21173. */
  21174. getForClear( renderTarget = null ) {
  21175. return this.get( _defaultScene, _defaultCamera, renderTarget );
  21176. }
  21177. /**
  21178. * Returns a chain map for the given attachment state.
  21179. *
  21180. * @private
  21181. * @param {string} attachmentState - The attachment state.
  21182. * @return {ChainMap} The chain map.
  21183. */
  21184. _getChainMap( attachmentState ) {
  21185. return this.chainMaps[ attachmentState ] || ( this.chainMaps[ attachmentState ] = new ChainMap() );
  21186. }
  21187. /**
  21188. * Frees internal resources.
  21189. */
  21190. dispose() {
  21191. this.chainMaps = {};
  21192. }
  21193. }
  21194. const _size$3 = /*@__PURE__*/ new Vector3();
  21195. /**
  21196. * This module manages the textures of the renderer.
  21197. *
  21198. * @private
  21199. * @augments DataMap
  21200. */
  21201. class Textures extends DataMap {
  21202. /**
  21203. * Constructs a new texture management component.
  21204. *
  21205. * @param {Renderer} renderer - The renderer.
  21206. * @param {Backend} backend - The renderer's backend.
  21207. * @param {Info} info - Renderer component for managing metrics and monitoring data.
  21208. */
  21209. constructor( renderer, backend, info ) {
  21210. super();
  21211. /**
  21212. * The renderer.
  21213. *
  21214. * @type {Renderer}
  21215. */
  21216. this.renderer = renderer;
  21217. /**
  21218. * The backend.
  21219. *
  21220. * @type {Backend}
  21221. */
  21222. this.backend = backend;
  21223. /**
  21224. * Renderer component for managing metrics and monitoring data.
  21225. *
  21226. * @type {Info}
  21227. */
  21228. this.info = info;
  21229. }
  21230. /**
  21231. * Updates the given render target. Based on the given render target configuration,
  21232. * it updates the texture states representing the attachments of the framebuffer.
  21233. *
  21234. * @param {RenderTarget} renderTarget - The render target to update.
  21235. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  21236. */
  21237. updateRenderTarget( renderTarget, activeMipmapLevel = 0 ) {
  21238. const renderTargetData = this.get( renderTarget );
  21239. const sampleCount = renderTarget.samples === 0 ? 1 : renderTarget.samples;
  21240. const depthTextureMips = renderTargetData.depthTextureMips || ( renderTargetData.depthTextureMips = {} );
  21241. const textures = renderTarget.textures;
  21242. const size = this.getSize( textures[ 0 ] );
  21243. const mipWidth = size.width >> activeMipmapLevel;
  21244. const mipHeight = size.height >> activeMipmapLevel;
  21245. let depthTexture = renderTarget.depthTexture || depthTextureMips[ activeMipmapLevel ];
  21246. const useDepthTexture = renderTarget.depthBuffer === true || renderTarget.stencilBuffer === true;
  21247. let textureNeedsUpdate = false;
  21248. if ( depthTexture === undefined && useDepthTexture ) {
  21249. depthTexture = new DepthTexture();
  21250. depthTexture.format = renderTarget.stencilBuffer ? DepthStencilFormat : DepthFormat;
  21251. depthTexture.type = renderTarget.stencilBuffer ? UnsignedInt248Type : UnsignedIntType; // FloatType
  21252. depthTexture.image.width = mipWidth;
  21253. depthTexture.image.height = mipHeight;
  21254. depthTexture.image.depth = size.depth;
  21255. depthTexture.isArrayTexture = renderTarget.multiview === true && size.depth > 1;
  21256. depthTextureMips[ activeMipmapLevel ] = depthTexture;
  21257. }
  21258. if ( renderTargetData.width !== size.width || size.height !== renderTargetData.height ) {
  21259. textureNeedsUpdate = true;
  21260. if ( depthTexture ) {
  21261. depthTexture.needsUpdate = true;
  21262. depthTexture.image.width = mipWidth;
  21263. depthTexture.image.height = mipHeight;
  21264. depthTexture.image.depth = depthTexture.isArrayTexture ? depthTexture.image.depth : 1;
  21265. }
  21266. }
  21267. renderTargetData.width = size.width;
  21268. renderTargetData.height = size.height;
  21269. renderTargetData.textures = textures;
  21270. renderTargetData.depthTexture = depthTexture || null;
  21271. renderTargetData.depth = renderTarget.depthBuffer;
  21272. renderTargetData.stencil = renderTarget.stencilBuffer;
  21273. renderTargetData.renderTarget = renderTarget;
  21274. if ( renderTargetData.sampleCount !== sampleCount ) {
  21275. textureNeedsUpdate = true;
  21276. if ( depthTexture ) {
  21277. depthTexture.needsUpdate = true;
  21278. }
  21279. renderTargetData.sampleCount = sampleCount;
  21280. }
  21281. //
  21282. const options = { sampleCount };
  21283. // XR render targets require no texture updates
  21284. if ( renderTarget.isXRRenderTarget !== true ) {
  21285. for ( let i = 0; i < textures.length; i ++ ) {
  21286. const texture = textures[ i ];
  21287. if ( textureNeedsUpdate ) texture.needsUpdate = true;
  21288. this.updateTexture( texture, options );
  21289. }
  21290. if ( depthTexture ) {
  21291. this.updateTexture( depthTexture, options );
  21292. }
  21293. }
  21294. // dispose handler
  21295. if ( renderTargetData.initialized !== true ) {
  21296. renderTargetData.initialized = true;
  21297. // dispose
  21298. const onDispose = () => {
  21299. renderTarget.removeEventListener( 'dispose', onDispose );
  21300. for ( let i = 0; i < textures.length; i ++ ) {
  21301. this._destroyTexture( textures[ i ] );
  21302. }
  21303. if ( depthTexture ) {
  21304. this._destroyTexture( depthTexture );
  21305. }
  21306. this.delete( renderTarget );
  21307. };
  21308. renderTarget.addEventListener( 'dispose', onDispose );
  21309. }
  21310. }
  21311. /**
  21312. * Updates the given texture. Depending on the texture state, this method
  21313. * triggers the upload of texture data to the GPU memory. If the texture data are
  21314. * not yet ready for the upload, it uses default texture data for as a placeholder.
  21315. *
  21316. * @param {Texture} texture - The texture to update.
  21317. * @param {Object} [options={}] - The options.
  21318. */
  21319. updateTexture( texture, options = {} ) {
  21320. const textureData = this.get( texture );
  21321. if ( textureData.initialized === true && textureData.version === texture.version ) return;
  21322. const isRenderTarget = texture.isRenderTargetTexture || texture.isDepthTexture || texture.isFramebufferTexture;
  21323. const backend = this.backend;
  21324. if ( isRenderTarget && textureData.initialized === true ) {
  21325. // it's an update
  21326. backend.destroySampler( texture );
  21327. backend.destroyTexture( texture );
  21328. }
  21329. //
  21330. if ( texture.isFramebufferTexture ) {
  21331. const renderTarget = this.renderer.getRenderTarget();
  21332. if ( renderTarget ) {
  21333. texture.type = renderTarget.texture.type;
  21334. } else {
  21335. texture.type = UnsignedByteType;
  21336. }
  21337. }
  21338. //
  21339. const { width, height, depth } = this.getSize( texture );
  21340. options.width = width;
  21341. options.height = height;
  21342. options.depth = depth;
  21343. options.needsMipmaps = this.needsMipmaps( texture );
  21344. options.levels = options.needsMipmaps ? this.getMipLevels( texture, width, height ) : 1;
  21345. //
  21346. if ( isRenderTarget || texture.isStorageTexture === true ) {
  21347. backend.createSampler( texture );
  21348. backend.createTexture( texture, options );
  21349. textureData.generation = texture.version;
  21350. } else {
  21351. const needsCreate = textureData.initialized !== true;
  21352. if ( needsCreate ) backend.createSampler( texture );
  21353. if ( texture.version > 0 ) {
  21354. const image = texture.image;
  21355. if ( image === undefined ) {
  21356. console.warn( 'THREE.Renderer: Texture marked for update but image is undefined.' );
  21357. } else if ( image.complete === false ) {
  21358. console.warn( 'THREE.Renderer: Texture marked for update but image is incomplete.' );
  21359. } else {
  21360. if ( texture.images ) {
  21361. const images = [];
  21362. for ( const image of texture.images ) {
  21363. images.push( image );
  21364. }
  21365. options.images = images;
  21366. } else {
  21367. options.image = image;
  21368. }
  21369. if ( textureData.isDefaultTexture === undefined || textureData.isDefaultTexture === true ) {
  21370. backend.createTexture( texture, options );
  21371. textureData.isDefaultTexture = false;
  21372. textureData.generation = texture.version;
  21373. }
  21374. if ( texture.source.dataReady === true ) backend.updateTexture( texture, options );
  21375. if ( options.needsMipmaps && texture.mipmaps.length === 0 ) backend.generateMipmaps( texture );
  21376. }
  21377. } else {
  21378. // async update
  21379. backend.createDefaultTexture( texture );
  21380. textureData.isDefaultTexture = true;
  21381. textureData.generation = texture.version;
  21382. }
  21383. }
  21384. // dispose handler
  21385. if ( textureData.initialized !== true ) {
  21386. textureData.initialized = true;
  21387. textureData.generation = texture.version;
  21388. //
  21389. this.info.memory.textures ++;
  21390. // dispose
  21391. const onDispose = () => {
  21392. texture.removeEventListener( 'dispose', onDispose );
  21393. this._destroyTexture( texture );
  21394. };
  21395. texture.addEventListener( 'dispose', onDispose );
  21396. }
  21397. //
  21398. textureData.version = texture.version;
  21399. }
  21400. /**
  21401. * Computes the size of the given texture and writes the result
  21402. * into the target vector. This vector is also returned by the
  21403. * method.
  21404. *
  21405. * If no texture data are available for the compute yet, the method
  21406. * returns default size values.
  21407. *
  21408. * @param {Texture} texture - The texture to compute the size for.
  21409. * @param {Vector3} target - The target vector.
  21410. * @return {Vector3} The target vector.
  21411. */
  21412. getSize( texture, target = _size$3 ) {
  21413. let image = texture.images ? texture.images[ 0 ] : texture.image;
  21414. if ( image ) {
  21415. if ( image.image !== undefined ) image = image.image;
  21416. target.width = image.width || 1;
  21417. target.height = image.height || 1;
  21418. target.depth = texture.isCubeTexture ? 6 : ( image.depth || 1 );
  21419. } else {
  21420. target.width = target.height = target.depth = 1;
  21421. }
  21422. return target;
  21423. }
  21424. /**
  21425. * Computes the number of mipmap levels for the given texture.
  21426. *
  21427. * @param {Texture} texture - The texture.
  21428. * @param {number} width - The texture's width.
  21429. * @param {number} height - The texture's height.
  21430. * @return {number} The number of mipmap levels.
  21431. */
  21432. getMipLevels( texture, width, height ) {
  21433. let mipLevelCount;
  21434. if ( texture.isCompressedTexture ) {
  21435. if ( texture.mipmaps ) {
  21436. mipLevelCount = texture.mipmaps.length;
  21437. } else {
  21438. mipLevelCount = 1;
  21439. }
  21440. } else {
  21441. mipLevelCount = Math.floor( Math.log2( Math.max( width, height ) ) ) + 1;
  21442. }
  21443. return mipLevelCount;
  21444. }
  21445. /**
  21446. * Returns `true` if the given texture requires mipmaps.
  21447. *
  21448. * @param {Texture} texture - The texture.
  21449. * @return {boolean} Whether mipmaps are required or not.
  21450. */
  21451. needsMipmaps( texture ) {
  21452. return texture.isCompressedTexture === true || texture.generateMipmaps;
  21453. }
  21454. /**
  21455. * Frees internal resource when the given texture isn't
  21456. * required anymore.
  21457. *
  21458. * @param {Texture} texture - The texture to destroy.
  21459. */
  21460. _destroyTexture( texture ) {
  21461. if ( this.has( texture ) === true ) {
  21462. this.backend.destroySampler( texture );
  21463. this.backend.destroyTexture( texture );
  21464. this.delete( texture );
  21465. this.info.memory.textures --;
  21466. }
  21467. }
  21468. }
  21469. /**
  21470. * A four-component version of {@link Color} which is internally
  21471. * used by the renderer to represents clear color with alpha as
  21472. * one object.
  21473. *
  21474. * @private
  21475. * @augments Color
  21476. */
  21477. class Color4 extends Color {
  21478. /**
  21479. * Constructs a new four-component color.
  21480. * You can also pass a single THREE.Color, hex or
  21481. * string argument to this constructor.
  21482. *
  21483. * @param {number|string} [r=1] - The red value.
  21484. * @param {number} [g=1] - The green value.
  21485. * @param {number} [b=1] - The blue value.
  21486. * @param {number} [a=1] - The alpha value.
  21487. */
  21488. constructor( r, g, b, a = 1 ) {
  21489. super( r, g, b );
  21490. this.a = a;
  21491. }
  21492. /**
  21493. * Overwrites the default to honor alpha.
  21494. * You can also pass a single THREE.Color, hex or
  21495. * string argument to this method.
  21496. *
  21497. * @param {number|string|Color} r - The red value.
  21498. * @param {number} g - The green value.
  21499. * @param {number} b - The blue value.
  21500. * @param {number} [a=1] - The alpha value.
  21501. * @return {Color4} A reference to this object.
  21502. */
  21503. set( r, g, b, a = 1 ) {
  21504. this.a = a;
  21505. return super.set( r, g, b );
  21506. }
  21507. /**
  21508. * Overwrites the default to honor alpha.
  21509. *
  21510. * @param {Color4} color - The color to copy.
  21511. * @return {Color4} A reference to this object.
  21512. */
  21513. copy( color ) {
  21514. if ( color.a !== undefined ) this.a = color.a;
  21515. return super.copy( color );
  21516. }
  21517. /**
  21518. * Overwrites the default to honor alpha.
  21519. *
  21520. * @return {Color4} The cloned color.
  21521. */
  21522. clone() {
  21523. return new this.constructor( this.r, this.g, this.b, this.a );
  21524. }
  21525. }
  21526. /**
  21527. * Special version of {@link PropertyNode} which is used for parameters.
  21528. *
  21529. * @augments PropertyNode
  21530. */
  21531. class ParameterNode extends PropertyNode {
  21532. static get type() {
  21533. return 'ParameterNode';
  21534. }
  21535. /**
  21536. * Constructs a new parameter node.
  21537. *
  21538. * @param {string} nodeType - The type of the node.
  21539. * @param {?string} [name=null] - The name of the parameter in the shader.
  21540. */
  21541. constructor( nodeType, name = null ) {
  21542. super( nodeType, name );
  21543. /**
  21544. * This flag can be used for type testing.
  21545. *
  21546. * @type {boolean}
  21547. * @readonly
  21548. * @default true
  21549. */
  21550. this.isParameterNode = true;
  21551. }
  21552. getHash() {
  21553. return this.uuid;
  21554. }
  21555. generate() {
  21556. return this.name;
  21557. }
  21558. }
  21559. /**
  21560. * TSL function for creating a parameter node.
  21561. *
  21562. * @tsl
  21563. * @function
  21564. * @param {string} type - The type of the node.
  21565. * @param {?string} name - The name of the parameter in the shader.
  21566. * @returns {ParameterNode}
  21567. */
  21568. const parameter = ( type, name ) => nodeObject( new ParameterNode( type, name ) );
  21569. /**
  21570. * Stack is a helper for Nodes that need to produce stack-based code instead of continuous flow.
  21571. * They are usually needed in cases like `If`, `Else`.
  21572. *
  21573. * @augments Node
  21574. */
  21575. class StackNode extends Node {
  21576. static get type() {
  21577. return 'StackNode';
  21578. }
  21579. /**
  21580. * Constructs a new stack node.
  21581. *
  21582. * @param {?StackNode} [parent=null] - The parent stack node.
  21583. */
  21584. constructor( parent = null ) {
  21585. super();
  21586. /**
  21587. * List of nodes.
  21588. *
  21589. * @type {Array<Node>}
  21590. */
  21591. this.nodes = [];
  21592. /**
  21593. * The output node.
  21594. *
  21595. * @type {?Node}
  21596. * @default null
  21597. */
  21598. this.outputNode = null;
  21599. /**
  21600. * The parent stack node.
  21601. *
  21602. * @type {?StackNode}
  21603. * @default null
  21604. */
  21605. this.parent = parent;
  21606. /**
  21607. * The current conditional node.
  21608. *
  21609. * @private
  21610. * @type {ConditionalNode}
  21611. * @default null
  21612. */
  21613. this._currentCond = null;
  21614. /**
  21615. * The expression node. Only
  21616. * relevant for Switch/Case.
  21617. *
  21618. * @private
  21619. * @type {Node}
  21620. * @default null
  21621. */
  21622. this._expressionNode = null;
  21623. /**
  21624. * This flag can be used for type testing.
  21625. *
  21626. * @type {boolean}
  21627. * @readonly
  21628. * @default true
  21629. */
  21630. this.isStackNode = true;
  21631. }
  21632. getNodeType( builder ) {
  21633. return this.outputNode ? this.outputNode.getNodeType( builder ) : 'void';
  21634. }
  21635. getMemberType( builder, name ) {
  21636. return this.outputNode ? this.outputNode.getMemberType( builder, name ) : 'void';
  21637. }
  21638. /**
  21639. * Adds a node to this stack.
  21640. *
  21641. * @param {Node} node - The node to add.
  21642. * @return {StackNode} A reference to this stack node.
  21643. */
  21644. add( node ) {
  21645. this.nodes.push( node );
  21646. return this;
  21647. }
  21648. /**
  21649. * Represent an `if` statement in TSL.
  21650. *
  21651. * @param {Node} boolNode - Represents the condition.
  21652. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21653. * @return {StackNode} A reference to this stack node.
  21654. */
  21655. If( boolNode, method ) {
  21656. const methodNode = new ShaderNode( method );
  21657. this._currentCond = select( boolNode, methodNode );
  21658. return this.add( this._currentCond );
  21659. }
  21660. /**
  21661. * Represent an `elseif` statement in TSL.
  21662. *
  21663. * @param {Node} boolNode - Represents the condition.
  21664. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21665. * @return {StackNode} A reference to this stack node.
  21666. */
  21667. ElseIf( boolNode, method ) {
  21668. const methodNode = new ShaderNode( method );
  21669. const ifNode = select( boolNode, methodNode );
  21670. this._currentCond.elseNode = ifNode;
  21671. this._currentCond = ifNode;
  21672. return this;
  21673. }
  21674. /**
  21675. * Represent an `else` statement in TSL.
  21676. *
  21677. * @param {Function} method - TSL code which is executed in the `else` case.
  21678. * @return {StackNode} A reference to this stack node.
  21679. */
  21680. Else( method ) {
  21681. this._currentCond.elseNode = new ShaderNode( method );
  21682. return this;
  21683. }
  21684. /**
  21685. * Represents a `switch` statement in TSL.
  21686. *
  21687. * @param {any} expression - Represents the expression.
  21688. * @param {Function} method - TSL code which is executed if the condition evaluates to `true`.
  21689. * @return {StackNode} A reference to this stack node.
  21690. */
  21691. Switch( expression ) {
  21692. this._expressionNode = nodeObject( expression );
  21693. return this;
  21694. }
  21695. /**
  21696. * Represents a `case` statement in TSL. The TSL version accepts an arbitrary numbers of values.
  21697. * The last parameter must be the callback method that should be executed in the `true` case.
  21698. *
  21699. * @param {...any} params - The values of the `Case()` statement as well as the callback method.
  21700. * @return {StackNode} A reference to this stack node.
  21701. */
  21702. Case( ...params ) {
  21703. const caseNodes = [];
  21704. // extract case nodes from the parameter list
  21705. if ( params.length >= 2 ) {
  21706. for ( let i = 0; i < params.length - 1; i ++ ) {
  21707. caseNodes.push( this._expressionNode.equal( nodeObject( params[ i ] ) ) );
  21708. }
  21709. } else {
  21710. throw new Error( 'TSL: Invalid parameter length. Case() requires at least two parameters.' );
  21711. }
  21712. // extract method
  21713. const method = params[ params.length - 1 ];
  21714. const methodNode = new ShaderNode( method );
  21715. // chain multiple cases when using Case( 1, 2, 3, () => {} )
  21716. let caseNode = caseNodes[ 0 ];
  21717. for ( let i = 1; i < caseNodes.length; i ++ ) {
  21718. caseNode = caseNode.or( caseNodes[ i ] );
  21719. }
  21720. // build condition
  21721. const condNode = select( caseNode, methodNode );
  21722. if ( this._currentCond === null ) {
  21723. this._currentCond = condNode;
  21724. return this.add( this._currentCond );
  21725. } else {
  21726. this._currentCond.elseNode = condNode;
  21727. this._currentCond = condNode;
  21728. return this;
  21729. }
  21730. }
  21731. /**
  21732. * Represents the default code block of a Switch/Case statement.
  21733. *
  21734. * @param {Function} method - TSL code which is executed in the `else` case.
  21735. * @return {StackNode} A reference to this stack node.
  21736. */
  21737. Default( method ) {
  21738. this.Else( method );
  21739. return this;
  21740. }
  21741. build( builder, ...params ) {
  21742. const previousStack = getCurrentStack();
  21743. setCurrentStack( this );
  21744. const buildStage = builder.buildStage;
  21745. for ( const node of this.nodes ) {
  21746. if ( buildStage === 'setup' ) {
  21747. node.build( builder );
  21748. } else if ( buildStage === 'analyze' ) {
  21749. node.build( builder, this );
  21750. } else if ( buildStage === 'generate' ) {
  21751. const stages = builder.getDataFromNode( node, 'any' ).stages;
  21752. const parents = stages && stages[ builder.shaderStage ];
  21753. if ( node.isVarNode && parents && parents.length === 1 && parents[ 0 ] && parents[ 0 ].isStackNode ) {
  21754. continue; // skip var nodes that are only used in .toVarying()
  21755. }
  21756. node.build( builder, 'void' );
  21757. }
  21758. }
  21759. setCurrentStack( previousStack );
  21760. return this.outputNode ? this.outputNode.build( builder, ...params ) : super.build( builder, ...params );
  21761. }
  21762. // Deprecated
  21763. /**
  21764. * @function
  21765. * @deprecated since r168. Use {@link StackNode#Else} instead.
  21766. *
  21767. * @param {...any} params
  21768. * @returns {StackNode}
  21769. */
  21770. else( ...params ) { // @deprecated, r168
  21771. console.warn( 'THREE.TSL: .else() has been renamed to .Else().' );
  21772. return this.Else( ...params );
  21773. }
  21774. /**
  21775. * @deprecated since r168. Use {@link StackNode#ElseIf} instead.
  21776. *
  21777. * @param {...any} params
  21778. * @returns {StackNode}
  21779. */
  21780. elseif( ...params ) { // @deprecated, r168
  21781. console.warn( 'THREE.TSL: .elseif() has been renamed to .ElseIf().' );
  21782. return this.ElseIf( ...params );
  21783. }
  21784. }
  21785. /**
  21786. * TSL function for creating a stack node.
  21787. *
  21788. * @tsl
  21789. * @function
  21790. * @param {?StackNode} [parent=null] - The parent stack node.
  21791. * @returns {StackNode}
  21792. */
  21793. const stack = /*@__PURE__*/ nodeProxy( StackNode ).setParameterLength( 0, 1 );
  21794. /**
  21795. * Generates a layout for struct members.
  21796. * This function takes an object representing struct members and returns an array of member layouts.
  21797. * Each member layout includes the member's name, type, and whether it is atomic.
  21798. *
  21799. * @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.
  21800. * @returns {Array.<{name: string, type: string, atomic: boolean}>} An array of member layouts.
  21801. */
  21802. function getMembersLayout( members ) {
  21803. return Object.entries( members ).map( ( [ name, value ] ) => {
  21804. if ( typeof value === 'string' ) {
  21805. return { name, type: value, atomic: false };
  21806. }
  21807. return { name, type: value.type, atomic: value.atomic || false };
  21808. } );
  21809. }
  21810. /**
  21811. * Represents a struct type node in the node-based system.
  21812. * This class is used to define and manage the layout and types of struct members.
  21813. * It extends the base Node class and provides methods to get the length of the struct,
  21814. * retrieve member types, and generate the struct type for a builder.
  21815. *
  21816. * @augments Node
  21817. */
  21818. class StructTypeNode extends Node {
  21819. static get type() {
  21820. return 'StructTypeNode';
  21821. }
  21822. /**
  21823. * Creates an instance of StructTypeNode.
  21824. *
  21825. * @param {Object} membersLayout - The layout of the members for the struct.
  21826. * @param {?string} [name=null] - The optional name of the struct.
  21827. */
  21828. constructor( membersLayout, name = null ) {
  21829. super( 'struct' );
  21830. /**
  21831. * The layout of the members for the struct
  21832. *
  21833. * @type {Array.<{name: string, type: string, atomic: boolean}>}
  21834. */
  21835. this.membersLayout = getMembersLayout( membersLayout );
  21836. /**
  21837. * The name of the struct.
  21838. *
  21839. * @type {?string}
  21840. * @default null
  21841. */
  21842. this.name = name;
  21843. /**
  21844. * This flag can be used for type testing.
  21845. *
  21846. * @type {boolean}
  21847. * @readonly
  21848. * @default true
  21849. */
  21850. this.isStructLayoutNode = true;
  21851. }
  21852. /**
  21853. * Returns the length of the struct.
  21854. * The length is calculated by summing the lengths of the struct's members.
  21855. *
  21856. * @returns {number} The length of the struct.
  21857. */
  21858. getLength() {
  21859. const GPU_CHUNK_BYTES = 8;
  21860. const BYTES_PER_ELEMENT = Float32Array.BYTES_PER_ELEMENT;
  21861. let offset = 0; // global buffer offset in bytes
  21862. for ( const member of this.membersLayout ) {
  21863. const type = member.type;
  21864. const itemSize = getMemoryLengthFromType( type ) * BYTES_PER_ELEMENT;
  21865. const boundary = getByteBoundaryFromType( type );
  21866. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  21867. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  21868. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  21869. offset += chunkPadding;
  21870. // Check for chunk overflow
  21871. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  21872. // Add padding to the end of the chunk
  21873. offset += ( GPU_CHUNK_BYTES - chunkStart );
  21874. }
  21875. offset += itemSize;
  21876. }
  21877. return ( Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES ) / BYTES_PER_ELEMENT;
  21878. }
  21879. getMemberType( builder, name ) {
  21880. const member = this.membersLayout.find( m => m.name === name );
  21881. return member ? member.type : 'void';
  21882. }
  21883. getNodeType( builder ) {
  21884. const structType = builder.getStructTypeFromNode( this, this.membersLayout, this.name );
  21885. return structType.name;
  21886. }
  21887. setup( builder ) {
  21888. builder.addInclude( this );
  21889. }
  21890. generate( builder ) {
  21891. return this.getNodeType( builder );
  21892. }
  21893. }
  21894. /**
  21895. * StructNode allows to create custom structures with multiple members.
  21896. * This can also be used to define structures in attribute and uniform data.
  21897. *
  21898. * ```js
  21899. * // Define a custom struct
  21900. * const BoundingBox = struct( { min: 'vec3', max: 'vec3' } );
  21901. *
  21902. * // Create a new instance of the struct
  21903. * const bb = BoundingBox( vec3( 0 ), vec3( 1 ) ); // style 1
  21904. * const bb = BoundingBox( { min: vec3( 0 ), max: vec3( 1 ) } ); // style 2
  21905. *
  21906. * // Access the struct members
  21907. * const min = bb.get( 'min' );
  21908. *
  21909. * // Assign a new value to a member
  21910. * min.assign( vec3() );
  21911. * ```
  21912. * @augments Node
  21913. */
  21914. class StructNode extends Node {
  21915. static get type() {
  21916. return 'StructNode';
  21917. }
  21918. constructor( structLayoutNode, values ) {
  21919. super( 'vec3' );
  21920. this.structLayoutNode = structLayoutNode;
  21921. this.values = values;
  21922. this.isStructNode = true;
  21923. }
  21924. getNodeType( builder ) {
  21925. return this.structLayoutNode.getNodeType( builder );
  21926. }
  21927. getMemberType( builder, name ) {
  21928. return this.structLayoutNode.getMemberType( builder, name );
  21929. }
  21930. generate( builder ) {
  21931. const nodeVar = builder.getVarFromNode( this );
  21932. const structType = nodeVar.type;
  21933. const propertyName = builder.getPropertyName( nodeVar );
  21934. builder.addLineFlowCode( `${ propertyName } = ${ builder.generateStruct( structType, this.structLayoutNode.membersLayout, this.values ) }`, this );
  21935. return nodeVar.name;
  21936. }
  21937. }
  21938. /**
  21939. * TSL function for creating a struct node.
  21940. *
  21941. * @tsl
  21942. * @function
  21943. * @param {Object} membersLayout - The layout of the struct members.
  21944. * @param {?string} [name=null] - The name of the struct.
  21945. * @returns {Function} The struct function.
  21946. */
  21947. const struct = ( membersLayout, name = null ) => {
  21948. const structLayout = new StructTypeNode( membersLayout, name );
  21949. const struct = ( ...params ) => {
  21950. let values = null;
  21951. if ( params.length > 0 ) {
  21952. if ( params[ 0 ].isNode ) {
  21953. values = {};
  21954. const names = Object.keys( membersLayout );
  21955. for ( let i = 0; i < params.length; i ++ ) {
  21956. values[ names[ i ] ] = params[ i ];
  21957. }
  21958. } else {
  21959. values = params[ 0 ];
  21960. }
  21961. }
  21962. return nodeObject( new StructNode( structLayout, values ) );
  21963. };
  21964. struct.layout = structLayout;
  21965. struct.isStruct = true;
  21966. return struct;
  21967. };
  21968. /**
  21969. * This node can be used to define multiple outputs in a shader programs.
  21970. *
  21971. * @augments Node
  21972. */
  21973. class OutputStructNode extends Node {
  21974. static get type() {
  21975. return 'OutputStructNode';
  21976. }
  21977. /**
  21978. * Constructs a new output struct node. The constructor can be invoked with an
  21979. * arbitrary number of nodes representing the members.
  21980. *
  21981. * @param {...Node} members - A parameter list of nodes.
  21982. */
  21983. constructor( ...members ) {
  21984. super();
  21985. /**
  21986. * An array of nodes which defines the output.
  21987. *
  21988. * @type {Array<Node>}
  21989. */
  21990. this.members = members;
  21991. /**
  21992. * This flag can be used for type testing.
  21993. *
  21994. * @type {boolean}
  21995. * @readonly
  21996. * @default true
  21997. */
  21998. this.isOutputStructNode = true;
  21999. }
  22000. getNodeType( builder ) {
  22001. const properties = builder.getNodeProperties( this );
  22002. if ( properties.membersLayout === undefined ) {
  22003. const members = this.members;
  22004. const membersLayout = [];
  22005. for ( let i = 0; i < members.length; i ++ ) {
  22006. const name = 'm' + i;
  22007. const type = members[ i ].getNodeType( builder );
  22008. membersLayout.push( { name, type, index: i } );
  22009. }
  22010. properties.membersLayout = membersLayout;
  22011. properties.structType = builder.getOutputStructTypeFromNode( this, properties.membersLayout );
  22012. }
  22013. return properties.structType.name;
  22014. }
  22015. generate( builder ) {
  22016. const propertyName = builder.getOutputStructName();
  22017. const members = this.members;
  22018. const structPrefix = propertyName !== '' ? propertyName + '.' : '';
  22019. for ( let i = 0; i < members.length; i ++ ) {
  22020. const snippet = members[ i ].build( builder );
  22021. builder.addLineFlowCode( `${ structPrefix }m${ i } = ${ snippet }`, this );
  22022. }
  22023. return propertyName;
  22024. }
  22025. }
  22026. /**
  22027. * TSL function for creating an output struct node.
  22028. *
  22029. * @tsl
  22030. * @function
  22031. * @param {...Node} members - A parameter list of nodes.
  22032. * @returns {OutputStructNode}
  22033. */
  22034. const outputStruct = /*@__PURE__*/ nodeProxy( OutputStructNode );
  22035. /**
  22036. * Returns the MRT texture index for the given name.
  22037. *
  22038. * @param {Array<Texture>} textures - The textures of a MRT-configured render target.
  22039. * @param {string} name - The name of the MRT texture which index is requested.
  22040. * @return {number} The texture index.
  22041. */
  22042. function getTextureIndex( textures, name ) {
  22043. for ( let i = 0; i < textures.length; i ++ ) {
  22044. if ( textures[ i ].name === name ) {
  22045. return i;
  22046. }
  22047. }
  22048. return -1;
  22049. }
  22050. /**
  22051. * This node can be used setup a MRT context for rendering. A typical MRT setup for
  22052. * post-processing is shown below:
  22053. * ```js
  22054. * const mrtNode = mrt( {
  22055. * output: output,
  22056. * normal: normalView
  22057. * } ) );
  22058. * ```
  22059. * The MRT output is defined as a dictionary.
  22060. *
  22061. * @augments OutputStructNode
  22062. */
  22063. class MRTNode extends OutputStructNode {
  22064. static get type() {
  22065. return 'MRTNode';
  22066. }
  22067. /**
  22068. * Constructs a new output struct node.
  22069. *
  22070. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  22071. */
  22072. constructor( outputNodes ) {
  22073. super();
  22074. /**
  22075. * A dictionary representing the MRT outputs. The key
  22076. * is the name of the output, the value the node which produces
  22077. * the output result.
  22078. *
  22079. * @type {Object<string, Node>}
  22080. */
  22081. this.outputNodes = outputNodes;
  22082. /**
  22083. * This flag can be used for type testing.
  22084. *
  22085. * @type {boolean}
  22086. * @readonly
  22087. * @default true
  22088. */
  22089. this.isMRTNode = true;
  22090. }
  22091. /**
  22092. * Returns `true` if the MRT node has an output with the given name.
  22093. *
  22094. * @param {string} name - The name of the output.
  22095. * @return {NodeBuilder} Whether the MRT node has an output for the given name or not.
  22096. */
  22097. has( name ) {
  22098. return this.outputNodes[ name ] !== undefined;
  22099. }
  22100. /**
  22101. * Returns the output node for the given name.
  22102. *
  22103. * @param {string} name - The name of the output.
  22104. * @return {Node} The output node.
  22105. */
  22106. get( name ) {
  22107. return this.outputNodes[ name ];
  22108. }
  22109. /**
  22110. * Merges the outputs of the given MRT node with the outputs of this node.
  22111. *
  22112. * @param {MRTNode} mrtNode - The MRT to merge.
  22113. * @return {MRTNode} A new MRT node with merged outputs..
  22114. */
  22115. merge( mrtNode ) {
  22116. const outputs = { ...this.outputNodes, ...mrtNode.outputNodes };
  22117. return mrt( outputs );
  22118. }
  22119. setup( builder ) {
  22120. const outputNodes = this.outputNodes;
  22121. const mrt = builder.renderer.getRenderTarget();
  22122. const members = [];
  22123. const textures = mrt.textures;
  22124. for ( const name in outputNodes ) {
  22125. const index = getTextureIndex( textures, name );
  22126. members[ index ] = vec4( outputNodes[ name ] );
  22127. }
  22128. this.members = members;
  22129. return super.setup( builder );
  22130. }
  22131. }
  22132. /**
  22133. * TSL function for creating a MRT node.
  22134. *
  22135. * @tsl
  22136. * @function
  22137. * @param {Object<string, Node>} outputNodes - The MRT outputs.
  22138. * @returns {MRTNode}
  22139. */
  22140. const mrt = /*@__PURE__*/ nodeProxy( MRTNode );
  22141. /**
  22142. * Generates a hash value in the range `[0, 1]` from the given seed.
  22143. *
  22144. * @tsl
  22145. * @function
  22146. * @param {Node<float>} seed - The seed.
  22147. * @return {Node<float>} The hash value.
  22148. */
  22149. const hash = /*@__PURE__*/ Fn( ( [ seed ] ) => {
  22150. // Taken from https://www.shadertoy.com/view/XlGcRh, originally from pcg-random.org
  22151. const state = seed.toUint().mul( 747796405 ).add( 2891336453 );
  22152. const word = state.shiftRight( state.shiftRight( 28 ).add( 4 ) ).bitXor( state ).mul( 277803737 );
  22153. const result = word.shiftRight( 22 ).bitXor( word );
  22154. return result.toFloat().mul( 1 / 2 ** 32 ); // Convert to range [0, 1)
  22155. } );
  22156. /**
  22157. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22158. * The corners are mapped to `0` and the center to `1`.
  22159. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22160. *
  22161. * @tsl
  22162. * @function
  22163. * @param {Node<float>} x - The value to remap.
  22164. * @param {Node<float>} k - Allows to control the remapping functions shape by rising the parabola to a power `k`.
  22165. * @return {Node<float>} The remapped value.
  22166. */
  22167. const parabola = ( x, k ) => pow( mul( 4.0, x.mul( sub( 1.0, x ) ) ), k );
  22168. /**
  22169. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22170. * Expands the sides and compresses the center, and keeps `0.5` mapped to `0.5`.
  22171. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22172. *
  22173. * @tsl
  22174. * @function
  22175. * @param {Node<float>} x - The value to remap.
  22176. * @param {Node<float>} k - `k=1` is the identity curve,`k<1` produces the classic `gain()` shape, and `k>1` produces "s" shaped curves.
  22177. * @return {Node<float>} The remapped value.
  22178. */
  22179. 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 ) );
  22180. /**
  22181. * A function that remaps the `[0,1]` interval into the `[0,1]` interval.
  22182. * A generalization of the `parabola()`. Keeps the corners mapped to 0 but allows the control of the shape one either side of the curve.
  22183. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22184. *
  22185. * @tsl
  22186. * @function
  22187. * @param {Node<float>} x - The value to remap.
  22188. * @param {Node<float>} a - First control parameter.
  22189. * @param {Node<float>} b - Second control parameter.
  22190. * @return {Node<float>} The remapped value.
  22191. */
  22192. const pcurve = ( x, a, b ) => pow( div( pow( x, a ), add( pow( x, a ), pow( sub( 1.0, x ), b ) ) ), 1.0 / a );
  22193. /**
  22194. * A phase shifted sinus curve that starts at zero and ends at zero, with bouncing behavior.
  22195. * Reference: {@link https://iquilezles.org/articles/functions/}.
  22196. *
  22197. * @tsl
  22198. * @function
  22199. * @param {Node<float>} x - The value to compute the sin for.
  22200. * @param {Node<float>} k - Controls the amount of bounces.
  22201. * @return {Node<float>} The result value.
  22202. */
  22203. const sinc = ( x, k ) => sin( PI.mul( k.mul( x ).sub( 1.0 ) ) ).div( PI.mul( k.mul( x ).sub( 1.0 ) ) );
  22204. // https://github.com/cabbibo/glsl-tri-noise-3d
  22205. const tri = /*@__PURE__*/ Fn( ( [ x ] ) => {
  22206. return x.fract().sub( .5 ).abs();
  22207. } ).setLayout( {
  22208. name: 'tri',
  22209. type: 'float',
  22210. inputs: [
  22211. { name: 'x', type: 'float' }
  22212. ]
  22213. } );
  22214. const tri3 = /*@__PURE__*/ Fn( ( [ p ] ) => {
  22215. 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. ) ) ) ) );
  22216. } ).setLayout( {
  22217. name: 'tri3',
  22218. type: 'vec3',
  22219. inputs: [
  22220. { name: 'p', type: 'vec3' }
  22221. ]
  22222. } );
  22223. /**
  22224. * Generates a noise value from the given position, speed and time parameters.
  22225. *
  22226. * @tsl
  22227. * @function
  22228. * @param {Node<vec3>} position - The position.
  22229. * @param {Node<float>} speed - The speed.
  22230. * @param {Node<float>} time - The time.
  22231. * @return {Node<float>} The generated noise.
  22232. */
  22233. const triNoise3D = /*@__PURE__*/ Fn( ( [ position, speed, time ] ) => {
  22234. const p = vec3( position ).toVar();
  22235. const z = float( 1.4 ).toVar();
  22236. const rz = float( 0.0 ).toVar();
  22237. const bp = vec3( p ).toVar();
  22238. Loop( { start: float( 0.0 ), end: float( 3.0 ), type: 'float', condition: '<=' }, () => {
  22239. const dg = vec3( tri3( bp.mul( 2.0 ) ) ).toVar();
  22240. p.addAssign( dg.add( time.mul( float( 0.1 ).mul( speed ) ) ) );
  22241. bp.mulAssign( 1.8 );
  22242. z.mulAssign( 1.5 );
  22243. p.mulAssign( 1.2 );
  22244. const t = float( tri( p.z.add( tri( p.x.add( tri( p.y ) ) ) ) ) ).toVar();
  22245. rz.addAssign( t.div( z ) );
  22246. bp.addAssign( 0.14 );
  22247. } );
  22248. return rz;
  22249. } ).setLayout( {
  22250. name: 'triNoise3D',
  22251. type: 'float',
  22252. inputs: [
  22253. { name: 'position', type: 'vec3' },
  22254. { name: 'speed', type: 'float' },
  22255. { name: 'time', type: 'float' }
  22256. ]
  22257. } );
  22258. /**
  22259. * This class allows to define multiple overloaded versions
  22260. * of the same function. Depending on the parameters of the function
  22261. * call, the node picks the best-fit overloaded version.
  22262. *
  22263. * @augments Node
  22264. */
  22265. class FunctionOverloadingNode extends Node {
  22266. static get type() {
  22267. return 'FunctionOverloadingNode';
  22268. }
  22269. /**
  22270. * Constructs a new function overloading node.
  22271. *
  22272. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  22273. * @param {...Node} parametersNodes - A list of parameter nodes.
  22274. */
  22275. constructor( functionNodes = [], ...parametersNodes ) {
  22276. super();
  22277. /**
  22278. * Array of `Fn` function definitions.
  22279. *
  22280. * @type {Array<Function>}
  22281. */
  22282. this.functionNodes = functionNodes;
  22283. /**
  22284. * A list of parameter nodes.
  22285. *
  22286. * @type {Array<Node>}
  22287. */
  22288. this.parametersNodes = parametersNodes;
  22289. /**
  22290. * The selected overloaded function call.
  22291. *
  22292. * @private
  22293. * @type {ShaderCallNodeInternal}
  22294. */
  22295. this._candidateFnCall = null;
  22296. /**
  22297. * This node is marked as global.
  22298. *
  22299. * @type {boolean}
  22300. * @default true
  22301. */
  22302. this.global = true;
  22303. }
  22304. /**
  22305. * This method is overwritten since the node type is inferred from
  22306. * the function's return type.
  22307. *
  22308. * @param {NodeBuilder} builder - The current node builder.
  22309. * @return {string} The node type.
  22310. */
  22311. getNodeType() {
  22312. return this.functionNodes[ 0 ].shaderNode.layout.type;
  22313. }
  22314. setup( builder ) {
  22315. const params = this.parametersNodes;
  22316. let candidateFnCall = this._candidateFnCall;
  22317. if ( candidateFnCall === null ) {
  22318. let candidateFn = null;
  22319. let candidateScore = -1;
  22320. for ( const functionNode of this.functionNodes ) {
  22321. const shaderNode = functionNode.shaderNode;
  22322. const layout = shaderNode.layout;
  22323. if ( layout === null ) {
  22324. throw new Error( 'FunctionOverloadingNode: FunctionNode must be a layout.' );
  22325. }
  22326. const inputs = layout.inputs;
  22327. if ( params.length === inputs.length ) {
  22328. let score = 0;
  22329. for ( let i = 0; i < params.length; i ++ ) {
  22330. const param = params[ i ];
  22331. const input = inputs[ i ];
  22332. if ( param.getNodeType( builder ) === input.type ) {
  22333. score ++;
  22334. } else {
  22335. score = 0;
  22336. }
  22337. }
  22338. if ( score > candidateScore ) {
  22339. candidateFn = functionNode;
  22340. candidateScore = score;
  22341. }
  22342. }
  22343. }
  22344. this._candidateFnCall = candidateFnCall = candidateFn( ...params );
  22345. }
  22346. return candidateFnCall;
  22347. }
  22348. }
  22349. const overloadingBaseFn = /*@__PURE__*/ nodeProxy( FunctionOverloadingNode );
  22350. /**
  22351. * TSL function for creating a function overloading node.
  22352. *
  22353. * @tsl
  22354. * @function
  22355. * @param {Array<Function>} functionNodes - Array of `Fn` function definitions.
  22356. * @returns {FunctionOverloadingNode}
  22357. */
  22358. const overloadingFn = ( functionNodes ) => ( ...params ) => overloadingBaseFn( functionNodes, ...params );
  22359. /**
  22360. * Represents the elapsed time in seconds.
  22361. *
  22362. * @tsl
  22363. * @type {UniformNode<float>}
  22364. */
  22365. const time = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.time );
  22366. /**
  22367. * Represents the delta time in seconds.
  22368. *
  22369. * @tsl
  22370. * @type {UniformNode<float>}
  22371. */
  22372. const deltaTime = /*@__PURE__*/ uniform( 0 ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.deltaTime );
  22373. /**
  22374. * Represents the current frame ID.
  22375. *
  22376. * @tsl
  22377. * @type {UniformNode<uint>}
  22378. */
  22379. const frameId = /*@__PURE__*/ uniform( 0, 'uint' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => frame.frameId );
  22380. // Deprecated
  22381. /**
  22382. * @tsl
  22383. * @function
  22384. * @deprecated since r170. Use {@link time} instead.
  22385. *
  22386. * @param {number} [timeScale=1] - The time scale.
  22387. * @returns {UniformNode<float>}
  22388. */
  22389. const timerLocal = ( timeScale = 1 ) => { // @deprecated, r170
  22390. console.warn( 'TSL: timerLocal() is deprecated. Use "time" instead.' );
  22391. return time.mul( timeScale );
  22392. };
  22393. /**
  22394. * @tsl
  22395. * @function
  22396. * @deprecated since r170. Use {@link time} instead.
  22397. *
  22398. * @param {number} [timeScale=1] - The time scale.
  22399. * @returns {UniformNode<float>}
  22400. */
  22401. const timerGlobal = ( timeScale = 1 ) => { // @deprecated, r170
  22402. console.warn( 'TSL: timerGlobal() is deprecated. Use "time" instead.' );
  22403. return time.mul( timeScale );
  22404. };
  22405. /**
  22406. * @tsl
  22407. * @function
  22408. * @deprecated since r170. Use {@link deltaTime} instead.
  22409. *
  22410. * @param {number} [timeScale=1] - The time scale.
  22411. * @returns {UniformNode<float>}
  22412. */
  22413. const timerDelta = ( timeScale = 1 ) => { // @deprecated, r170
  22414. console.warn( 'TSL: timerDelta() is deprecated. Use "deltaTime" instead.' );
  22415. return deltaTime.mul( timeScale );
  22416. };
  22417. /**
  22418. * Generates a sine wave oscillation based on a timer.
  22419. *
  22420. * @tsl
  22421. * @function
  22422. * @param {Node<float>} t - The timer to generate the oscillation with.
  22423. * @return {Node<float>} The oscillation node.
  22424. */
  22425. const oscSine = ( t = time ) => t.add( 0.75 ).mul( Math.PI * 2 ).sin().mul( 0.5 ).add( 0.5 );
  22426. /**
  22427. * Generates a square wave oscillation based on a timer.
  22428. *
  22429. * @tsl
  22430. * @function
  22431. * @param {Node<float>} t - The timer to generate the oscillation with.
  22432. * @return {Node<float>} The oscillation node.
  22433. */
  22434. const oscSquare = ( t = time ) => t.fract().round();
  22435. /**
  22436. * Generates a triangle wave oscillation based on a timer.
  22437. *
  22438. * @tsl
  22439. * @function
  22440. * @param {Node<float>} t - The timer to generate the oscillation with.
  22441. * @return {Node<float>} The oscillation node.
  22442. */
  22443. const oscTriangle = ( t = time ) => t.add( 0.5 ).fract().mul( 2 ).sub( 1 ).abs();
  22444. /**
  22445. * Generates a sawtooth wave oscillation based on a timer.
  22446. *
  22447. * @tsl
  22448. * @function
  22449. * @param {Node<float>} t - The timer to generate the oscillation with.
  22450. * @return {Node<float>} The oscillation node.
  22451. */
  22452. const oscSawtooth = ( t = time ) => t.fract();
  22453. /**
  22454. * Rotates the given uv coordinates around a center point
  22455. *
  22456. * @tsl
  22457. * @function
  22458. * @param {Node<vec2>} uv - The uv coordinates.
  22459. * @param {Node<float>} rotation - The rotation defined in radians.
  22460. * @param {Node<vec2>} center - The center of rotation
  22461. * @return {Node<vec2>} The rotated uv coordinates.
  22462. */
  22463. const rotateUV = /*@__PURE__*/ Fn( ( [ uv, rotation, center = vec2( 0.5 ) ] ) => {
  22464. return rotate( uv.sub( center ), rotation ).add( center );
  22465. } );
  22466. /**
  22467. * Applies a spherical warping effect to the given uv coordinates.
  22468. *
  22469. * @tsl
  22470. * @function
  22471. * @param {Node<vec2>} uv - The uv coordinates.
  22472. * @param {Node<float>} strength - The strength of the effect.
  22473. * @param {Node<vec2>} center - The center point
  22474. * @return {Node<vec2>} The updated uv coordinates.
  22475. */
  22476. const spherizeUV = /*@__PURE__*/ Fn( ( [ uv, strength, center = vec2( 0.5 ) ] ) => {
  22477. const delta = uv.sub( center );
  22478. const delta2 = delta.dot( delta );
  22479. const delta4 = delta2.mul( delta2 );
  22480. const deltaOffset = delta4.mul( strength );
  22481. return uv.add( delta.mul( deltaOffset ) );
  22482. } );
  22483. /**
  22484. * This can be used to achieve a billboarding behavior for flat meshes. That means they are
  22485. * oriented always towards the camera.
  22486. *
  22487. * ```js
  22488. * material.vertexNode = billboarding();
  22489. * ```
  22490. *
  22491. * @tsl
  22492. * @function
  22493. * @param {Object} config - The configuration object.
  22494. * @param {?Node<vec3>} [config.position=null] - Can be used to define the vertex positions in world space.
  22495. * @param {boolean} [config.horizontal=true] - Whether to follow the camera rotation horizontally or not.
  22496. * @param {boolean} [config.vertical=false] - Whether to follow the camera rotation vertically or not.
  22497. * @return {Node<vec3>} The updated vertex position in clip space.
  22498. */
  22499. const billboarding = /*@__PURE__*/ Fn( ( { position = null, horizontal = true, vertical = false } ) => {
  22500. let worldMatrix;
  22501. if ( position !== null ) {
  22502. worldMatrix = modelWorldMatrix.toVar();
  22503. worldMatrix[ 3 ][ 0 ] = position.x;
  22504. worldMatrix[ 3 ][ 1 ] = position.y;
  22505. worldMatrix[ 3 ][ 2 ] = position.z;
  22506. } else {
  22507. worldMatrix = modelWorldMatrix;
  22508. }
  22509. const modelViewMatrix = cameraViewMatrix.mul( worldMatrix );
  22510. if ( defined( horizontal ) ) {
  22511. modelViewMatrix[ 0 ][ 0 ] = modelWorldMatrix[ 0 ].length();
  22512. modelViewMatrix[ 0 ][ 1 ] = 0;
  22513. modelViewMatrix[ 0 ][ 2 ] = 0;
  22514. }
  22515. if ( defined( vertical ) ) {
  22516. modelViewMatrix[ 1 ][ 0 ] = 0;
  22517. modelViewMatrix[ 1 ][ 1 ] = modelWorldMatrix[ 1 ].length();
  22518. modelViewMatrix[ 1 ][ 2 ] = 0;
  22519. }
  22520. modelViewMatrix[ 2 ][ 0 ] = 0;
  22521. modelViewMatrix[ 2 ][ 1 ] = 0;
  22522. modelViewMatrix[ 2 ][ 2 ] = 1;
  22523. return cameraProjectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  22524. } );
  22525. /**
  22526. * A special version of a screen uv function that involves a depth comparison
  22527. * when computing the final uvs. The function mitigates visual errors when
  22528. * using viewport texture nodes for refraction purposes. Without this function
  22529. * objects in front of a refractive surface might appear on the refractive surface
  22530. * which is incorrect.
  22531. *
  22532. * @tsl
  22533. * @function
  22534. * @param {?Node<vec2>} uv - Optional uv coordinates. By default `screenUV` is used.
  22535. * @return {Node<vec2>} The update uv coordinates.
  22536. */
  22537. const viewportSafeUV = /*@__PURE__*/ Fn( ( [ uv = null ] ) => {
  22538. const depth = linearDepth();
  22539. const depthDiff = linearDepth( viewportDepthTexture( uv ) ).sub( depth );
  22540. const finalUV = depthDiff.lessThan( 0 ).select( screenUV, uv );
  22541. return finalUV;
  22542. } );
  22543. /**
  22544. * Can be used to compute texture coordinates for animated sprite sheets.
  22545. *
  22546. * ```js
  22547. * const uvNode = spritesheetUV( vec2( 6, 6 ), uv(), time.mul( animationSpeed ) );
  22548. *
  22549. * material.colorNode = texture( spriteSheet, uvNode );
  22550. * ```
  22551. *
  22552. * @augments Node
  22553. */
  22554. class SpriteSheetUVNode extends Node {
  22555. static get type() {
  22556. return 'SpriteSheetUVNode';
  22557. }
  22558. /**
  22559. * Constructs a new sprite sheet uv node.
  22560. *
  22561. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22562. * @param {Node<vec2>} [uvNode=uv()] - The uv node.
  22563. * @param {Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  22564. */
  22565. constructor( countNode, uvNode = uv(), frameNode = float( 0 ) ) {
  22566. super( 'vec2' );
  22567. /**
  22568. * The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22569. *
  22570. * @type {Node<vec2>}
  22571. */
  22572. this.countNode = countNode;
  22573. /**
  22574. * The uv node.
  22575. *
  22576. * @type {Node<vec2>}
  22577. */
  22578. this.uvNode = uvNode;
  22579. /**
  22580. * The node that defines the current frame/sprite.
  22581. *
  22582. * @type {Node<float>}
  22583. */
  22584. this.frameNode = frameNode;
  22585. }
  22586. setup() {
  22587. const { frameNode, uvNode, countNode } = this;
  22588. const { width, height } = countNode;
  22589. const frameNum = frameNode.mod( width.mul( height ) ).floor();
  22590. const column = frameNum.mod( width );
  22591. const row = height.sub( frameNum.add( 1 ).div( width ).ceil() );
  22592. const scale = countNode.reciprocal();
  22593. const uvFrameOffset = vec2( column, row );
  22594. return uvNode.add( uvFrameOffset ).mul( scale );
  22595. }
  22596. }
  22597. /**
  22598. * TSL function for creating a sprite sheet uv node.
  22599. *
  22600. * @tsl
  22601. * @function
  22602. * @param {Node<vec2>} countNode - The node that defines the number of sprites in the x and y direction (e.g 6x6).
  22603. * @param {?Node<vec2>} [uvNode=uv()] - The uv node.
  22604. * @param {?Node<float>} [frameNode=float()] - The node that defines the current frame/sprite.
  22605. * @returns {SpriteSheetUVNode}
  22606. */
  22607. const spritesheetUV = /*@__PURE__*/ nodeProxy( SpriteSheetUVNode ).setParameterLength( 3 );
  22608. /**
  22609. * Can be used for triplanar texture mapping.
  22610. *
  22611. * ```js
  22612. * material.colorNode = triplanarTexture( texture( diffuseMap ) );
  22613. * ```
  22614. *
  22615. * @augments Node
  22616. */
  22617. class TriplanarTexturesNode extends Node {
  22618. static get type() {
  22619. return 'TriplanarTexturesNode';
  22620. }
  22621. /**
  22622. * Constructs a new triplanar textures node.
  22623. *
  22624. * @param {Node} textureXNode - First texture node.
  22625. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22626. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22627. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22628. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22629. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22630. */
  22631. constructor( textureXNode, textureYNode = null, textureZNode = null, scaleNode = float( 1 ), positionNode = positionLocal, normalNode = normalLocal ) {
  22632. super( 'vec4' );
  22633. /**
  22634. * First texture node.
  22635. *
  22636. * @type {Node}
  22637. */
  22638. this.textureXNode = textureXNode;
  22639. /**
  22640. * Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22641. *
  22642. * @type {?Node}
  22643. * @default null
  22644. */
  22645. this.textureYNode = textureYNode;
  22646. /**
  22647. * Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22648. *
  22649. * @type {?Node}
  22650. * @default null
  22651. */
  22652. this.textureZNode = textureZNode;
  22653. /**
  22654. * The scale node.
  22655. *
  22656. * @type {Node<float>}
  22657. * @default float(1)
  22658. */
  22659. this.scaleNode = scaleNode;
  22660. /**
  22661. * Vertex positions in local space.
  22662. *
  22663. * @type {Node<vec3>}
  22664. * @default positionLocal
  22665. */
  22666. this.positionNode = positionNode;
  22667. /**
  22668. * Normals in local space.
  22669. *
  22670. * @type {Node<vec3>}
  22671. * @default normalLocal
  22672. */
  22673. this.normalNode = normalNode;
  22674. }
  22675. setup() {
  22676. const { textureXNode, textureYNode, textureZNode, scaleNode, positionNode, normalNode } = this;
  22677. // Ref: https://github.com/keijiro/StandardTriplanar
  22678. // Blending factor of triplanar mapping
  22679. let bf = normalNode.abs().normalize();
  22680. bf = bf.div( bf.dot( vec3( 1.0 ) ) );
  22681. // Triplanar mapping
  22682. const tx = positionNode.yz.mul( scaleNode );
  22683. const ty = positionNode.zx.mul( scaleNode );
  22684. const tz = positionNode.xy.mul( scaleNode );
  22685. // Base color
  22686. const textureX = textureXNode.value;
  22687. const textureY = textureYNode !== null ? textureYNode.value : textureX;
  22688. const textureZ = textureZNode !== null ? textureZNode.value : textureX;
  22689. const cx = texture( textureX, tx ).mul( bf.x );
  22690. const cy = texture( textureY, ty ).mul( bf.y );
  22691. const cz = texture( textureZ, tz ).mul( bf.z );
  22692. return add( cx, cy, cz );
  22693. }
  22694. }
  22695. /**
  22696. * TSL function for creating a triplanar textures node.
  22697. *
  22698. * @tsl
  22699. * @function
  22700. * @param {Node} textureXNode - First texture node.
  22701. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22702. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22703. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22704. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22705. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22706. * @returns {TriplanarTexturesNode}
  22707. */
  22708. const triplanarTextures = /*@__PURE__*/ nodeProxy( TriplanarTexturesNode ).setParameterLength( 1, 6 );
  22709. /**
  22710. * TSL function for creating a triplanar textures node.
  22711. *
  22712. * @tsl
  22713. * @function
  22714. * @param {Node} textureXNode - First texture node.
  22715. * @param {?Node} [textureYNode=null] - Second texture node. When not set, the shader will sample from `textureXNode` instead.
  22716. * @param {?Node} [textureZNode=null] - Third texture node. When not set, the shader will sample from `textureXNode` instead.
  22717. * @param {?Node<float>} [scaleNode=float(1)] - The scale node.
  22718. * @param {?Node<vec3>} [positionNode=positionLocal] - Vertex positions in local space.
  22719. * @param {?Node<vec3>} [normalNode=normalLocal] - Normals in local space.
  22720. * @returns {TriplanarTexturesNode}
  22721. */
  22722. const triplanarTexture = ( ...params ) => triplanarTextures( ...params );
  22723. const _reflectorPlane = new Plane();
  22724. const _normal = new Vector3();
  22725. const _reflectorWorldPosition = new Vector3();
  22726. const _cameraWorldPosition = new Vector3();
  22727. const _rotationMatrix = new Matrix4();
  22728. const _lookAtPosition = new Vector3( 0, 0, -1 );
  22729. const clipPlane = new Vector4();
  22730. const _view = new Vector3();
  22731. const _target = new Vector3();
  22732. const _q = new Vector4();
  22733. const _size$2 = new Vector2();
  22734. const _defaultRT = new RenderTarget();
  22735. const _defaultUV = screenUV.flipX();
  22736. _defaultRT.depthTexture = new DepthTexture( 1, 1 );
  22737. let _inReflector = false;
  22738. /**
  22739. * This node can be used to implement mirror-like flat reflective surfaces.
  22740. *
  22741. * ```js
  22742. * const groundReflector = reflector();
  22743. * material.colorNode = groundReflector;
  22744. *
  22745. * const plane = new Mesh( geometry, material );
  22746. * plane.add( groundReflector.target );
  22747. * ```
  22748. *
  22749. * @augments TextureNode
  22750. */
  22751. class ReflectorNode extends TextureNode {
  22752. static get type() {
  22753. return 'ReflectorNode';
  22754. }
  22755. /**
  22756. * Constructs a new reflector node.
  22757. *
  22758. * @param {Object} [parameters={}] - An object holding configuration parameters.
  22759. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  22760. * @param {number} [parameters.resolution=1] - The resolution scale.
  22761. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  22762. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  22763. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  22764. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  22765. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  22766. */
  22767. constructor( parameters = {} ) {
  22768. super( parameters.defaultTexture || _defaultRT.texture, _defaultUV );
  22769. /**
  22770. * A reference to the internal reflector base node which holds the actual implementation.
  22771. *
  22772. * @private
  22773. * @type {ReflectorBaseNode}
  22774. * @default ReflectorBaseNode
  22775. */
  22776. this._reflectorBaseNode = parameters.reflector || new ReflectorBaseNode( this, parameters );
  22777. /**
  22778. * A reference to the internal depth node.
  22779. *
  22780. * @private
  22781. * @type {?Node}
  22782. * @default null
  22783. */
  22784. this._depthNode = null;
  22785. this.setUpdateMatrix( false );
  22786. }
  22787. /**
  22788. * A reference to the internal reflector node.
  22789. *
  22790. * @type {ReflectorBaseNode}
  22791. */
  22792. get reflector() {
  22793. return this._reflectorBaseNode;
  22794. }
  22795. /**
  22796. * A reference to 3D object the reflector is linked to.
  22797. *
  22798. * @type {Object3D}
  22799. */
  22800. get target() {
  22801. return this._reflectorBaseNode.target;
  22802. }
  22803. /**
  22804. * Returns a node representing the mirror's depth. That can be used
  22805. * to implement more advanced reflection effects like distance attenuation.
  22806. *
  22807. * @return {Node} The depth node.
  22808. */
  22809. getDepthNode() {
  22810. if ( this._depthNode === null ) {
  22811. if ( this._reflectorBaseNode.depth !== true ) {
  22812. throw new Error( 'THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ' );
  22813. }
  22814. this._depthNode = nodeObject( new ReflectorNode( {
  22815. defaultTexture: _defaultRT.depthTexture,
  22816. reflector: this._reflectorBaseNode
  22817. } ) );
  22818. }
  22819. return this._depthNode;
  22820. }
  22821. setup( builder ) {
  22822. // ignore if used in post-processing
  22823. if ( ! builder.object.isQuadMesh ) this._reflectorBaseNode.build( builder );
  22824. return super.setup( builder );
  22825. }
  22826. clone() {
  22827. const texture = new this.constructor( this.reflectorNode );
  22828. texture._reflectorBaseNode = this._reflectorBaseNode;
  22829. return texture;
  22830. }
  22831. /**
  22832. * Frees internal resources. Should be called when the node is no longer in use.
  22833. */
  22834. dispose() {
  22835. super.dispose();
  22836. this._reflectorBaseNode.dispose();
  22837. }
  22838. }
  22839. /**
  22840. * Holds the actual implementation of the reflector.
  22841. *
  22842. * TODO: Explain why `ReflectorBaseNode`. Originally the entire logic was implemented
  22843. * in `ReflectorNode`, see #29619.
  22844. *
  22845. * @private
  22846. * @augments Node
  22847. */
  22848. class ReflectorBaseNode extends Node {
  22849. static get type() {
  22850. return 'ReflectorBaseNode';
  22851. }
  22852. /**
  22853. * Constructs a new reflector base node.
  22854. *
  22855. * @param {TextureNode} textureNode - Represents the rendered reflections as a texture node.
  22856. * @param {Object} [parameters={}] - An object holding configuration parameters.
  22857. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  22858. * @param {number} [parameters.resolution=1] - The resolution scale.
  22859. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  22860. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  22861. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  22862. */
  22863. constructor( textureNode, parameters = {} ) {
  22864. super();
  22865. const {
  22866. target = new Object3D(),
  22867. resolution = 1,
  22868. generateMipmaps = false,
  22869. bounces = true,
  22870. depth = false
  22871. } = parameters;
  22872. /**
  22873. * Represents the rendered reflections as a texture node.
  22874. *
  22875. * @type {TextureNode}
  22876. */
  22877. this.textureNode = textureNode;
  22878. /**
  22879. * The 3D object the reflector is linked to.
  22880. *
  22881. * @type {Object3D}
  22882. * @default {new Object3D()}
  22883. */
  22884. this.target = target;
  22885. /**
  22886. * The resolution scale.
  22887. *
  22888. * @type {number}
  22889. * @default {1}
  22890. */
  22891. this.resolution = resolution;
  22892. /**
  22893. * Whether mipmaps should be generated or not.
  22894. *
  22895. * @type {boolean}
  22896. * @default {false}
  22897. */
  22898. this.generateMipmaps = generateMipmaps;
  22899. /**
  22900. * Whether reflectors can render other reflector nodes or not.
  22901. *
  22902. * @type {boolean}
  22903. * @default {true}
  22904. */
  22905. this.bounces = bounces;
  22906. /**
  22907. * Whether depth data should be generated or not.
  22908. *
  22909. * @type {boolean}
  22910. * @default {false}
  22911. */
  22912. this.depth = depth;
  22913. /**
  22914. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` when {@link ReflectorBaseNode#bounces}
  22915. * is `true`. Otherwise it's `NodeUpdateType.FRAME`.
  22916. *
  22917. * @type {string}
  22918. * @default 'render'
  22919. */
  22920. this.updateBeforeType = bounces ? NodeUpdateType.RENDER : NodeUpdateType.FRAME;
  22921. /**
  22922. * Weak map for managing virtual cameras.
  22923. *
  22924. * @type {WeakMap<Camera, Camera>}
  22925. */
  22926. this.virtualCameras = new WeakMap();
  22927. /**
  22928. * Weak map for managing render targets.
  22929. *
  22930. * @type {Map<Camera, RenderTarget>}
  22931. */
  22932. this.renderTargets = new Map();
  22933. /**
  22934. * Force render even if reflector is facing away from camera.
  22935. *
  22936. * @type {boolean}
  22937. * @default {false}
  22938. */
  22939. this.forceUpdate = false;
  22940. /**
  22941. * Whether the reflector has been rendered or not.
  22942. *
  22943. * When the reflector is facing away from the camera,
  22944. * this flag is set to `false` and the texture will be empty(black).
  22945. *
  22946. * @type {boolean}
  22947. * @default {false}
  22948. */
  22949. this.hasOutput = false;
  22950. }
  22951. /**
  22952. * Updates the resolution of the internal render target.
  22953. *
  22954. * @private
  22955. * @param {RenderTarget} renderTarget - The render target to resize.
  22956. * @param {Renderer} renderer - The renderer that is used to determine the new size.
  22957. */
  22958. _updateResolution( renderTarget, renderer ) {
  22959. const resolution = this.resolution;
  22960. renderer.getDrawingBufferSize( _size$2 );
  22961. renderTarget.setSize( Math.round( _size$2.width * resolution ), Math.round( _size$2.height * resolution ) );
  22962. }
  22963. setup( builder ) {
  22964. this._updateResolution( _defaultRT, builder.renderer );
  22965. return super.setup( builder );
  22966. }
  22967. /**
  22968. * Frees internal resources. Should be called when the node is no longer in use.
  22969. */
  22970. dispose() {
  22971. super.dispose();
  22972. for ( const renderTarget of this.renderTargets.values() ) {
  22973. renderTarget.dispose();
  22974. }
  22975. }
  22976. /**
  22977. * Returns a virtual camera for the given camera. The virtual camera is used to
  22978. * render the scene from the reflector's view so correct reflections can be produced.
  22979. *
  22980. * @param {Camera} camera - The scene's camera.
  22981. * @return {Camera} The corresponding virtual camera.
  22982. */
  22983. getVirtualCamera( camera ) {
  22984. let virtualCamera = this.virtualCameras.get( camera );
  22985. if ( virtualCamera === undefined ) {
  22986. virtualCamera = camera.clone();
  22987. this.virtualCameras.set( camera, virtualCamera );
  22988. }
  22989. return virtualCamera;
  22990. }
  22991. /**
  22992. * Returns a render target for the given camera. The reflections are rendered
  22993. * into this render target.
  22994. *
  22995. * @param {Camera} camera - The scene's camera.
  22996. * @return {RenderTarget} The render target.
  22997. */
  22998. getRenderTarget( camera ) {
  22999. let renderTarget = this.renderTargets.get( camera );
  23000. if ( renderTarget === undefined ) {
  23001. renderTarget = new RenderTarget( 0, 0, { type: HalfFloatType } );
  23002. if ( this.generateMipmaps === true ) {
  23003. renderTarget.texture.minFilter = LinearMipMapLinearFilter;
  23004. renderTarget.texture.generateMipmaps = true;
  23005. }
  23006. if ( this.depth === true ) {
  23007. renderTarget.depthTexture = new DepthTexture();
  23008. }
  23009. this.renderTargets.set( camera, renderTarget );
  23010. }
  23011. return renderTarget;
  23012. }
  23013. updateBefore( frame ) {
  23014. if ( this.bounces === false && _inReflector ) return false;
  23015. _inReflector = true;
  23016. const { scene, camera, renderer, material } = frame;
  23017. const { target } = this;
  23018. const virtualCamera = this.getVirtualCamera( camera );
  23019. const renderTarget = this.getRenderTarget( virtualCamera );
  23020. renderer.getDrawingBufferSize( _size$2 );
  23021. this._updateResolution( renderTarget, renderer );
  23022. //
  23023. _reflectorWorldPosition.setFromMatrixPosition( target.matrixWorld );
  23024. _cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
  23025. _rotationMatrix.extractRotation( target.matrixWorld );
  23026. _normal.set( 0, 0, 1 );
  23027. _normal.applyMatrix4( _rotationMatrix );
  23028. _view.subVectors( _reflectorWorldPosition, _cameraWorldPosition );
  23029. // Avoid rendering when reflector is facing away unless forcing an update
  23030. const isFacingAway = _view.dot( _normal ) > 0;
  23031. let needsClear = false;
  23032. if ( isFacingAway === true && this.forceUpdate === false ) {
  23033. if ( this.hasOutput === false ) {
  23034. _inReflector = false;
  23035. return;
  23036. }
  23037. needsClear = true;
  23038. }
  23039. _view.reflect( _normal ).negate();
  23040. _view.add( _reflectorWorldPosition );
  23041. _rotationMatrix.extractRotation( camera.matrixWorld );
  23042. _lookAtPosition.set( 0, 0, -1 );
  23043. _lookAtPosition.applyMatrix4( _rotationMatrix );
  23044. _lookAtPosition.add( _cameraWorldPosition );
  23045. _target.subVectors( _reflectorWorldPosition, _lookAtPosition );
  23046. _target.reflect( _normal ).negate();
  23047. _target.add( _reflectorWorldPosition );
  23048. //
  23049. virtualCamera.coordinateSystem = camera.coordinateSystem;
  23050. virtualCamera.position.copy( _view );
  23051. virtualCamera.up.set( 0, 1, 0 );
  23052. virtualCamera.up.applyMatrix4( _rotationMatrix );
  23053. virtualCamera.up.reflect( _normal );
  23054. virtualCamera.lookAt( _target );
  23055. virtualCamera.near = camera.near;
  23056. virtualCamera.far = camera.far;
  23057. virtualCamera.updateMatrixWorld();
  23058. virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
  23059. // Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
  23060. // Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
  23061. _reflectorPlane.setFromNormalAndCoplanarPoint( _normal, _reflectorWorldPosition );
  23062. _reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
  23063. clipPlane.set( _reflectorPlane.normal.x, _reflectorPlane.normal.y, _reflectorPlane.normal.z, _reflectorPlane.constant );
  23064. const projectionMatrix = virtualCamera.projectionMatrix;
  23065. _q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
  23066. _q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
  23067. _q.z = -1;
  23068. _q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
  23069. // Calculate the scaled plane vector
  23070. clipPlane.multiplyScalar( 1.0 / clipPlane.dot( _q ) );
  23071. const clipBias = 0;
  23072. // Replacing the third row of the projection matrix
  23073. projectionMatrix.elements[ 2 ] = clipPlane.x;
  23074. projectionMatrix.elements[ 6 ] = clipPlane.y;
  23075. projectionMatrix.elements[ 10 ] = ( renderer.coordinateSystem === WebGPUCoordinateSystem ) ? ( clipPlane.z - clipBias ) : ( clipPlane.z + 1.0 - clipBias );
  23076. projectionMatrix.elements[ 14 ] = clipPlane.w;
  23077. //
  23078. this.textureNode.value = renderTarget.texture;
  23079. if ( this.depth === true ) {
  23080. this.textureNode.getDepthNode().value = renderTarget.depthTexture;
  23081. }
  23082. material.visible = false;
  23083. const currentRenderTarget = renderer.getRenderTarget();
  23084. const currentMRT = renderer.getMRT();
  23085. const currentAutoClear = renderer.autoClear;
  23086. renderer.setMRT( null );
  23087. renderer.setRenderTarget( renderTarget );
  23088. renderer.autoClear = true;
  23089. if ( needsClear ) {
  23090. renderer.clear();
  23091. this.hasOutput = false;
  23092. } else {
  23093. renderer.render( scene, virtualCamera );
  23094. this.hasOutput = true;
  23095. }
  23096. renderer.setMRT( currentMRT );
  23097. renderer.setRenderTarget( currentRenderTarget );
  23098. renderer.autoClear = currentAutoClear;
  23099. material.visible = true;
  23100. _inReflector = false;
  23101. this.forceUpdate = false;
  23102. }
  23103. }
  23104. /**
  23105. * TSL function for creating a reflector node.
  23106. *
  23107. * @tsl
  23108. * @function
  23109. * @param {Object} [parameters={}] - An object holding configuration parameters.
  23110. * @param {Object3D} [parameters.target=new Object3D()] - The 3D object the reflector is linked to.
  23111. * @param {number} [parameters.resolution=1] - The resolution scale.
  23112. * @param {boolean} [parameters.generateMipmaps=false] - Whether mipmaps should be generated or not.
  23113. * @param {boolean} [parameters.bounces=true] - Whether reflectors can render other reflector nodes or not.
  23114. * @param {boolean} [parameters.depth=false] - Whether depth data should be generated or not.
  23115. * @param {TextureNode} [parameters.defaultTexture] - The default texture node.
  23116. * @param {ReflectorBaseNode} [parameters.reflector] - The reflector base node.
  23117. * @returns {ReflectorNode}
  23118. */
  23119. const reflector = ( parameters ) => nodeObject( new ReflectorNode( parameters ) );
  23120. const _camera = /*@__PURE__*/ new OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  23121. /**
  23122. * The purpose of this special geometry is to fill the entire viewport with a single triangle.
  23123. *
  23124. * Reference: {@link https://github.com/mrdoob/three.js/pull/21358}
  23125. *
  23126. * @private
  23127. * @augments BufferGeometry
  23128. */
  23129. class QuadGeometry extends BufferGeometry {
  23130. /**
  23131. * Constructs a new quad geometry.
  23132. *
  23133. * @param {boolean} [flipY=false] - Whether the uv coordinates should be flipped along the vertical axis or not.
  23134. */
  23135. constructor( flipY = false ) {
  23136. super();
  23137. const uv = flipY === false ? [ 0, -1, 0, 1, 2, 1 ] : [ 0, 2, 0, 0, 2, 0 ];
  23138. this.setAttribute( 'position', new Float32BufferAttribute( [ -1, 3, 0, -1, -1, 0, 3, -1, 0 ], 3 ) );
  23139. this.setAttribute( 'uv', new Float32BufferAttribute( uv, 2 ) );
  23140. }
  23141. }
  23142. const _geometry = /*@__PURE__*/ new QuadGeometry();
  23143. /**
  23144. * This module is a helper for passes which need to render a full
  23145. * screen effect which is quite common in context of post processing.
  23146. *
  23147. * The intended usage is to reuse a single quad mesh for rendering
  23148. * subsequent passes by just reassigning the `material` reference.
  23149. *
  23150. * Note: This module can only be used with `WebGPURenderer`.
  23151. *
  23152. * @augments Mesh
  23153. */
  23154. class QuadMesh extends Mesh {
  23155. /**
  23156. * Constructs a new quad mesh.
  23157. *
  23158. * @param {?Material} [material=null] - The material to render the quad mesh with.
  23159. */
  23160. constructor( material = null ) {
  23161. super( _geometry, material );
  23162. /**
  23163. * The camera to render the quad mesh with.
  23164. *
  23165. * @type {OrthographicCamera}
  23166. * @readonly
  23167. */
  23168. this.camera = _camera;
  23169. /**
  23170. * This flag can be used for type testing.
  23171. *
  23172. * @type {boolean}
  23173. * @readonly
  23174. * @default true
  23175. */
  23176. this.isQuadMesh = true;
  23177. }
  23178. /**
  23179. * Async version of `render()`.
  23180. *
  23181. * @async
  23182. * @param {Renderer} renderer - The renderer.
  23183. * @return {Promise} A Promise that resolves when the render has been finished.
  23184. */
  23185. async renderAsync( renderer ) {
  23186. return renderer.renderAsync( this, _camera );
  23187. }
  23188. /**
  23189. * Renders the quad mesh
  23190. *
  23191. * @param {Renderer} renderer - The renderer.
  23192. */
  23193. render( renderer ) {
  23194. renderer.render( this, _camera );
  23195. }
  23196. }
  23197. const _size$1 = /*@__PURE__*/ new Vector2();
  23198. /**
  23199. * `RTTNode` takes another node and uses it with a `QuadMesh` to render into a texture (RTT).
  23200. * This module is especially relevant in context of post processing where certain nodes require
  23201. * texture input for their effects. With the helper function `convertToTexture()` which is based
  23202. * on this module, the node system can automatically ensure texture input if required.
  23203. *
  23204. * @augments TextureNode
  23205. */
  23206. class RTTNode extends TextureNode {
  23207. static get type() {
  23208. return 'RTTNode';
  23209. }
  23210. /**
  23211. * Constructs a new RTT node.
  23212. *
  23213. * @param {Node} node - The node to render a texture with.
  23214. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23215. * @param {?number} [height=null] - The height of the internal render target.
  23216. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23217. */
  23218. constructor( node, width = null, height = null, options = { type: HalfFloatType } ) {
  23219. const renderTarget = new RenderTarget( width, height, options );
  23220. super( renderTarget.texture, uv() );
  23221. /**
  23222. * The node to render a texture with.
  23223. *
  23224. * @type {Node}
  23225. */
  23226. this.node = node;
  23227. /**
  23228. * The width of the internal render target.
  23229. * If not width is applied, the render target is automatically resized.
  23230. *
  23231. * @type {?number}
  23232. * @default null
  23233. */
  23234. this.width = width;
  23235. /**
  23236. * The height of the internal render target.
  23237. *
  23238. * @type {?number}
  23239. * @default null
  23240. */
  23241. this.height = height;
  23242. /**
  23243. * The pixel ratio
  23244. *
  23245. * @type {number}
  23246. * @default 1
  23247. */
  23248. this.pixelRatio = 1;
  23249. /**
  23250. * The render target
  23251. *
  23252. * @type {RenderTarget}
  23253. */
  23254. this.renderTarget = renderTarget;
  23255. /**
  23256. * Whether the texture requires an update or not.
  23257. *
  23258. * @type {boolean}
  23259. * @default true
  23260. */
  23261. this.textureNeedsUpdate = true;
  23262. /**
  23263. * Whether the texture should automatically be updated or not.
  23264. *
  23265. * @type {boolean}
  23266. * @default true
  23267. */
  23268. this.autoUpdate = true;
  23269. /**
  23270. * The node which is used with the quad mesh for RTT.
  23271. *
  23272. * @private
  23273. * @type {Node}
  23274. * @default null
  23275. */
  23276. this._rttNode = null;
  23277. /**
  23278. * The internal quad mesh for RTT.
  23279. *
  23280. * @private
  23281. * @type {QuadMesh}
  23282. */
  23283. this._quadMesh = new QuadMesh( new NodeMaterial() );
  23284. /**
  23285. * The `updateBeforeType` is set to `NodeUpdateType.RENDER` since the node updates
  23286. * the texture once per render in its {@link RTTNode#updateBefore} method.
  23287. *
  23288. * @type {string}
  23289. * @default 'render'
  23290. */
  23291. this.updateBeforeType = NodeUpdateType.RENDER;
  23292. }
  23293. /**
  23294. * Whether the internal render target should automatically be resized or not.
  23295. *
  23296. * @type {boolean}
  23297. * @readonly
  23298. * @default true
  23299. */
  23300. get autoSize() {
  23301. return this.width === null;
  23302. }
  23303. setup( builder ) {
  23304. this._rttNode = this.node.context( builder.getSharedContext() );
  23305. this._quadMesh.material.name = 'RTT';
  23306. this._quadMesh.material.needsUpdate = true;
  23307. return super.setup( builder );
  23308. }
  23309. /**
  23310. * Sets the size of the internal render target
  23311. *
  23312. * @param {number} width - The width to set.
  23313. * @param {number} height - The width to set.
  23314. */
  23315. setSize( width, height ) {
  23316. this.width = width;
  23317. this.height = height;
  23318. const effectiveWidth = width * this.pixelRatio;
  23319. const effectiveHeight = height * this.pixelRatio;
  23320. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  23321. this.textureNeedsUpdate = true;
  23322. }
  23323. /**
  23324. * Sets the pixel ratio. This will also resize the render target.
  23325. *
  23326. * @param {number} pixelRatio - The pixel ratio to set.
  23327. */
  23328. setPixelRatio( pixelRatio ) {
  23329. this.pixelRatio = pixelRatio;
  23330. this.setSize( this.width, this.height );
  23331. }
  23332. updateBefore( { renderer } ) {
  23333. if ( this.textureNeedsUpdate === false && this.autoUpdate === false ) return;
  23334. this.textureNeedsUpdate = false;
  23335. //
  23336. if ( this.autoSize === true ) {
  23337. this.pixelRatio = renderer.getPixelRatio();
  23338. const size = renderer.getSize( _size$1 );
  23339. this.setSize( size.width, size.height );
  23340. }
  23341. //
  23342. this._quadMesh.material.fragmentNode = this._rttNode;
  23343. //
  23344. const currentRenderTarget = renderer.getRenderTarget();
  23345. renderer.setRenderTarget( this.renderTarget );
  23346. this._quadMesh.render( renderer );
  23347. renderer.setRenderTarget( currentRenderTarget );
  23348. }
  23349. clone() {
  23350. const newNode = new TextureNode( this.value, this.uvNode, this.levelNode );
  23351. newNode.sampler = this.sampler;
  23352. newNode.referenceNode = this;
  23353. return newNode;
  23354. }
  23355. }
  23356. /**
  23357. * TSL function for creating a RTT node.
  23358. *
  23359. * @tsl
  23360. * @function
  23361. * @param {Node} node - The node to render a texture with.
  23362. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23363. * @param {?number} [height=null] - The height of the internal render target.
  23364. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23365. * @returns {RTTNode}
  23366. */
  23367. const rtt = ( node, ...params ) => nodeObject( new RTTNode( nodeObject( node ), ...params ) );
  23368. /**
  23369. * TSL function for converting nodes to textures nodes.
  23370. *
  23371. * @tsl
  23372. * @function
  23373. * @param {Node} node - The node to render a texture with.
  23374. * @param {?number} [width=null] - The width of the internal render target. If not width is applied, the render target is automatically resized.
  23375. * @param {?number} [height=null] - The height of the internal render target.
  23376. * @param {Object} [options={type:HalfFloatType}] - The options for the internal render target.
  23377. * @returns {RTTNode}
  23378. */
  23379. const convertToTexture = ( node, ...params ) => {
  23380. if ( node.isTextureNode ) return node;
  23381. if ( node.isPassNode ) return node.getTextureNode();
  23382. return rtt( node, ...params );
  23383. };
  23384. /**
  23385. * Computes a position in view space based on a fragment's screen position expressed as uv coordinates, the fragments
  23386. * depth value and the camera's inverse projection matrix.
  23387. *
  23388. * @tsl
  23389. * @function
  23390. * @param {Node<vec2>} screenPosition - The fragment's screen position expressed as uv coordinates.
  23391. * @param {Node<float>} depth - The fragment's depth value.
  23392. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  23393. * @return {Node<vec3>} The fragments position in view space.
  23394. */
  23395. const getViewPosition = /*@__PURE__*/ Fn( ( [ screenPosition, depth, projectionMatrixInverse ], builder ) => {
  23396. let clipSpacePosition;
  23397. if ( builder.renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  23398. screenPosition = vec2( screenPosition.x, screenPosition.y.oneMinus() ).mul( 2.0 ).sub( 1.0 );
  23399. clipSpacePosition = vec4( vec3( screenPosition, depth ), 1.0 );
  23400. } else {
  23401. clipSpacePosition = vec4( vec3( screenPosition.x, screenPosition.y.oneMinus(), depth ).mul( 2.0 ).sub( 1.0 ), 1.0 );
  23402. }
  23403. const viewSpacePosition = vec4( projectionMatrixInverse.mul( clipSpacePosition ) );
  23404. return viewSpacePosition.xyz.div( viewSpacePosition.w );
  23405. } );
  23406. /**
  23407. * Computes a screen position expressed as uv coordinates based on a fragment's position in view space
  23408. * and the camera's projection matrix
  23409. *
  23410. * @tsl
  23411. * @function
  23412. * @param {Node<vec3>} viewPosition - The fragments position in view space.
  23413. * @param {Node<mat4>} projectionMatrix - The camera's projection matrix.
  23414. * @return {Node<vec2>} The fragment's screen position expressed as uv coordinates.
  23415. */
  23416. const getScreenPosition = /*@__PURE__*/ Fn( ( [ viewPosition, projectionMatrix ] ) => {
  23417. const sampleClipPos = projectionMatrix.mul( vec4( viewPosition, 1.0 ) );
  23418. const sampleUv = sampleClipPos.xy.div( sampleClipPos.w ).mul( 0.5 ).add( 0.5 ).toVar();
  23419. return vec2( sampleUv.x, sampleUv.y.oneMinus() );
  23420. } );
  23421. /**
  23422. * Computes a normal vector based on depth data. Can be used as a fallback when no normal render
  23423. * target is available or if flat surface normals are required.
  23424. *
  23425. * @tsl
  23426. * @function
  23427. * @param {Node<vec2>} uv - The texture coordinate.
  23428. * @param {DepthTexture} depthTexture - The depth texture.
  23429. * @param {Node<mat4>} projectionMatrixInverse - The camera's inverse projection matrix.
  23430. * @return {Node<vec3>} The computed normal vector.
  23431. */
  23432. const getNormalFromDepth = /*@__PURE__*/ Fn( ( [ uv, depthTexture, projectionMatrixInverse ] ) => {
  23433. const size = textureSize( textureLoad( depthTexture ) );
  23434. const p = ivec2( uv.mul( size ) ).toVar();
  23435. const c0 = textureLoad( depthTexture, p ).toVar();
  23436. const l2 = textureLoad( depthTexture, p.sub( ivec2( 2, 0 ) ) ).toVar();
  23437. const l1 = textureLoad( depthTexture, p.sub( ivec2( 1, 0 ) ) ).toVar();
  23438. const r1 = textureLoad( depthTexture, p.add( ivec2( 1, 0 ) ) ).toVar();
  23439. const r2 = textureLoad( depthTexture, p.add( ivec2( 2, 0 ) ) ).toVar();
  23440. const b2 = textureLoad( depthTexture, p.add( ivec2( 0, 2 ) ) ).toVar();
  23441. const b1 = textureLoad( depthTexture, p.add( ivec2( 0, 1 ) ) ).toVar();
  23442. const t1 = textureLoad( depthTexture, p.sub( ivec2( 0, 1 ) ) ).toVar();
  23443. const t2 = textureLoad( depthTexture, p.sub( ivec2( 0, 2 ) ) ).toVar();
  23444. const dl = abs( sub( float( 2 ).mul( l1 ).sub( l2 ), c0 ) ).toVar();
  23445. const dr = abs( sub( float( 2 ).mul( r1 ).sub( r2 ), c0 ) ).toVar();
  23446. const db = abs( sub( float( 2 ).mul( b1 ).sub( b2 ), c0 ) ).toVar();
  23447. const dt = abs( sub( float( 2 ).mul( t1 ).sub( t2 ), c0 ) ).toVar();
  23448. const ce = getViewPosition( uv, c0, projectionMatrixInverse ).toVar();
  23449. 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 ) ) );
  23450. 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 ) ) );
  23451. return normalize( cross( dpdx, dpdy ) );
  23452. } );
  23453. /**
  23454. * This special type of instanced buffer attribute is intended for compute shaders.
  23455. * In earlier three.js versions it was only possible to update attribute data
  23456. * on the CPU via JavaScript and then upload the data to the GPU. With the
  23457. * new material system and renderer it is now possible to use compute shaders
  23458. * to compute the data for an attribute more efficiently on the GPU.
  23459. *
  23460. * The idea is to create an instance of this class and provide it as an input
  23461. * to {@link StorageBufferNode}.
  23462. *
  23463. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  23464. *
  23465. * @augments InstancedBufferAttribute
  23466. */
  23467. class StorageInstancedBufferAttribute extends InstancedBufferAttribute {
  23468. /**
  23469. * Constructs a new storage instanced buffer attribute.
  23470. *
  23471. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  23472. * The subsequent parameters are then obsolete.
  23473. * @param {number} itemSize - The item size.
  23474. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  23475. */
  23476. constructor( count, itemSize, typeClass = Float32Array ) {
  23477. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  23478. super( array, itemSize );
  23479. /**
  23480. * This flag can be used for type testing.
  23481. *
  23482. * @type {boolean}
  23483. * @readonly
  23484. * @default true
  23485. */
  23486. this.isStorageInstancedBufferAttribute = true;
  23487. }
  23488. }
  23489. /**
  23490. * This special type of buffer attribute is intended for compute shaders.
  23491. * In earlier three.js versions it was only possible to update attribute data
  23492. * on the CPU via JavaScript and then upload the data to the GPU. With the
  23493. * new material system and renderer it is now possible to use compute shaders
  23494. * to compute the data for an attribute more efficiently on the GPU.
  23495. *
  23496. * The idea is to create an instance of this class and provide it as an input
  23497. * to {@link StorageBufferNode}.
  23498. *
  23499. * Note: This type of buffer attribute can only be used with `WebGPURenderer`.
  23500. *
  23501. * @augments BufferAttribute
  23502. */
  23503. class StorageBufferAttribute extends BufferAttribute {
  23504. /**
  23505. * Constructs a new storage buffer attribute.
  23506. *
  23507. * @param {number|TypedArray} count - The item count. It is also valid to pass a typed array as an argument.
  23508. * The subsequent parameters are then obsolete.
  23509. * @param {number} itemSize - The item size.
  23510. * @param {TypedArray.constructor} [typeClass=Float32Array] - A typed array constructor.
  23511. */
  23512. constructor( count, itemSize, typeClass = Float32Array ) {
  23513. const array = ArrayBuffer.isView( count ) ? count : new typeClass( count * itemSize );
  23514. super( array, itemSize );
  23515. /**
  23516. * This flag can be used for type testing.
  23517. *
  23518. * @type {boolean}
  23519. * @readonly
  23520. * @default true
  23521. */
  23522. this.isStorageBufferAttribute = true;
  23523. }
  23524. }
  23525. /**
  23526. * TSL function for creating a storage buffer node with a configured `StorageBufferAttribute`.
  23527. *
  23528. * @tsl
  23529. * @function
  23530. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  23531. * @param {string|Struct} [type='float'] - The data type.
  23532. * @returns {StorageBufferNode}
  23533. */
  23534. const attributeArray = ( count, type = 'float' ) => {
  23535. let itemSize, typedArray;
  23536. if ( type.isStruct === true ) {
  23537. itemSize = type.layout.getLength();
  23538. typedArray = getTypedArrayFromType( 'float' );
  23539. } else {
  23540. itemSize = getLengthFromType( type );
  23541. typedArray = getTypedArrayFromType( type );
  23542. }
  23543. const buffer = new StorageBufferAttribute( count, itemSize, typedArray );
  23544. const node = storage( buffer, type, count );
  23545. return node;
  23546. };
  23547. /**
  23548. * TSL function for creating a storage buffer node with a configured `StorageInstancedBufferAttribute`.
  23549. *
  23550. * @tsl
  23551. * @function
  23552. * @param {number|TypedArray} count - The data count. It is also valid to pass a typed array as an argument.
  23553. * @param {string|Struct} [type='float'] - The data type.
  23554. * @returns {StorageBufferNode}
  23555. */
  23556. const instancedArray = ( count, type = 'float' ) => {
  23557. let itemSize, typedArray;
  23558. if ( type.isStruct === true ) {
  23559. itemSize = type.layout.getLength();
  23560. typedArray = getTypedArrayFromType( 'float' );
  23561. } else {
  23562. itemSize = getLengthFromType( type );
  23563. typedArray = getTypedArrayFromType( type );
  23564. }
  23565. const buffer = new StorageInstancedBufferAttribute( count, itemSize, typedArray );
  23566. const node = storage( buffer, type, count );
  23567. return node;
  23568. };
  23569. /**
  23570. * A node for representing the uv coordinates of points.
  23571. *
  23572. * Can only be used with a WebGL backend. In WebGPU, point
  23573. * primitives always have the size of one pixel and can thus
  23574. * can't be used as sprite-like objects that display textures.
  23575. *
  23576. * @augments Node
  23577. */
  23578. class PointUVNode extends Node {
  23579. static get type() {
  23580. return 'PointUVNode';
  23581. }
  23582. /**
  23583. * Constructs a new point uv node.
  23584. */
  23585. constructor() {
  23586. super( 'vec2' );
  23587. /**
  23588. * This flag can be used for type testing.
  23589. *
  23590. * @type {boolean}
  23591. * @readonly
  23592. * @default true
  23593. */
  23594. this.isPointUVNode = true;
  23595. }
  23596. generate( /*builder*/ ) {
  23597. return 'vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )';
  23598. }
  23599. }
  23600. /**
  23601. * TSL object that represents the uv coordinates of points.
  23602. *
  23603. * @tsl
  23604. * @type {PointUVNode}
  23605. */
  23606. const pointUV = /*@__PURE__*/ nodeImmutable( PointUVNode );
  23607. const _e1 = /*@__PURE__*/ new Euler();
  23608. const _m1 = /*@__PURE__*/ new Matrix4();
  23609. /**
  23610. * This module allows access to a collection of scene properties. The following predefined TSL objects
  23611. * are available for easier use:
  23612. *
  23613. * - `backgroundBlurriness`: A node that represents the scene's background blurriness.
  23614. * - `backgroundIntensity`: A node that represents the scene's background intensity.
  23615. * - `backgroundRotation`: A node that represents the scene's background rotation.
  23616. *
  23617. * @augments Node
  23618. */
  23619. class SceneNode extends Node {
  23620. static get type() {
  23621. return 'SceneNode';
  23622. }
  23623. /**
  23624. * Constructs a new scene node.
  23625. *
  23626. * @param {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')} scope - The scope defines the type of scene property that is accessed.
  23627. * @param {?Scene} [scene=null] - A reference to the scene.
  23628. */
  23629. constructor( scope = SceneNode.BACKGROUND_BLURRINESS, scene = null ) {
  23630. super();
  23631. /**
  23632. * The scope defines the type of scene property that is accessed.
  23633. *
  23634. * @type {('backgroundBlurriness'|'backgroundIntensity'|'backgroundRotation')}
  23635. */
  23636. this.scope = scope;
  23637. /**
  23638. * A reference to the scene that is going to be accessed.
  23639. *
  23640. * @type {?Scene}
  23641. * @default null
  23642. */
  23643. this.scene = scene;
  23644. }
  23645. /**
  23646. * Depending on the scope, the method returns a different type of node that represents
  23647. * the respective scene property.
  23648. *
  23649. * @param {NodeBuilder} builder - The current node builder.
  23650. * @return {Node} The output node.
  23651. */
  23652. setup( builder ) {
  23653. const scope = this.scope;
  23654. const scene = this.scene !== null ? this.scene : builder.scene;
  23655. let output;
  23656. if ( scope === SceneNode.BACKGROUND_BLURRINESS ) {
  23657. output = reference( 'backgroundBlurriness', 'float', scene );
  23658. } else if ( scope === SceneNode.BACKGROUND_INTENSITY ) {
  23659. output = reference( 'backgroundIntensity', 'float', scene );
  23660. } else if ( scope === SceneNode.BACKGROUND_ROTATION ) {
  23661. output = uniform( 'mat4' ).label( 'backgroundRotation' ).setGroup( renderGroup ).onRenderUpdate( () => {
  23662. const background = scene.background;
  23663. if ( background !== null && background.isTexture && background.mapping !== UVMapping ) {
  23664. _e1.copy( scene.backgroundRotation );
  23665. // accommodate left-handed frame
  23666. _e1.x *= -1; _e1.y *= -1; _e1.z *= -1;
  23667. _m1.makeRotationFromEuler( _e1 );
  23668. } else {
  23669. _m1.identity();
  23670. }
  23671. return _m1;
  23672. } );
  23673. } else {
  23674. console.error( 'THREE.SceneNode: Unknown scope:', scope );
  23675. }
  23676. return output;
  23677. }
  23678. }
  23679. SceneNode.BACKGROUND_BLURRINESS = 'backgroundBlurriness';
  23680. SceneNode.BACKGROUND_INTENSITY = 'backgroundIntensity';
  23681. SceneNode.BACKGROUND_ROTATION = 'backgroundRotation';
  23682. /**
  23683. * TSL object that represents the scene's background blurriness.
  23684. *
  23685. * @tsl
  23686. * @type {SceneNode}
  23687. */
  23688. const backgroundBlurriness = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_BLURRINESS );
  23689. /**
  23690. * TSL object that represents the scene's background intensity.
  23691. *
  23692. * @tsl
  23693. * @type {SceneNode}
  23694. */
  23695. const backgroundIntensity = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_INTENSITY );
  23696. /**
  23697. * TSL object that represents the scene's background rotation.
  23698. *
  23699. * @tsl
  23700. * @type {SceneNode}
  23701. */
  23702. const backgroundRotation = /*@__PURE__*/ nodeImmutable( SceneNode, SceneNode.BACKGROUND_ROTATION );
  23703. /**
  23704. * This special version of a texture node can be used to
  23705. * write data into a storage texture with a compute shader.
  23706. *
  23707. * ```js
  23708. * const storageTexture = new THREE.StorageTexture( width, height );
  23709. *
  23710. * const computeTexture = Fn( ( { storageTexture } ) => {
  23711. *
  23712. * const posX = instanceIndex.mod( width );
  23713. * const posY = instanceIndex.div( width );
  23714. * const indexUV = uvec2( posX, posY );
  23715. *
  23716. * // generate RGB values
  23717. *
  23718. * const r = 1;
  23719. * const g = 1;
  23720. * const b = 1;
  23721. *
  23722. * textureStore( storageTexture, indexUV, vec4( r, g, b, 1 ) ).toWriteOnly();
  23723. *
  23724. * } );
  23725. *
  23726. * const computeNode = computeTexture( { storageTexture } ).compute( width * height );
  23727. * renderer.computeAsync( computeNode );
  23728. * ```
  23729. *
  23730. * This node can only be used with a WebGPU backend.
  23731. *
  23732. * @augments TextureNode
  23733. */
  23734. class StorageTextureNode extends TextureNode {
  23735. static get type() {
  23736. return 'StorageTextureNode';
  23737. }
  23738. /**
  23739. * Constructs a new storage texture node.
  23740. *
  23741. * @param {StorageTexture} value - The storage texture.
  23742. * @param {Node<vec2|vec3>} uvNode - The uv node.
  23743. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23744. */
  23745. constructor( value, uvNode, storeNode = null ) {
  23746. super( value, uvNode );
  23747. /**
  23748. * The value node that should be stored in the texture.
  23749. *
  23750. * @type {?Node}
  23751. * @default null
  23752. */
  23753. this.storeNode = storeNode;
  23754. /**
  23755. * This flag can be used for type testing.
  23756. *
  23757. * @type {boolean}
  23758. * @readonly
  23759. * @default true
  23760. */
  23761. this.isStorageTextureNode = true;
  23762. /**
  23763. * The access type of the texture node.
  23764. *
  23765. * @type {string}
  23766. * @default 'writeOnly'
  23767. */
  23768. this.access = NodeAccess.WRITE_ONLY;
  23769. }
  23770. /**
  23771. * Overwrites the default implementation to return a fixed value `'storageTexture'`.
  23772. *
  23773. * @param {NodeBuilder} builder - The current node builder.
  23774. * @return {string} The input type.
  23775. */
  23776. getInputType( /*builder*/ ) {
  23777. return 'storageTexture';
  23778. }
  23779. setup( builder ) {
  23780. super.setup( builder );
  23781. const properties = builder.getNodeProperties( this );
  23782. properties.storeNode = this.storeNode;
  23783. return properties;
  23784. }
  23785. /**
  23786. * Defines the node access.
  23787. *
  23788. * @param {string} value - The node access.
  23789. * @return {StorageTextureNode} A reference to this node.
  23790. */
  23791. setAccess( value ) {
  23792. this.access = value;
  23793. return this;
  23794. }
  23795. /**
  23796. * Generates the code snippet of the storage node. If no `storeNode`
  23797. * is defined, the texture node is generated as normal texture.
  23798. *
  23799. * @param {NodeBuilder} builder - The current node builder.
  23800. * @param {string} output - The current output.
  23801. * @return {string} The generated code snippet.
  23802. */
  23803. generate( builder, output ) {
  23804. let snippet;
  23805. if ( this.storeNode !== null ) {
  23806. snippet = this.generateStore( builder );
  23807. } else {
  23808. snippet = super.generate( builder, output );
  23809. }
  23810. return snippet;
  23811. }
  23812. /**
  23813. * Convenience method for configuring a read/write node access.
  23814. *
  23815. * @return {StorageTextureNode} A reference to this node.
  23816. */
  23817. toReadWrite() {
  23818. return this.setAccess( NodeAccess.READ_WRITE );
  23819. }
  23820. /**
  23821. * Convenience method for configuring a read-only node access.
  23822. *
  23823. * @return {StorageTextureNode} A reference to this node.
  23824. */
  23825. toReadOnly() {
  23826. return this.setAccess( NodeAccess.READ_ONLY );
  23827. }
  23828. /**
  23829. * Convenience method for configuring a write-only node access.
  23830. *
  23831. * @return {StorageTextureNode} A reference to this node.
  23832. */
  23833. toWriteOnly() {
  23834. return this.setAccess( NodeAccess.WRITE_ONLY );
  23835. }
  23836. /**
  23837. * Generates the code snippet of the storage texture node.
  23838. *
  23839. * @param {NodeBuilder} builder - The current node builder.
  23840. */
  23841. generateStore( builder ) {
  23842. const properties = builder.getNodeProperties( this );
  23843. const { uvNode, storeNode, depthNode } = properties;
  23844. const textureProperty = super.generate( builder, 'property' );
  23845. const uvSnippet = uvNode.build( builder, 'uvec2' );
  23846. const storeSnippet = storeNode.build( builder, 'vec4' );
  23847. const depthSnippet = depthNode ? depthNode.build( builder, 'int' ) : null;
  23848. const snippet = builder.generateTextureStore( builder, textureProperty, uvSnippet, depthSnippet, storeSnippet );
  23849. builder.addLineFlowCode( snippet, this );
  23850. }
  23851. clone() {
  23852. const newNode = super.clone();
  23853. newNode.storeNode = this.storeNode;
  23854. return newNode;
  23855. }
  23856. }
  23857. /**
  23858. * TSL function for creating a storage texture node.
  23859. *
  23860. * @tsl
  23861. * @function
  23862. * @param {StorageTexture} value - The storage texture.
  23863. * @param {?Node<vec2|vec3>} uvNode - The uv node.
  23864. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23865. * @returns {StorageTextureNode}
  23866. */
  23867. const storageTexture = /*@__PURE__*/ nodeProxy( StorageTextureNode ).setParameterLength( 1, 3 );
  23868. /**
  23869. * TODO: Explain difference to `storageTexture()`.
  23870. *
  23871. * @tsl
  23872. * @function
  23873. * @param {StorageTexture} value - The storage texture.
  23874. * @param {Node<vec2|vec3>} uvNode - The uv node.
  23875. * @param {?Node} [storeNode=null] - The value node that should be stored in the texture.
  23876. * @returns {StorageTextureNode}
  23877. */
  23878. const textureStore = ( value, uvNode, storeNode ) => {
  23879. const node = storageTexture( value, uvNode, storeNode );
  23880. if ( storeNode !== null ) node.toStack();
  23881. return node;
  23882. };
  23883. const normal = Fn( ( { texture, uv } ) => {
  23884. const epsilon = 0.0001;
  23885. const ret = vec3().toVar();
  23886. If( uv.x.lessThan( epsilon ), () => {
  23887. ret.assign( vec3( 1, 0, 0 ) );
  23888. } ).ElseIf( uv.y.lessThan( epsilon ), () => {
  23889. ret.assign( vec3( 0, 1, 0 ) );
  23890. } ).ElseIf( uv.z.lessThan( epsilon ), () => {
  23891. ret.assign( vec3( 0, 0, 1 ) );
  23892. } ).ElseIf( uv.x.greaterThan( 1 - epsilon ), () => {
  23893. ret.assign( vec3( -1, 0, 0 ) );
  23894. } ).ElseIf( uv.y.greaterThan( 1 - epsilon ), () => {
  23895. ret.assign( vec3( 0, -1, 0 ) );
  23896. } ).ElseIf( uv.z.greaterThan( 1 - epsilon ), () => {
  23897. ret.assign( vec3( 0, 0, -1 ) );
  23898. } ).Else( () => {
  23899. const step = 0.01;
  23900. const x = texture.sample( uv.add( vec3( -0.01, 0.0, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( step, 0.0, 0.0 ) ) ).r );
  23901. const y = texture.sample( uv.add( vec3( 0.0, -0.01, 0.0 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, step, 0.0 ) ) ).r );
  23902. const z = texture.sample( uv.add( vec3( 0.0, 0.0, -0.01 ) ) ).r.sub( texture.sample( uv.add( vec3( 0.0, 0.0, step ) ) ).r );
  23903. ret.assign( vec3( x, y, z ) );
  23904. } );
  23905. return ret.normalize();
  23906. } );
  23907. /**
  23908. * This type of uniform node represents a 3D texture.
  23909. *
  23910. * @augments TextureNode
  23911. */
  23912. class Texture3DNode extends TextureNode {
  23913. static get type() {
  23914. return 'Texture3DNode';
  23915. }
  23916. /**
  23917. * Constructs a new 3D texture node.
  23918. *
  23919. * @param {Data3DTexture} value - The 3D texture.
  23920. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  23921. * @param {?Node<int>} [levelNode=null] - The level node.
  23922. */
  23923. constructor( value, uvNode = null, levelNode = null ) {
  23924. super( value, uvNode, levelNode );
  23925. /**
  23926. * This flag can be used for type testing.
  23927. *
  23928. * @type {boolean}
  23929. * @readonly
  23930. * @default true
  23931. */
  23932. this.isTexture3DNode = true;
  23933. }
  23934. /**
  23935. * Overwrites the default implementation to return a fixed value `'texture3D'`.
  23936. *
  23937. * @param {NodeBuilder} builder - The current node builder.
  23938. * @return {string} The input type.
  23939. */
  23940. getInputType( /*builder*/ ) {
  23941. return 'texture3D';
  23942. }
  23943. /**
  23944. * Returns a default uv node which is in context of 3D textures a three-dimensional
  23945. * uv node.
  23946. *
  23947. * @return {Node<vec3>} The default uv node.
  23948. */
  23949. getDefaultUV() {
  23950. return vec3( 0.5, 0.5, 0.5 );
  23951. }
  23952. /**
  23953. * Overwritten with an empty implementation since the `updateMatrix` flag is ignored
  23954. * for 3D textures. The uv transformation matrix is not applied to 3D textures.
  23955. *
  23956. * @param {boolean} value - The update toggle.
  23957. */
  23958. setUpdateMatrix( /*value*/ ) { } // Ignore .updateMatrix for 3d TextureNode
  23959. /**
  23960. * Overwrites the default implementation to return the unmodified uv node.
  23961. *
  23962. * @param {NodeBuilder} builder - The current node builder.
  23963. * @param {Node} uvNode - The uv node to setup.
  23964. * @return {Node} The unmodified uv node.
  23965. */
  23966. setupUV( builder, uvNode ) {
  23967. const texture = this.value;
  23968. if ( builder.isFlipY() && ( texture.isRenderTargetTexture === true || texture.isFramebufferTexture === true ) ) {
  23969. if ( this.sampler ) {
  23970. uvNode = uvNode.flipY();
  23971. } else {
  23972. uvNode = uvNode.setY( int( textureSize( this, this.levelNode ).y ).sub( uvNode.y ).sub( 1 ) );
  23973. }
  23974. }
  23975. return uvNode;
  23976. }
  23977. /**
  23978. * Generates the uv code snippet.
  23979. *
  23980. * @param {NodeBuilder} builder - The current node builder.
  23981. * @param {Node} uvNode - The uv node to generate code for.
  23982. * @return {string} The generated code snippet.
  23983. */
  23984. generateUV( builder, uvNode ) {
  23985. return uvNode.build( builder, 'vec3' );
  23986. }
  23987. /**
  23988. * TODO.
  23989. *
  23990. * @param {Node<vec3>} uvNode - The uv node .
  23991. * @return {Node<vec3>} TODO.
  23992. */
  23993. normal( uvNode ) {
  23994. return normal( { texture: this, uv: uvNode } );
  23995. }
  23996. }
  23997. /**
  23998. * TSL function for creating a 3D texture node.
  23999. *
  24000. * @tsl
  24001. * @function
  24002. * @param {Data3DTexture} value - The 3D texture.
  24003. * @param {?Node<vec2|vec3>} [uvNode=null] - The uv node.
  24004. * @param {?Node<int>} [levelNode=null] - The level node.
  24005. * @returns {Texture3DNode}
  24006. */
  24007. const texture3D = /*@__PURE__*/ nodeProxy( Texture3DNode ).setParameterLength( 1, 3 );
  24008. /**
  24009. * A special type of reference node that allows to link values in
  24010. * `userData` fields to node objects.
  24011. * ```js
  24012. * sprite.userData.rotation = 1; // stores individual rotation per sprite
  24013. *
  24014. * const material = new THREE.SpriteNodeMaterial();
  24015. * material.rotationNode = userData( 'rotation', 'float' );
  24016. * ```
  24017. * Since `UserDataNode` is extended from {@link ReferenceNode}, the node value
  24018. * will automatically be updated when the `rotation` user data field changes.
  24019. *
  24020. * @augments ReferenceNode
  24021. */
  24022. class UserDataNode extends ReferenceNode {
  24023. static get type() {
  24024. return 'UserDataNode';
  24025. }
  24026. /**
  24027. * Constructs a new user data node.
  24028. *
  24029. * @param {string} property - The property name that should be referenced by the node.
  24030. * @param {string} inputType - The node data type of the reference.
  24031. * @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.
  24032. */
  24033. constructor( property, inputType, userData = null ) {
  24034. super( property, inputType, userData );
  24035. /**
  24036. * A reference to the `userData` object. If not provided, the `userData`
  24037. * property of the 3D object that uses the node material is evaluated.
  24038. *
  24039. * @type {?Object}
  24040. * @default null
  24041. */
  24042. this.userData = userData;
  24043. }
  24044. /**
  24045. * Overwritten to make sure {@link ReferenceNode#reference} points to the correct
  24046. * `userData` field.
  24047. *
  24048. * @param {(NodeFrame|NodeBuilder)} state - The current state to evaluate.
  24049. * @return {Object} A reference to the `userData` field.
  24050. */
  24051. updateReference( state ) {
  24052. this.reference = this.userData !== null ? this.userData : state.object.userData;
  24053. return this.reference;
  24054. }
  24055. }
  24056. /**
  24057. * TSL function for creating a user data node.
  24058. *
  24059. * @tsl
  24060. * @function
  24061. * @param {string} name - The property name that should be referenced by the node.
  24062. * @param {string} inputType - The node data type of the reference.
  24063. * @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.
  24064. * @returns {UserDataNode}
  24065. */
  24066. const userData = ( name, inputType, userData ) => nodeObject( new UserDataNode( name, inputType, userData ) );
  24067. const _objectData = new WeakMap();
  24068. /**
  24069. * A node for representing motion or velocity vectors. Foundation
  24070. * for advanced post processing effects like motion blur or TRAA.
  24071. *
  24072. * The node keeps track of the model, view and projection matrices
  24073. * of the previous frame and uses them to compute offsets in NDC space.
  24074. * These offsets represent the final velocity.
  24075. *
  24076. * @augments TempNode
  24077. */
  24078. class VelocityNode extends TempNode {
  24079. static get type() {
  24080. return 'VelocityNode';
  24081. }
  24082. /**
  24083. * Constructs a new vertex color node.
  24084. */
  24085. constructor() {
  24086. super( 'vec2' );
  24087. /**
  24088. * The current projection matrix.
  24089. *
  24090. * @type {?Matrix4}
  24091. * @default null
  24092. */
  24093. this.projectionMatrix = null;
  24094. /**
  24095. * Overwritten since velocity nodes are updated per object.
  24096. *
  24097. * @type {string}
  24098. * @default 'object'
  24099. */
  24100. this.updateType = NodeUpdateType.OBJECT;
  24101. /**
  24102. * Overwritten since velocity nodes save data after the update.
  24103. *
  24104. * @type {string}
  24105. * @default 'object'
  24106. */
  24107. this.updateAfterType = NodeUpdateType.OBJECT;
  24108. /**
  24109. * Uniform node representing the previous model matrix in world space.
  24110. *
  24111. * @type {UniformNode<mat4>}
  24112. * @default null
  24113. */
  24114. this.previousModelWorldMatrix = uniform( new Matrix4() );
  24115. /**
  24116. * Uniform node representing the previous projection matrix.
  24117. *
  24118. * @type {UniformNode<mat4>}
  24119. * @default null
  24120. */
  24121. this.previousProjectionMatrix = uniform( new Matrix4() ).setGroup( renderGroup );
  24122. /**
  24123. * Uniform node representing the previous view matrix.
  24124. *
  24125. * @type {UniformNode<mat4>}
  24126. * @default null
  24127. */
  24128. this.previousCameraViewMatrix = uniform( new Matrix4() );
  24129. }
  24130. /**
  24131. * Sets the given projection matrix.
  24132. *
  24133. * @param {Matrix4} projectionMatrix - The projection matrix to set.
  24134. */
  24135. setProjectionMatrix( projectionMatrix ) {
  24136. this.projectionMatrix = projectionMatrix;
  24137. }
  24138. /**
  24139. * Updates velocity specific uniforms.
  24140. *
  24141. * @param {NodeFrame} frame - A reference to the current node frame.
  24142. */
  24143. update( { frameId, camera, object } ) {
  24144. const previousModelMatrix = getPreviousMatrix( object );
  24145. this.previousModelWorldMatrix.value.copy( previousModelMatrix );
  24146. //
  24147. const cameraData = getData( camera );
  24148. if ( cameraData.frameId !== frameId ) {
  24149. cameraData.frameId = frameId;
  24150. if ( cameraData.previousProjectionMatrix === undefined ) {
  24151. cameraData.previousProjectionMatrix = new Matrix4();
  24152. cameraData.previousCameraViewMatrix = new Matrix4();
  24153. cameraData.currentProjectionMatrix = new Matrix4();
  24154. cameraData.currentCameraViewMatrix = new Matrix4();
  24155. cameraData.previousProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  24156. cameraData.previousCameraViewMatrix.copy( camera.matrixWorldInverse );
  24157. } else {
  24158. cameraData.previousProjectionMatrix.copy( cameraData.currentProjectionMatrix );
  24159. cameraData.previousCameraViewMatrix.copy( cameraData.currentCameraViewMatrix );
  24160. }
  24161. cameraData.currentProjectionMatrix.copy( this.projectionMatrix || camera.projectionMatrix );
  24162. cameraData.currentCameraViewMatrix.copy( camera.matrixWorldInverse );
  24163. this.previousProjectionMatrix.value.copy( cameraData.previousProjectionMatrix );
  24164. this.previousCameraViewMatrix.value.copy( cameraData.previousCameraViewMatrix );
  24165. }
  24166. }
  24167. /**
  24168. * Overwritten to updated velocity specific uniforms.
  24169. *
  24170. * @param {NodeFrame} frame - A reference to the current node frame.
  24171. */
  24172. updateAfter( { object } ) {
  24173. getPreviousMatrix( object ).copy( object.matrixWorld );
  24174. }
  24175. /**
  24176. * Implements the velocity computation based on the previous and current vertex data.
  24177. *
  24178. * @param {NodeBuilder} builder - A reference to the current node builder.
  24179. * @return {Node<vec2>} The motion vector.
  24180. */
  24181. setup( /*builder*/ ) {
  24182. const projectionMatrix = ( this.projectionMatrix === null ) ? cameraProjectionMatrix : uniform( this.projectionMatrix );
  24183. const previousModelViewMatrix = this.previousCameraViewMatrix.mul( this.previousModelWorldMatrix );
  24184. const clipPositionCurrent = projectionMatrix.mul( modelViewMatrix ).mul( positionLocal );
  24185. const clipPositionPrevious = this.previousProjectionMatrix.mul( previousModelViewMatrix ).mul( positionPrevious );
  24186. const ndcPositionCurrent = clipPositionCurrent.xy.div( clipPositionCurrent.w );
  24187. const ndcPositionPrevious = clipPositionPrevious.xy.div( clipPositionPrevious.w );
  24188. const velocity = sub( ndcPositionCurrent, ndcPositionPrevious );
  24189. return velocity;
  24190. }
  24191. }
  24192. function getData( object ) {
  24193. let objectData = _objectData.get( object );
  24194. if ( objectData === undefined ) {
  24195. objectData = {};
  24196. _objectData.set( object, objectData );
  24197. }
  24198. return objectData;
  24199. }
  24200. function getPreviousMatrix( object, index = 0 ) {
  24201. const objectData = getData( object );
  24202. let matrix = objectData[ index ];
  24203. if ( matrix === undefined ) {
  24204. objectData[ index ] = matrix = new Matrix4();
  24205. objectData[ index ].copy( object.matrixWorld );
  24206. }
  24207. return matrix;
  24208. }
  24209. /**
  24210. * TSL object that represents the velocity of a render pass.
  24211. *
  24212. * @tsl
  24213. * @type {VelocityNode}
  24214. */
  24215. const velocity = /*@__PURE__*/ nodeImmutable( VelocityNode );
  24216. /**
  24217. * Computes a grayscale value for the given RGB color value.
  24218. *
  24219. * @tsl
  24220. * @function
  24221. * @param {Node<vec3>} color - The color value to compute the grayscale for.
  24222. * @return {Node<vec3>} The grayscale color.
  24223. */
  24224. const grayscale = /*@__PURE__*/ Fn( ( [ color ] ) => {
  24225. return luminance( color.rgb );
  24226. } );
  24227. /**
  24228. * Super-saturates or desaturates the given RGB color.
  24229. *
  24230. * @tsl
  24231. * @function
  24232. * @param {Node<vec3>} color - The input color.
  24233. * @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.
  24234. * @return {Node<vec3>} The saturated color.
  24235. */
  24236. const saturation = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24237. return adjustment.mix( luminance( color.rgb ), color.rgb );
  24238. } );
  24239. /**
  24240. * Selectively enhance the intensity of less saturated RGB colors. Can result
  24241. * in a more natural and visually appealing image with enhanced color depth
  24242. * compared to {@link ColorAdjustment#saturation}.
  24243. *
  24244. * @tsl
  24245. * @function
  24246. * @param {Node<vec3>} color - The input color.
  24247. * @param {Node<float>} [adjustment=1] - Controls the intensity of the vibrance effect.
  24248. * @return {Node<vec3>} The updated color.
  24249. */
  24250. const vibrance = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24251. const average = add( color.r, color.g, color.b ).div( 3.0 );
  24252. const mx = color.r.max( color.g.max( color.b ) );
  24253. const amt = mx.sub( average ).mul( adjustment ).mul( -3 );
  24254. return mix( color.rgb, mx, amt );
  24255. } );
  24256. /**
  24257. * Updates the hue component of the given RGB color while preserving its luminance and saturation.
  24258. *
  24259. * @tsl
  24260. * @function
  24261. * @param {Node<vec3>} color - The input color.
  24262. * @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.
  24263. * @return {Node<vec3>} The updated color.
  24264. */
  24265. const hue = /*@__PURE__*/ Fn( ( [ color, adjustment = float( 1 ) ] ) => {
  24266. const k = vec3( 0.57735, 0.57735, 0.57735 );
  24267. const cosAngle = adjustment.cos();
  24268. return vec3( color.rgb.mul( cosAngle ).add( k.cross( color.rgb ).mul( adjustment.sin() ).add( k.mul( dot( k, color.rgb ).mul( cosAngle.oneMinus() ) ) ) ) );
  24269. } );
  24270. /**
  24271. * Computes the luminance for the given RGB color value.
  24272. *
  24273. * @tsl
  24274. * @function
  24275. * @param {Node<vec3>} color - The color value to compute the luminance for.
  24276. * @param {?Node<vec3>} luminanceCoefficients - The luminance coefficients. By default predefined values of the current working color space are used.
  24277. * @return {Node<vec3>} The luminance.
  24278. */
  24279. const luminance = (
  24280. color,
  24281. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3() ) )
  24282. ) => dot( color, luminanceCoefficients );
  24283. /**
  24284. * Color Decision List (CDL) v1.2
  24285. *
  24286. * Compact representation of color grading information, defined by slope, offset, power, and
  24287. * saturation. The CDL should be typically be given input in a log space (such as LogC, ACEScc,
  24288. * or AgX Log), and will return output in the same space. Output may require clamping >=0.
  24289. *
  24290. * @tsl
  24291. * @function
  24292. * @param {Node<vec4>} color Input (-Infinity < input < +Infinity)
  24293. * @param {Node<vec3>} slope Slope (0 ≤ slope < +Infinity)
  24294. * @param {Node<vec3>} offset Offset (-Infinity < offset < +Infinity; typically -1 < offset < 1)
  24295. * @param {Node<vec3>} power Power (0 < power < +Infinity)
  24296. * @param {Node<float>} saturation Saturation (0 ≤ saturation < +Infinity; typically 0 ≤ saturation < 4)
  24297. * @param {Node<vec3>} luminanceCoefficients Luminance coefficients for saturation term, typically Rec. 709
  24298. * @return {Node<vec4>} Output, -Infinity < output < +Infinity
  24299. *
  24300. * References:
  24301. * - ASC CDL v1.2
  24302. * - {@link https://blender.stackexchange.com/a/55239/43930}
  24303. * - {@link https://docs.acescentral.com/specifications/acescc/}
  24304. */
  24305. const cdl = /*@__PURE__*/ Fn( ( [
  24306. color,
  24307. slope = vec3( 1 ),
  24308. offset = vec3( 0 ),
  24309. power = vec3( 1 ),
  24310. saturation = float( 1 ),
  24311. // ASC CDL v1.2 explicitly requires Rec. 709 luminance coefficients.
  24312. luminanceCoefficients = vec3( ColorManagement.getLuminanceCoefficients( new Vector3(), LinearSRGBColorSpace ) )
  24313. ] ) => {
  24314. // NOTE: The ASC CDL v1.2 defines a [0, 1] clamp on the slope+offset term, and another on the
  24315. // saturation term. Per the ACEScc specification and Filament, limits may be omitted to support
  24316. // values outside [0, 1], requiring a workaround for negative values in the power expression.
  24317. const luma = color.rgb.dot( vec3( luminanceCoefficients ) );
  24318. const v = max$1( color.rgb.mul( slope ).add( offset ), 0.0 ).toVar();
  24319. const pv = v.pow( power ).toVar();
  24320. If( v.r.greaterThan( 0.0 ), () => { v.r.assign( pv.r ); } ); // eslint-disable-line
  24321. If( v.g.greaterThan( 0.0 ), () => { v.g.assign( pv.g ); } ); // eslint-disable-line
  24322. If( v.b.greaterThan( 0.0 ), () => { v.b.assign( pv.b ); } ); // eslint-disable-line
  24323. v.assign( luma.add( v.sub( luma ).mul( saturation ) ) );
  24324. return vec4( v.rgb, color.a );
  24325. } );
  24326. /**
  24327. * Represents a posterize effect which reduces the number of colors
  24328. * in an image, resulting in a more blocky and stylized appearance.
  24329. *
  24330. * @augments TempNode
  24331. */
  24332. class PosterizeNode extends TempNode {
  24333. static get type() {
  24334. return 'PosterizeNode';
  24335. }
  24336. /**
  24337. * Constructs a new posterize node.
  24338. *
  24339. * @param {Node} sourceNode - The input color.
  24340. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24341. */
  24342. constructor( sourceNode, stepsNode ) {
  24343. super();
  24344. /**
  24345. * The input color.
  24346. *
  24347. * @type {Node}
  24348. */
  24349. this.sourceNode = sourceNode;
  24350. /**
  24351. * Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24352. *
  24353. * @type {Node}
  24354. */
  24355. this.stepsNode = stepsNode;
  24356. }
  24357. setup() {
  24358. const { sourceNode, stepsNode } = this;
  24359. return sourceNode.mul( stepsNode ).floor().div( stepsNode );
  24360. }
  24361. }
  24362. /**
  24363. * TSL function for creating a posterize node.
  24364. *
  24365. * @tsl
  24366. * @function
  24367. * @param {Node} sourceNode - The input color.
  24368. * @param {Node} stepsNode - Controls the intensity of the posterization effect. A lower number results in a more blocky appearance.
  24369. * @returns {PosterizeNode}
  24370. */
  24371. const posterize = /*@__PURE__*/ nodeProxy( PosterizeNode ).setParameterLength( 2 );
  24372. const _size = /*@__PURE__*/ new Vector2();
  24373. /**
  24374. * Represents the texture of a pass node.
  24375. *
  24376. * @augments TextureNode
  24377. */
  24378. class PassTextureNode extends TextureNode {
  24379. static get type() {
  24380. return 'PassTextureNode';
  24381. }
  24382. /**
  24383. * Constructs a new pass texture node.
  24384. *
  24385. * @param {PassNode} passNode - The pass node.
  24386. * @param {Texture} texture - The output texture.
  24387. */
  24388. constructor( passNode, texture ) {
  24389. super( texture );
  24390. /**
  24391. * A reference to the pass node.
  24392. *
  24393. * @type {PassNode}
  24394. */
  24395. this.passNode = passNode;
  24396. this.setUpdateMatrix( false );
  24397. }
  24398. setup( builder ) {
  24399. if ( builder.object.isQuadMesh ) this.passNode.build( builder );
  24400. return super.setup( builder );
  24401. }
  24402. clone() {
  24403. return new this.constructor( this.passNode, this.value );
  24404. }
  24405. }
  24406. /**
  24407. * An extension of `PassTextureNode` which allows to manage more than one
  24408. * internal texture. Relevant for the `getPreviousTexture()` related API.
  24409. *
  24410. * @augments PassTextureNode
  24411. */
  24412. class PassMultipleTextureNode extends PassTextureNode {
  24413. static get type() {
  24414. return 'PassMultipleTextureNode';
  24415. }
  24416. /**
  24417. * Constructs a new pass texture node.
  24418. *
  24419. * @param {PassNode} passNode - The pass node.
  24420. * @param {string} textureName - The output texture name.
  24421. * @param {boolean} [previousTexture=false] - Whether previous frame data should be used or not.
  24422. */
  24423. constructor( passNode, textureName, previousTexture = false ) {
  24424. // null is passed to the super call since this class does not
  24425. // use an external texture for rendering pass data into. Instead
  24426. // the texture is managed by the pass node itself
  24427. super( passNode, null );
  24428. /**
  24429. * The output texture name.
  24430. *
  24431. * @type {string}
  24432. */
  24433. this.textureName = textureName;
  24434. /**
  24435. * Whether previous frame data should be used or not.
  24436. *
  24437. * @type {boolean}
  24438. */
  24439. this.previousTexture = previousTexture;
  24440. }
  24441. /**
  24442. * Updates the texture reference of this node.
  24443. */
  24444. updateTexture() {
  24445. this.value = this.previousTexture ? this.passNode.getPreviousTexture( this.textureName ) : this.passNode.getTexture( this.textureName );
  24446. }
  24447. setup( builder ) {
  24448. this.updateTexture();
  24449. return super.setup( builder );
  24450. }
  24451. clone() {
  24452. return new this.constructor( this.passNode, this.textureName, this.previousTexture );
  24453. }
  24454. }
  24455. /**
  24456. * Represents a render pass (sometimes called beauty pass) in context of post processing.
  24457. * This pass produces a render for the given scene and camera and can provide multiple outputs
  24458. * via MRT for further processing.
  24459. *
  24460. * ```js
  24461. * const postProcessing = new PostProcessing( renderer );
  24462. *
  24463. * const scenePass = pass( scene, camera );
  24464. *
  24465. * postProcessing.outputNode = scenePass;
  24466. * ```
  24467. *
  24468. * @augments TempNode
  24469. */
  24470. class PassNode extends TempNode {
  24471. static get type() {
  24472. return 'PassNode';
  24473. }
  24474. /**
  24475. * Constructs a new pass node.
  24476. *
  24477. * @param {('color'|'depth')} scope - The scope of the pass. The scope determines whether the node outputs color or depth.
  24478. * @param {Scene} scene - A reference to the scene.
  24479. * @param {Camera} camera - A reference to the camera.
  24480. * @param {Object} options - Options for the internal render target.
  24481. */
  24482. constructor( scope, scene, camera, options = {} ) {
  24483. super( 'vec4' );
  24484. /**
  24485. * The scope of the pass. The scope determines whether the node outputs color or depth.
  24486. *
  24487. * @type {('color'|'depth')}
  24488. */
  24489. this.scope = scope;
  24490. /**
  24491. * A reference to the scene.
  24492. *
  24493. * @type {Scene}
  24494. */
  24495. this.scene = scene;
  24496. /**
  24497. * A reference to the camera.
  24498. *
  24499. * @type {Camera}
  24500. */
  24501. this.camera = camera;
  24502. /**
  24503. * Options for the internal render target.
  24504. *
  24505. * @type {Object}
  24506. */
  24507. this.options = options;
  24508. /**
  24509. * The pass's pixel ratio. Will be kept automatically kept in sync with the renderer's pixel ratio.
  24510. *
  24511. * @private
  24512. * @type {number}
  24513. * @default 1
  24514. */
  24515. this._pixelRatio = 1;
  24516. /**
  24517. * The pass's pixel width. Will be kept automatically kept in sync with the renderer's width.
  24518. * @private
  24519. * @type {number}
  24520. * @default 1
  24521. */
  24522. this._width = 1;
  24523. /**
  24524. * The pass's pixel height. Will be kept automatically kept in sync with the renderer's height.
  24525. * @private
  24526. * @type {number}
  24527. * @default 1
  24528. */
  24529. this._height = 1;
  24530. const depthTexture = new DepthTexture();
  24531. depthTexture.isRenderTargetTexture = true;
  24532. //depthTexture.type = FloatType;
  24533. depthTexture.name = 'depth';
  24534. const renderTarget = new RenderTarget( this._width * this._pixelRatio, this._height * this._pixelRatio, { type: HalfFloatType, ...options, } );
  24535. renderTarget.texture.name = 'output';
  24536. renderTarget.depthTexture = depthTexture;
  24537. /**
  24538. * The pass's render target.
  24539. *
  24540. * @type {RenderTarget}
  24541. */
  24542. this.renderTarget = renderTarget;
  24543. /**
  24544. * A dictionary holding the internal result textures.
  24545. *
  24546. * @private
  24547. * @type {Object<string, Texture>}
  24548. */
  24549. this._textures = {
  24550. output: renderTarget.texture,
  24551. depth: depthTexture
  24552. };
  24553. /**
  24554. * A dictionary holding the internal texture nodes.
  24555. *
  24556. * @private
  24557. * @type {Object<string, TextureNode>}
  24558. */
  24559. this._textureNodes = {};
  24560. /**
  24561. * A dictionary holding the internal depth nodes.
  24562. *
  24563. * @private
  24564. * @type {Object}
  24565. */
  24566. this._linearDepthNodes = {};
  24567. /**
  24568. * A dictionary holding the internal viewZ nodes.
  24569. *
  24570. * @private
  24571. * @type {Object}
  24572. */
  24573. this._viewZNodes = {};
  24574. /**
  24575. * A dictionary holding the texture data of the previous frame.
  24576. * Used for computing velocity/motion vectors.
  24577. *
  24578. * @private
  24579. * @type {Object<string, Texture>}
  24580. */
  24581. this._previousTextures = {};
  24582. /**
  24583. * A dictionary holding the texture nodes of the previous frame.
  24584. * Used for computing velocity/motion vectors.
  24585. *
  24586. * @private
  24587. * @type {Object<string, TextureNode>}
  24588. */
  24589. this._previousTextureNodes = {};
  24590. /**
  24591. * The `near` property of the camera as a uniform.
  24592. *
  24593. * @private
  24594. * @type {UniformNode}
  24595. */
  24596. this._cameraNear = uniform( 0 );
  24597. /**
  24598. * The `far` property of the camera as a uniform.
  24599. *
  24600. * @private
  24601. * @type {UniformNode}
  24602. */
  24603. this._cameraFar = uniform( 0 );
  24604. /**
  24605. * A MRT node configuring the MRT settings.
  24606. *
  24607. * @private
  24608. * @type {?MRTNode}
  24609. * @default null
  24610. */
  24611. this._mrt = null;
  24612. this._layers = null;
  24613. this._resolution = 1;
  24614. /**
  24615. * This flag can be used for type testing.
  24616. *
  24617. * @type {boolean}
  24618. * @readonly
  24619. * @default true
  24620. */
  24621. this.isPassNode = true;
  24622. /**
  24623. * The `updateBeforeType` is set to `NodeUpdateType.FRAME` since the node renders the
  24624. * scene once per frame in its {@link PassNode#updateBefore} method.
  24625. *
  24626. * @type {string}
  24627. * @default 'frame'
  24628. */
  24629. this.updateBeforeType = NodeUpdateType.FRAME;
  24630. /**
  24631. * This flag is used for global cache.
  24632. *
  24633. * @type {boolean}
  24634. * @default true
  24635. */
  24636. this.global = true;
  24637. }
  24638. /**
  24639. * Sets the resolution for the pass.
  24640. * The resolution is a factor that is multiplied with the renderer's width and height.
  24641. *
  24642. * @param {number} resolution - The resolution to set. A value of `1` means full resolution.
  24643. * @return {PassNode} A reference to this pass.
  24644. */
  24645. setResolution( resolution ) {
  24646. this._resolution = resolution;
  24647. return this;
  24648. }
  24649. /**
  24650. * Gets the current resolution of the pass.
  24651. *
  24652. * @return {number} The current resolution. A value of `1` means full resolution.
  24653. * @default 1
  24654. */
  24655. getResolution() {
  24656. return this._resolution;
  24657. }
  24658. setLayers( layers ) {
  24659. this._layers = layers;
  24660. return this;
  24661. }
  24662. getLayers() {
  24663. return this._layers;
  24664. }
  24665. /**
  24666. * Sets the given MRT node to setup MRT for this pass.
  24667. *
  24668. * @param {MRTNode} mrt - The MRT object.
  24669. * @return {PassNode} A reference to this pass.
  24670. */
  24671. setMRT( mrt ) {
  24672. this._mrt = mrt;
  24673. return this;
  24674. }
  24675. /**
  24676. * Returns the current MRT node.
  24677. *
  24678. * @return {MRTNode} The current MRT node.
  24679. */
  24680. getMRT() {
  24681. return this._mrt;
  24682. }
  24683. /**
  24684. * Returns the texture for the given output name.
  24685. *
  24686. * @param {string} name - The output name to get the texture for.
  24687. * @return {Texture} The texture.
  24688. */
  24689. getTexture( name ) {
  24690. let texture = this._textures[ name ];
  24691. if ( texture === undefined ) {
  24692. const refTexture = this.renderTarget.texture;
  24693. texture = refTexture.clone();
  24694. texture.name = name;
  24695. this._textures[ name ] = texture;
  24696. this.renderTarget.textures.push( texture );
  24697. }
  24698. return texture;
  24699. }
  24700. /**
  24701. * Returns the texture holding the data of the previous frame for the given output name.
  24702. *
  24703. * @param {string} name - The output name to get the texture for.
  24704. * @return {Texture} The texture holding the data of the previous frame.
  24705. */
  24706. getPreviousTexture( name ) {
  24707. let texture = this._previousTextures[ name ];
  24708. if ( texture === undefined ) {
  24709. texture = this.getTexture( name ).clone();
  24710. this._previousTextures[ name ] = texture;
  24711. }
  24712. return texture;
  24713. }
  24714. /**
  24715. * Switches current and previous textures for the given output name.
  24716. *
  24717. * @param {string} name - The output name.
  24718. */
  24719. toggleTexture( name ) {
  24720. const prevTexture = this._previousTextures[ name ];
  24721. if ( prevTexture !== undefined ) {
  24722. const texture = this._textures[ name ];
  24723. const index = this.renderTarget.textures.indexOf( texture );
  24724. this.renderTarget.textures[ index ] = prevTexture;
  24725. this._textures[ name ] = prevTexture;
  24726. this._previousTextures[ name ] = texture;
  24727. this._textureNodes[ name ].updateTexture();
  24728. this._previousTextureNodes[ name ].updateTexture();
  24729. }
  24730. }
  24731. /**
  24732. * Returns the texture node for the given output name.
  24733. *
  24734. * @param {string} [name='output'] - The output name to get the texture node for.
  24735. * @return {TextureNode} The texture node.
  24736. */
  24737. getTextureNode( name = 'output' ) {
  24738. let textureNode = this._textureNodes[ name ];
  24739. if ( textureNode === undefined ) {
  24740. textureNode = nodeObject( new PassMultipleTextureNode( this, name ) );
  24741. textureNode.updateTexture();
  24742. this._textureNodes[ name ] = textureNode;
  24743. }
  24744. return textureNode;
  24745. }
  24746. /**
  24747. * Returns the previous texture node for the given output name.
  24748. *
  24749. * @param {string} [name='output'] - The output name to get the previous texture node for.
  24750. * @return {TextureNode} The previous texture node.
  24751. */
  24752. getPreviousTextureNode( name = 'output' ) {
  24753. let textureNode = this._previousTextureNodes[ name ];
  24754. if ( textureNode === undefined ) {
  24755. if ( this._textureNodes[ name ] === undefined ) this.getTextureNode( name );
  24756. textureNode = nodeObject( new PassMultipleTextureNode( this, name, true ) );
  24757. textureNode.updateTexture();
  24758. this._previousTextureNodes[ name ] = textureNode;
  24759. }
  24760. return textureNode;
  24761. }
  24762. /**
  24763. * Returns a viewZ node of this pass.
  24764. *
  24765. * @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.
  24766. * @return {Node} The viewZ node.
  24767. */
  24768. getViewZNode( name = 'depth' ) {
  24769. let viewZNode = this._viewZNodes[ name ];
  24770. if ( viewZNode === undefined ) {
  24771. const cameraNear = this._cameraNear;
  24772. const cameraFar = this._cameraFar;
  24773. this._viewZNodes[ name ] = viewZNode = perspectiveDepthToViewZ( this.getTextureNode( name ), cameraNear, cameraFar );
  24774. }
  24775. return viewZNode;
  24776. }
  24777. /**
  24778. * Returns a linear depth node of this pass.
  24779. *
  24780. * @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.
  24781. * @return {Node} The linear depth node.
  24782. */
  24783. getLinearDepthNode( name = 'depth' ) {
  24784. let linearDepthNode = this._linearDepthNodes[ name ];
  24785. if ( linearDepthNode === undefined ) {
  24786. const cameraNear = this._cameraNear;
  24787. const cameraFar = this._cameraFar;
  24788. const viewZNode = this.getViewZNode( name );
  24789. // TODO: just if ( builder.camera.isPerspectiveCamera )
  24790. this._linearDepthNodes[ name ] = linearDepthNode = viewZToOrthographicDepth( viewZNode, cameraNear, cameraFar );
  24791. }
  24792. return linearDepthNode;
  24793. }
  24794. setup( { renderer } ) {
  24795. this.renderTarget.samples = this.options.samples === undefined ? renderer.samples : this.options.samples;
  24796. this.renderTarget.texture.type = renderer.getColorBufferType();
  24797. return this.scope === PassNode.COLOR ? this.getTextureNode() : this.getLinearDepthNode();
  24798. }
  24799. updateBefore( frame ) {
  24800. const { renderer } = frame;
  24801. const { scene } = this;
  24802. let camera;
  24803. let pixelRatio;
  24804. const outputRenderTarget = renderer.getOutputRenderTarget();
  24805. if ( outputRenderTarget && outputRenderTarget.isXRRenderTarget === true ) {
  24806. pixelRatio = 1;
  24807. camera = renderer.xr.getCamera();
  24808. renderer.xr.updateCamera( camera );
  24809. _size.set( outputRenderTarget.width, outputRenderTarget.height );
  24810. } else {
  24811. camera = this.camera;
  24812. pixelRatio = renderer.getPixelRatio();
  24813. renderer.getSize( _size );
  24814. }
  24815. this._pixelRatio = pixelRatio;
  24816. this.setSize( _size.width, _size.height );
  24817. const currentRenderTarget = renderer.getRenderTarget();
  24818. const currentMRT = renderer.getMRT();
  24819. const currentMask = camera.layers.mask;
  24820. this._cameraNear.value = camera.near;
  24821. this._cameraFar.value = camera.far;
  24822. if ( this._layers !== null ) {
  24823. camera.layers.mask = this._layers.mask;
  24824. }
  24825. for ( const name in this._previousTextures ) {
  24826. this.toggleTexture( name );
  24827. }
  24828. renderer.setRenderTarget( this.renderTarget );
  24829. renderer.setMRT( this._mrt );
  24830. renderer.render( scene, camera );
  24831. renderer.setRenderTarget( currentRenderTarget );
  24832. renderer.setMRT( currentMRT );
  24833. camera.layers.mask = currentMask;
  24834. }
  24835. /**
  24836. * Sets the size of the pass's render target. Honors the pixel ratio.
  24837. *
  24838. * @param {number} width - The width to set.
  24839. * @param {number} height - The height to set.
  24840. */
  24841. setSize( width, height ) {
  24842. this._width = width;
  24843. this._height = height;
  24844. const effectiveWidth = this._width * this._pixelRatio * this._resolution;
  24845. const effectiveHeight = this._height * this._pixelRatio * this._resolution;
  24846. this.renderTarget.setSize( effectiveWidth, effectiveHeight );
  24847. }
  24848. /**
  24849. * Sets the pixel ratio the pass's render target and updates the size.
  24850. *
  24851. * @param {number} pixelRatio - The pixel ratio to set.
  24852. */
  24853. setPixelRatio( pixelRatio ) {
  24854. this._pixelRatio = pixelRatio;
  24855. this.setSize( this._width, this._height );
  24856. }
  24857. /**
  24858. * Frees internal resources. Should be called when the node is no longer in use.
  24859. */
  24860. dispose() {
  24861. this.renderTarget.dispose();
  24862. }
  24863. }
  24864. /**
  24865. * @static
  24866. * @type {'color'}
  24867. * @default 'color'
  24868. */
  24869. PassNode.COLOR = 'color';
  24870. /**
  24871. * @static
  24872. * @type {'depth'}
  24873. * @default 'depth'
  24874. */
  24875. PassNode.DEPTH = 'depth';
  24876. /**
  24877. * TSL function for creating a pass node.
  24878. *
  24879. * @tsl
  24880. * @function
  24881. * @param {Scene} scene - A reference to the scene.
  24882. * @param {Camera} camera - A reference to the camera.
  24883. * @param {Object} options - Options for the internal render target.
  24884. * @returns {PassNode}
  24885. */
  24886. const pass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.COLOR, scene, camera, options ) );
  24887. /**
  24888. * TSL function for creating a pass texture node.
  24889. *
  24890. * @tsl
  24891. * @function
  24892. * @param {PassNode} pass - The pass node.
  24893. * @param {Texture} texture - The output texture.
  24894. * @returns {PassTextureNode}
  24895. */
  24896. const passTexture = ( pass, texture ) => nodeObject( new PassTextureNode( pass, texture ) );
  24897. /**
  24898. * TSL function for creating a depth pass node.
  24899. *
  24900. * @tsl
  24901. * @function
  24902. * @param {Scene} scene - A reference to the scene.
  24903. * @param {Camera} camera - A reference to the camera.
  24904. * @param {Object} options - Options for the internal render target.
  24905. * @returns {PassNode}
  24906. */
  24907. const depthPass = ( scene, camera, options ) => nodeObject( new PassNode( PassNode.DEPTH, scene, camera, options ) );
  24908. /**
  24909. * Represents a render pass for producing a toon outline effect on compatible objects.
  24910. * Only 3D objects with materials of type `MeshToonMaterial` and `MeshToonNodeMaterial`
  24911. * will receive the outline.
  24912. *
  24913. * ```js
  24914. * const postProcessing = new PostProcessing( renderer );
  24915. *
  24916. * const scenePass = toonOutlinePass( scene, camera );
  24917. *
  24918. * postProcessing.outputNode = scenePass;
  24919. * ```
  24920. * @augments PassNode
  24921. */
  24922. class ToonOutlinePassNode extends PassNode {
  24923. static get type() {
  24924. return 'ToonOutlinePassNode';
  24925. }
  24926. /**
  24927. * Constructs a new outline pass node.
  24928. *
  24929. * @param {Scene} scene - A reference to the scene.
  24930. * @param {Camera} camera - A reference to the camera.
  24931. * @param {Node} colorNode - Defines the outline's color.
  24932. * @param {Node} thicknessNode - Defines the outline's thickness.
  24933. * @param {Node} alphaNode - Defines the outline's alpha.
  24934. */
  24935. constructor( scene, camera, colorNode, thicknessNode, alphaNode ) {
  24936. super( PassNode.COLOR, scene, camera );
  24937. /**
  24938. * Defines the outline's color.
  24939. *
  24940. * @type {Node}
  24941. */
  24942. this.colorNode = colorNode;
  24943. /**
  24944. * Defines the outline's thickness.
  24945. *
  24946. * @type {Node}
  24947. */
  24948. this.thicknessNode = thicknessNode;
  24949. /**
  24950. * Defines the outline's alpha.
  24951. *
  24952. * @type {Node}
  24953. */
  24954. this.alphaNode = alphaNode;
  24955. /**
  24956. * An internal material cache.
  24957. *
  24958. * @private
  24959. * @type {WeakMap<Material, NodeMaterial>}
  24960. */
  24961. this._materialCache = new WeakMap();
  24962. }
  24963. updateBefore( frame ) {
  24964. const { renderer } = frame;
  24965. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  24966. renderer.setRenderObjectFunction( ( object, scene, camera, geometry, material, group, lightsNode, clippingContext ) => {
  24967. // only render outline for supported materials
  24968. if ( material.isMeshToonMaterial || material.isMeshToonNodeMaterial ) {
  24969. if ( material.wireframe === false ) {
  24970. const outlineMaterial = this._getOutlineMaterial( material );
  24971. renderer.renderObject( object, scene, camera, geometry, outlineMaterial, group, lightsNode, clippingContext );
  24972. }
  24973. }
  24974. // default
  24975. renderer.renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext );
  24976. } );
  24977. super.updateBefore( frame );
  24978. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  24979. }
  24980. /**
  24981. * Creates the material used for outline rendering.
  24982. *
  24983. * @private
  24984. * @return {NodeMaterial} The outline material.
  24985. */
  24986. _createMaterial() {
  24987. const material = new NodeMaterial();
  24988. material.isMeshToonOutlineMaterial = true;
  24989. material.name = 'Toon_Outline';
  24990. material.side = BackSide;
  24991. // vertex node
  24992. const outlineNormal = normalLocal.negate();
  24993. const mvp = cameraProjectionMatrix.mul( modelViewMatrix );
  24994. const ratio = float( 1.0 ); // TODO: support outline thickness ratio for each vertex
  24995. const pos = mvp.mul( vec4( positionLocal, 1.0 ) );
  24996. const pos2 = mvp.mul( vec4( positionLocal.add( outlineNormal ), 1.0 ) );
  24997. const norm = normalize( pos.sub( pos2 ) ); // NOTE: subtract pos2 from pos because BackSide objectNormal is negative
  24998. material.vertexNode = pos.add( norm.mul( this.thicknessNode ).mul( pos.w ).mul( ratio ) );
  24999. // color node
  25000. material.colorNode = vec4( this.colorNode, this.alphaNode );
  25001. return material;
  25002. }
  25003. /**
  25004. * For the given toon material, this method returns a corresponding
  25005. * outline material.
  25006. *
  25007. * @private
  25008. * @param {(MeshToonMaterial|MeshToonNodeMaterial)} originalMaterial - The toon material.
  25009. * @return {NodeMaterial} The outline material.
  25010. */
  25011. _getOutlineMaterial( originalMaterial ) {
  25012. let outlineMaterial = this._materialCache.get( originalMaterial );
  25013. if ( outlineMaterial === undefined ) {
  25014. outlineMaterial = this._createMaterial();
  25015. this._materialCache.set( originalMaterial, outlineMaterial );
  25016. }
  25017. return outlineMaterial;
  25018. }
  25019. }
  25020. /**
  25021. * TSL function for creating a toon outline pass node.
  25022. *
  25023. * @tsl
  25024. * @function
  25025. * @param {Scene} scene - A reference to the scene.
  25026. * @param {Camera} camera - A reference to the camera.
  25027. * @param {Color} color - Defines the outline's color.
  25028. * @param {number} [thickness=0.003] - Defines the outline's thickness.
  25029. * @param {number} [alpha=1] - Defines the outline's alpha.
  25030. * @returns {ToonOutlinePassNode}
  25031. */
  25032. 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 ) ) );
  25033. /**
  25034. * Linear tone mapping, exposure only.
  25035. *
  25036. * @tsl
  25037. * @function
  25038. * @param {Node<vec3>} color - The color that should be tone mapped.
  25039. * @param {Node<float>} exposure - The exposure.
  25040. * @return {Node<vec3>} The tone mapped color.
  25041. */
  25042. const linearToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25043. return color.mul( exposure ).clamp();
  25044. } ).setLayout( {
  25045. name: 'linearToneMapping',
  25046. type: 'vec3',
  25047. inputs: [
  25048. { name: 'color', type: 'vec3' },
  25049. { name: 'exposure', type: 'float' }
  25050. ]
  25051. } );
  25052. /**
  25053. * Reinhard tone mapping.
  25054. *
  25055. * Reference: {@link https://www.cs.utah.edu/docs/techreports/2002/pdf/UUCS-02-001.pdf}
  25056. *
  25057. * @tsl
  25058. * @function
  25059. * @param {Node<vec3>} color - The color that should be tone mapped.
  25060. * @param {Node<float>} exposure - The exposure.
  25061. * @return {Node<vec3>} The tone mapped color.
  25062. */
  25063. const reinhardToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25064. color = color.mul( exposure );
  25065. return color.div( color.add( 1.0 ) ).clamp();
  25066. } ).setLayout( {
  25067. name: 'reinhardToneMapping',
  25068. type: 'vec3',
  25069. inputs: [
  25070. { name: 'color', type: 'vec3' },
  25071. { name: 'exposure', type: 'float' }
  25072. ]
  25073. } );
  25074. /**
  25075. * Cineon tone mapping.
  25076. *
  25077. * Reference: {@link http://filmicworlds.com/blog/filmic-tonemapping-operators/}
  25078. *
  25079. * @tsl
  25080. * @function
  25081. * @param {Node<vec3>} color - The color that should be tone mapped.
  25082. * @param {Node<float>} exposure - The exposure.
  25083. * @return {Node<vec3>} The tone mapped color.
  25084. */
  25085. const cineonToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25086. // filmic operator by Jim Hejl and Richard Burgess-Dawson
  25087. color = color.mul( exposure );
  25088. color = color.sub( 0.004 ).max( 0.0 );
  25089. const a = color.mul( color.mul( 6.2 ).add( 0.5 ) );
  25090. const b = color.mul( color.mul( 6.2 ).add( 1.7 ) ).add( 0.06 );
  25091. return a.div( b ).pow( 2.2 );
  25092. } ).setLayout( {
  25093. name: 'cineonToneMapping',
  25094. type: 'vec3',
  25095. inputs: [
  25096. { name: 'color', type: 'vec3' },
  25097. { name: 'exposure', type: 'float' }
  25098. ]
  25099. } );
  25100. // source: https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs
  25101. const RRTAndODTFit = /*@__PURE__*/ Fn( ( [ color ] ) => {
  25102. const a = color.mul( color.add( 0.0245786 ) ).sub( 0.000090537 );
  25103. const b = color.mul( color.add( 0.4329510 ).mul( 0.983729 ) ).add( 0.238081 );
  25104. return a.div( b );
  25105. } );
  25106. /**
  25107. * ACESFilmic tone mapping.
  25108. *
  25109. * Reference: {@link https://github.com/selfshadow/ltc_code/blob/master/webgl/shaders/ltc/ltc_blit.fs}
  25110. *
  25111. * @tsl
  25112. * @function
  25113. * @param {Node<vec3>} color - The color that should be tone mapped.
  25114. * @param {Node<float>} exposure - The exposure.
  25115. * @return {Node<vec3>} The tone mapped color.
  25116. */
  25117. const acesFilmicToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25118. // sRGB => XYZ => D65_2_D60 => AP1 => RRT_SAT
  25119. const ACESInputMat = mat3(
  25120. 0.59719, 0.35458, 0.04823,
  25121. 0.07600, 0.90834, 0.01566,
  25122. 0.02840, 0.13383, 0.83777
  25123. );
  25124. // ODT_SAT => XYZ => D60_2_D65 => sRGB
  25125. const ACESOutputMat = mat3(
  25126. 1.60475, -0.53108, -0.07367,
  25127. -0.10208, 1.10813, -605e-5,
  25128. -327e-5, -0.07276, 1.07602
  25129. );
  25130. color = color.mul( exposure ).div( 0.6 );
  25131. color = ACESInputMat.mul( color );
  25132. // Apply RRT and ODT
  25133. color = RRTAndODTFit( color );
  25134. color = ACESOutputMat.mul( color );
  25135. // Clamp to [0, 1]
  25136. return color.clamp();
  25137. } ).setLayout( {
  25138. name: 'acesFilmicToneMapping',
  25139. type: 'vec3',
  25140. inputs: [
  25141. { name: 'color', type: 'vec3' },
  25142. { name: 'exposure', type: 'float' }
  25143. ]
  25144. } );
  25145. 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 ) );
  25146. 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 ) );
  25147. const agxDefaultContrastApprox = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  25148. const x = vec3( x_immutable ).toVar();
  25149. const x2 = vec3( x.mul( x ) ).toVar();
  25150. const x4 = vec3( x2.mul( x2 ) ).toVar();
  25151. 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 ) ) ) );
  25152. } );
  25153. /**
  25154. * AgX tone mapping.
  25155. *
  25156. * @tsl
  25157. * @function
  25158. * @param {Node<vec3>} color - The color that should be tone mapped.
  25159. * @param {Node<float>} exposure - The exposure.
  25160. * @return {Node<vec3>} The tone mapped color.
  25161. */
  25162. const agxToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25163. const colortone = vec3( color ).toVar();
  25164. const AgXInsetMatrix = mat3( vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) );
  25165. const AgXOutsetMatrix = mat3( vec3( 1.1271005818144368, -0.1413297634984383, -0.14132976349843826 ), vec3( -0.11060664309660323, 1.157823702216272, -0.11060664309660294 ), vec3( -0.016493938717834573, -0.016493938717834257, 1.2519364065950405 ) );
  25166. const AgxMinEv = float( -12.47393 );
  25167. const AgxMaxEv = float( 4.026069 );
  25168. colortone.mulAssign( exposure );
  25169. colortone.assign( LINEAR_SRGB_TO_LINEAR_REC2020.mul( colortone ) );
  25170. colortone.assign( AgXInsetMatrix.mul( colortone ) );
  25171. colortone.assign( max$1( colortone, 1e-10 ) );
  25172. colortone.assign( log2( colortone ) );
  25173. colortone.assign( colortone.sub( AgxMinEv ).div( AgxMaxEv.sub( AgxMinEv ) ) );
  25174. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  25175. colortone.assign( agxDefaultContrastApprox( colortone ) );
  25176. colortone.assign( AgXOutsetMatrix.mul( colortone ) );
  25177. colortone.assign( pow( max$1( vec3( 0.0 ), colortone ), vec3( 2.2 ) ) );
  25178. colortone.assign( LINEAR_REC2020_TO_LINEAR_SRGB.mul( colortone ) );
  25179. colortone.assign( clamp( colortone, 0.0, 1.0 ) );
  25180. return colortone;
  25181. } ).setLayout( {
  25182. name: 'agxToneMapping',
  25183. type: 'vec3',
  25184. inputs: [
  25185. { name: 'color', type: 'vec3' },
  25186. { name: 'exposure', type: 'float' }
  25187. ]
  25188. } );
  25189. /**
  25190. * Neutral tone mapping.
  25191. *
  25192. * Reference: {@link https://modelviewer.dev/examples/tone-mapping}
  25193. *
  25194. * @tsl
  25195. * @function
  25196. * @param {Node<vec3>} color - The color that should be tone mapped.
  25197. * @param {Node<float>} exposure - The exposure.
  25198. * @return {Node<vec3>} The tone mapped color.
  25199. */
  25200. const neutralToneMapping = /*@__PURE__*/ Fn( ( [ color, exposure ] ) => {
  25201. const StartCompression = float( 0.8 - 0.04 );
  25202. const Desaturation = float( 0.15 );
  25203. color = color.mul( exposure );
  25204. const x = min$1( color.r, min$1( color.g, color.b ) );
  25205. const offset = select( x.lessThan( 0.08 ), x.sub( mul( 6.25, x.mul( x ) ) ), 0.04 );
  25206. color.subAssign( offset );
  25207. const peak = max$1( color.r, max$1( color.g, color.b ) );
  25208. If( peak.lessThan( StartCompression ), () => {
  25209. return color;
  25210. } );
  25211. const d = sub( 1, StartCompression );
  25212. const newPeak = sub( 1, d.mul( d ).div( peak.add( d.sub( StartCompression ) ) ) );
  25213. color.mulAssign( newPeak.div( peak ) );
  25214. const g = sub( 1, div( 1, Desaturation.mul( peak.sub( newPeak ) ).add( 1 ) ) );
  25215. return mix( color, vec3( newPeak ), g );
  25216. } ).setLayout( {
  25217. name: 'neutralToneMapping',
  25218. type: 'vec3',
  25219. inputs: [
  25220. { name: 'color', type: 'vec3' },
  25221. { name: 'exposure', type: 'float' }
  25222. ]
  25223. } );
  25224. /**
  25225. * This class represents native code sections. It is the base
  25226. * class for modules like {@link FunctionNode} which allows to implement
  25227. * functions with native shader languages.
  25228. *
  25229. * @augments Node
  25230. */
  25231. class CodeNode extends Node {
  25232. static get type() {
  25233. return 'CodeNode';
  25234. }
  25235. /**
  25236. * Constructs a new code node.
  25237. *
  25238. * @param {string} [code=''] - The native code.
  25239. * @param {Array<Node>} [includes=[]] - An array of includes.
  25240. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25241. */
  25242. constructor( code = '', includes = [], language = '' ) {
  25243. super( 'code' );
  25244. /**
  25245. * This flag can be used for type testing.
  25246. *
  25247. * @type {boolean}
  25248. * @readonly
  25249. * @default true
  25250. */
  25251. this.isCodeNode = true;
  25252. /**
  25253. * This flag is used for global cache.
  25254. *
  25255. * @type {boolean}
  25256. * @default true
  25257. */
  25258. this.global = true;
  25259. /**
  25260. * The native code.
  25261. *
  25262. * @type {string}
  25263. * @default ''
  25264. */
  25265. this.code = code;
  25266. /**
  25267. * An array of includes
  25268. *
  25269. * @type {Array<Node>}
  25270. * @default []
  25271. */
  25272. this.includes = includes;
  25273. /**
  25274. * The used language.
  25275. *
  25276. * @type {('js'|'wgsl'|'glsl')}
  25277. * @default ''
  25278. */
  25279. this.language = language;
  25280. }
  25281. /**
  25282. * Sets the includes of this code node.
  25283. *
  25284. * @param {Array<Node>} includes - The includes to set.
  25285. * @return {CodeNode} A reference to this node.
  25286. */
  25287. setIncludes( includes ) {
  25288. this.includes = includes;
  25289. return this;
  25290. }
  25291. /**
  25292. * Returns the includes of this code node.
  25293. *
  25294. * @param {NodeBuilder} builder - The current node builder.
  25295. * @return {Array<Node>} The includes.
  25296. */
  25297. getIncludes( /*builder*/ ) {
  25298. return this.includes;
  25299. }
  25300. generate( builder ) {
  25301. const includes = this.getIncludes( builder );
  25302. for ( const include of includes ) {
  25303. include.build( builder );
  25304. }
  25305. const nodeCode = builder.getCodeFromNode( this, this.getNodeType( builder ) );
  25306. nodeCode.code = this.code;
  25307. return nodeCode.code;
  25308. }
  25309. serialize( data ) {
  25310. super.serialize( data );
  25311. data.code = this.code;
  25312. data.language = this.language;
  25313. }
  25314. deserialize( data ) {
  25315. super.deserialize( data );
  25316. this.code = data.code;
  25317. this.language = data.language;
  25318. }
  25319. }
  25320. /**
  25321. * TSL function for creating a code node.
  25322. *
  25323. * @tsl
  25324. * @function
  25325. * @param {string} [code] - The native code.
  25326. * @param {?Array<Node>} [includes=[]] - An array of includes.
  25327. * @param {?('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25328. * @returns {CodeNode}
  25329. */
  25330. const code = /*@__PURE__*/ nodeProxy( CodeNode ).setParameterLength( 1, 3 );
  25331. /**
  25332. * TSL function for creating a JS code node.
  25333. *
  25334. * @tsl
  25335. * @function
  25336. * @param {string} src - The native code.
  25337. * @param {Array<Node>} includes - An array of includes.
  25338. * @returns {CodeNode}
  25339. */
  25340. const js = ( src, includes ) => code( src, includes, 'js' );
  25341. /**
  25342. * TSL function for creating a WGSL code node.
  25343. *
  25344. * @tsl
  25345. * @function
  25346. * @param {string} src - The native code.
  25347. * @param {Array<Node>} includes - An array of includes.
  25348. * @returns {CodeNode}
  25349. */
  25350. const wgsl = ( src, includes ) => code( src, includes, 'wgsl' );
  25351. /**
  25352. * TSL function for creating a GLSL code node.
  25353. *
  25354. * @tsl
  25355. * @function
  25356. * @param {string} src - The native code.
  25357. * @param {Array<Node>} includes - An array of includes.
  25358. * @returns {CodeNode}
  25359. */
  25360. const glsl = ( src, includes ) => code( src, includes, 'glsl' );
  25361. /**
  25362. * This class represents a native shader function. It can be used to implement
  25363. * certain aspects of a node material with native shader code. There are two predefined
  25364. * TSL functions for easier usage.
  25365. *
  25366. * - `wgslFn`: Creates a WGSL function node.
  25367. * - `glslFn`: Creates a GLSL function node.
  25368. *
  25369. * A basic example with one include looks like so:
  25370. *
  25371. * ```js
  25372. * const desaturateWGSLFn = wgslFn( `
  25373. * fn desaturate( color:vec3<f32> ) -> vec3<f32> {
  25374. * let lum = vec3<f32>( 0.299, 0.587, 0.114 );
  25375. * return vec3<f32>( dot( lum, color ) );
  25376. * }`
  25377. *);
  25378. * const someWGSLFn = wgslFn( `
  25379. * fn someFn( color:vec3<f32> ) -> vec3<f32> {
  25380. * return desaturate( color );
  25381. * }
  25382. * `, [ desaturateWGSLFn ] );
  25383. * material.colorNode = someWGSLFn( { color: texture( map ) } );
  25384. *```
  25385. * @augments CodeNode
  25386. */
  25387. class FunctionNode extends CodeNode {
  25388. static get type() {
  25389. return 'FunctionNode';
  25390. }
  25391. /**
  25392. * Constructs a new function node.
  25393. *
  25394. * @param {string} [code=''] - The native code.
  25395. * @param {Array<Node>} [includes=[]] - An array of includes.
  25396. * @param {('js'|'wgsl'|'glsl')} [language=''] - The used language.
  25397. */
  25398. constructor( code = '', includes = [], language = '' ) {
  25399. super( code, includes, language );
  25400. }
  25401. getNodeType( builder ) {
  25402. return this.getNodeFunction( builder ).type;
  25403. }
  25404. /**
  25405. * Returns the inputs of this function node.
  25406. *
  25407. * @param {NodeBuilder} builder - The current node builder.
  25408. * @return {Array<NodeFunctionInput>} The inputs.
  25409. */
  25410. getInputs( builder ) {
  25411. return this.getNodeFunction( builder ).inputs;
  25412. }
  25413. /**
  25414. * Returns the node function for this function node.
  25415. *
  25416. * @param {NodeBuilder} builder - The current node builder.
  25417. * @return {NodeFunction} The node function.
  25418. */
  25419. getNodeFunction( builder ) {
  25420. const nodeData = builder.getDataFromNode( this );
  25421. let nodeFunction = nodeData.nodeFunction;
  25422. if ( nodeFunction === undefined ) {
  25423. nodeFunction = builder.parser.parseFunction( this.code );
  25424. nodeData.nodeFunction = nodeFunction;
  25425. }
  25426. return nodeFunction;
  25427. }
  25428. generate( builder, output ) {
  25429. super.generate( builder );
  25430. const nodeFunction = this.getNodeFunction( builder );
  25431. const name = nodeFunction.name;
  25432. const type = nodeFunction.type;
  25433. const nodeCode = builder.getCodeFromNode( this, type );
  25434. if ( name !== '' ) {
  25435. // use a custom property name
  25436. nodeCode.name = name;
  25437. }
  25438. const propertyName = builder.getPropertyName( nodeCode );
  25439. const code = this.getNodeFunction( builder ).getCode( propertyName );
  25440. nodeCode.code = code + '\n';
  25441. if ( output === 'property' ) {
  25442. return propertyName;
  25443. } else {
  25444. return builder.format( `${ propertyName }()`, type, output );
  25445. }
  25446. }
  25447. }
  25448. const nativeFn = ( code, includes = [], language = '' ) => {
  25449. for ( let i = 0; i < includes.length; i ++ ) {
  25450. const include = includes[ i ];
  25451. // TSL Function: glslFn, wgslFn
  25452. if ( typeof include === 'function' ) {
  25453. includes[ i ] = include.functionNode;
  25454. }
  25455. }
  25456. const functionNode = nodeObject( new FunctionNode( code, includes, language ) );
  25457. const fn = ( ...params ) => functionNode.call( ...params );
  25458. fn.functionNode = functionNode;
  25459. return fn;
  25460. };
  25461. const glslFn = ( code, includes ) => nativeFn( code, includes, 'glsl' );
  25462. const wgslFn = ( code, includes ) => nativeFn( code, includes, 'wgsl' );
  25463. /**
  25464. * `ScriptableNode` uses this class to manage script inputs and outputs.
  25465. *
  25466. * @augments Node
  25467. */
  25468. class ScriptableValueNode extends Node {
  25469. static get type() {
  25470. return 'ScriptableValueNode';
  25471. }
  25472. /**
  25473. * Constructs a new scriptable node.
  25474. *
  25475. * @param {any} [value=null] - The value.
  25476. */
  25477. constructor( value = null ) {
  25478. super();
  25479. /**
  25480. * A reference to the value.
  25481. *
  25482. * @private
  25483. * @default null
  25484. */
  25485. this._value = value;
  25486. /**
  25487. * Depending on the type of `_value`, this property might cache parsed data.
  25488. *
  25489. * @private
  25490. * @default null
  25491. */
  25492. this._cache = null;
  25493. /**
  25494. * If this node represents an input, this property represents the input type.
  25495. *
  25496. * @type {?string}
  25497. * @default null
  25498. */
  25499. this.inputType = null;
  25500. /**
  25501. * If this node represents an output, this property represents the output type.
  25502. *
  25503. * @type {?string}
  25504. * @default null
  25505. */
  25506. this.outputType = null;
  25507. /**
  25508. * An event dispatcher for managing events.
  25509. *
  25510. * @type {EventDispatcher}
  25511. */
  25512. this.events = new EventDispatcher();
  25513. /**
  25514. * This flag can be used for type testing.
  25515. *
  25516. * @type {boolean}
  25517. * @readonly
  25518. * @default true
  25519. */
  25520. this.isScriptableValueNode = true;
  25521. }
  25522. /**
  25523. * Whether this node represents an output or not.
  25524. *
  25525. * @type {boolean}
  25526. * @readonly
  25527. * @default true
  25528. */
  25529. get isScriptableOutputNode() {
  25530. return this.outputType !== null;
  25531. }
  25532. set value( val ) {
  25533. if ( this._value === val ) return;
  25534. if ( this._cache && this.inputType === 'URL' && this.value.value instanceof ArrayBuffer ) {
  25535. URL.revokeObjectURL( this._cache );
  25536. this._cache = null;
  25537. }
  25538. this._value = val;
  25539. this.events.dispatchEvent( { type: 'change' } );
  25540. this.refresh();
  25541. }
  25542. /**
  25543. * The node's value.
  25544. *
  25545. * @type {any}
  25546. */
  25547. get value() {
  25548. return this._value;
  25549. }
  25550. /**
  25551. * Dispatches the `refresh` event.
  25552. */
  25553. refresh() {
  25554. this.events.dispatchEvent( { type: 'refresh' } );
  25555. }
  25556. /**
  25557. * The `value` property usually represents a node or even binary data in form of array buffers.
  25558. * In this case, this method tries to return the actual value behind the complex type.
  25559. *
  25560. * @return {any} The value.
  25561. */
  25562. getValue() {
  25563. const value = this.value;
  25564. if ( value && this._cache === null && this.inputType === 'URL' && value.value instanceof ArrayBuffer ) {
  25565. this._cache = URL.createObjectURL( new Blob( [ value.value ] ) );
  25566. } else if ( value && value.value !== null && value.value !== undefined && (
  25567. ( ( this.inputType === 'URL' || this.inputType === 'String' ) && typeof value.value === 'string' ) ||
  25568. ( this.inputType === 'Number' && typeof value.value === 'number' ) ||
  25569. ( this.inputType === 'Vector2' && value.value.isVector2 ) ||
  25570. ( this.inputType === 'Vector3' && value.value.isVector3 ) ||
  25571. ( this.inputType === 'Vector4' && value.value.isVector4 ) ||
  25572. ( this.inputType === 'Color' && value.value.isColor ) ||
  25573. ( this.inputType === 'Matrix3' && value.value.isMatrix3 ) ||
  25574. ( this.inputType === 'Matrix4' && value.value.isMatrix4 )
  25575. ) ) {
  25576. return value.value;
  25577. }
  25578. return this._cache || value;
  25579. }
  25580. /**
  25581. * Overwritten since the node type is inferred from the value.
  25582. *
  25583. * @param {NodeBuilder} builder - The current node builder.
  25584. * @return {string} The node type.
  25585. */
  25586. getNodeType( builder ) {
  25587. return this.value && this.value.isNode ? this.value.getNodeType( builder ) : 'float';
  25588. }
  25589. setup() {
  25590. return this.value && this.value.isNode ? this.value : float();
  25591. }
  25592. serialize( data ) {
  25593. super.serialize( data );
  25594. if ( this.value !== null ) {
  25595. if ( this.inputType === 'ArrayBuffer' ) {
  25596. data.value = arrayBufferToBase64( this.value );
  25597. } else {
  25598. data.value = this.value ? this.value.toJSON( data.meta ).uuid : null;
  25599. }
  25600. } else {
  25601. data.value = null;
  25602. }
  25603. data.inputType = this.inputType;
  25604. data.outputType = this.outputType;
  25605. }
  25606. deserialize( data ) {
  25607. super.deserialize( data );
  25608. let value = null;
  25609. if ( data.value !== null ) {
  25610. if ( data.inputType === 'ArrayBuffer' ) {
  25611. value = base64ToArrayBuffer( data.value );
  25612. } else if ( data.inputType === 'Texture' ) {
  25613. value = data.meta.textures[ data.value ];
  25614. } else {
  25615. value = data.meta.nodes[ data.value ] || null;
  25616. }
  25617. }
  25618. this.value = value;
  25619. this.inputType = data.inputType;
  25620. this.outputType = data.outputType;
  25621. }
  25622. }
  25623. /**
  25624. * TSL function for creating a scriptable value node.
  25625. *
  25626. * @tsl
  25627. * @function
  25628. * @param {any} [value] - The value.
  25629. * @returns {ScriptableValueNode}
  25630. */
  25631. const scriptableValue = /*@__PURE__*/ nodeProxy( ScriptableValueNode ).setParameterLength( 1 );
  25632. /**
  25633. * A Map-like data structure for managing resources of scriptable nodes.
  25634. *
  25635. * @augments Map
  25636. */
  25637. class Resources extends Map {
  25638. get( key, callback = null, ...params ) {
  25639. if ( this.has( key ) ) return super.get( key );
  25640. if ( callback !== null ) {
  25641. const value = callback( ...params );
  25642. this.set( key, value );
  25643. return value;
  25644. }
  25645. }
  25646. }
  25647. class Parameters {
  25648. constructor( scriptableNode ) {
  25649. this.scriptableNode = scriptableNode;
  25650. }
  25651. get parameters() {
  25652. return this.scriptableNode.parameters;
  25653. }
  25654. get layout() {
  25655. return this.scriptableNode.getLayout();
  25656. }
  25657. getInputLayout( id ) {
  25658. return this.scriptableNode.getInputLayout( id );
  25659. }
  25660. get( name ) {
  25661. const param = this.parameters[ name ];
  25662. const value = param ? param.getValue() : null;
  25663. return value;
  25664. }
  25665. }
  25666. /**
  25667. * Defines the resources (e.g. namespaces) of scriptable nodes.
  25668. *
  25669. * @type {Resources}
  25670. */
  25671. const ScriptableNodeResources = new Resources();
  25672. /**
  25673. * This type of node allows to implement nodes with custom scripts. The script
  25674. * section is represented as an instance of `CodeNode` written with JavaScript.
  25675. * The script itself must adhere to a specific structure.
  25676. *
  25677. * - main(): Executed once by default and every time `node.needsUpdate` is set.
  25678. * - layout: The layout object defines the script's interface (inputs and outputs).
  25679. *
  25680. * ```js
  25681. * ScriptableNodeResources.set( 'TSL', TSL );
  25682. *
  25683. * const scriptableNode = scriptable( js( `
  25684. * layout = {
  25685. * outputType: 'node',
  25686. * elements: [
  25687. * { name: 'source', inputType: 'node' },
  25688. * ]
  25689. * };
  25690. *
  25691. * const { mul, oscSine } = TSL;
  25692. *
  25693. * function main() {
  25694. * const source = parameters.get( 'source' ) || float();
  25695. * return mul( source, oscSine() ) );
  25696. * }
  25697. *
  25698. * ` ) );
  25699. *
  25700. * scriptableNode.setParameter( 'source', color( 1, 0, 0 ) );
  25701. *
  25702. * const material = new THREE.MeshBasicNodeMaterial();
  25703. * material.colorNode = scriptableNode;
  25704. * ```
  25705. *
  25706. * @augments Node
  25707. */
  25708. class ScriptableNode extends Node {
  25709. static get type() {
  25710. return 'ScriptableNode';
  25711. }
  25712. /**
  25713. * Constructs a new scriptable node.
  25714. *
  25715. * @param {?CodeNode} [codeNode=null] - The code node.
  25716. * @param {Object} [parameters={}] - The parameters definition.
  25717. */
  25718. constructor( codeNode = null, parameters = {} ) {
  25719. super();
  25720. /**
  25721. * The code node.
  25722. *
  25723. * @type {?CodeNode}
  25724. * @default null
  25725. */
  25726. this.codeNode = codeNode;
  25727. /**
  25728. * The parameters definition.
  25729. *
  25730. * @type {Object}
  25731. * @default {}
  25732. */
  25733. this.parameters = parameters;
  25734. this._local = new Resources();
  25735. this._output = scriptableValue( null );
  25736. this._outputs = {};
  25737. this._source = this.source;
  25738. this._method = null;
  25739. this._object = null;
  25740. this._value = null;
  25741. this._needsOutputUpdate = true;
  25742. this.onRefresh = this.onRefresh.bind( this );
  25743. /**
  25744. * This flag can be used for type testing.
  25745. *
  25746. * @type {boolean}
  25747. * @readonly
  25748. * @default true
  25749. */
  25750. this.isScriptableNode = true;
  25751. }
  25752. /**
  25753. * The source code of the scriptable node.
  25754. *
  25755. * @type {string}
  25756. */
  25757. get source() {
  25758. return this.codeNode ? this.codeNode.code : '';
  25759. }
  25760. /**
  25761. * Sets the reference of a local script variable.
  25762. *
  25763. * @param {string} name - The variable name.
  25764. * @param {Object} value - The reference to set.
  25765. * @return {Resources} The resource map
  25766. */
  25767. setLocal( name, value ) {
  25768. return this._local.set( name, value );
  25769. }
  25770. /**
  25771. * Gets the value of a local script variable.
  25772. *
  25773. * @param {string} name - The variable name.
  25774. * @return {Object} The value.
  25775. */
  25776. getLocal( name ) {
  25777. return this._local.get( name );
  25778. }
  25779. /**
  25780. * Event listener for the `refresh` event.
  25781. */
  25782. onRefresh() {
  25783. this._refresh();
  25784. }
  25785. /**
  25786. * Returns an input from the layout with the given id/name.
  25787. *
  25788. * @param {string} id - The id/name of the input.
  25789. * @return {Object} The element entry.
  25790. */
  25791. getInputLayout( id ) {
  25792. for ( const element of this.getLayout() ) {
  25793. if ( element.inputType && ( element.id === id || element.name === id ) ) {
  25794. return element;
  25795. }
  25796. }
  25797. }
  25798. /**
  25799. * Returns an output from the layout with the given id/name.
  25800. *
  25801. * @param {string} id - The id/name of the output.
  25802. * @return {Object} The element entry.
  25803. */
  25804. getOutputLayout( id ) {
  25805. for ( const element of this.getLayout() ) {
  25806. if ( element.outputType && ( element.id === id || element.name === id ) ) {
  25807. return element;
  25808. }
  25809. }
  25810. }
  25811. /**
  25812. * Defines a script output for the given name and value.
  25813. *
  25814. * @param {string} name - The name of the output.
  25815. * @param {Node} value - The node value.
  25816. * @return {ScriptableNode} A reference to this node.
  25817. */
  25818. setOutput( name, value ) {
  25819. const outputs = this._outputs;
  25820. if ( outputs[ name ] === undefined ) {
  25821. outputs[ name ] = scriptableValue( value );
  25822. } else {
  25823. outputs[ name ].value = value;
  25824. }
  25825. return this;
  25826. }
  25827. /**
  25828. * Returns a script output for the given name.
  25829. *
  25830. * @param {string} name - The name of the output.
  25831. * @return {ScriptableValueNode} The node value.
  25832. */
  25833. getOutput( name ) {
  25834. return this._outputs[ name ];
  25835. }
  25836. /**
  25837. * Returns a parameter for the given name
  25838. *
  25839. * @param {string} name - The name of the parameter.
  25840. * @return {ScriptableValueNode} The node value.
  25841. */
  25842. getParameter( name ) {
  25843. return this.parameters[ name ];
  25844. }
  25845. /**
  25846. * Sets a value for the given parameter name.
  25847. *
  25848. * @param {string} name - The parameter name.
  25849. * @param {any} value - The parameter value.
  25850. * @return {ScriptableNode} A reference to this node.
  25851. */
  25852. setParameter( name, value ) {
  25853. const parameters = this.parameters;
  25854. if ( value && value.isScriptableNode ) {
  25855. this.deleteParameter( name );
  25856. parameters[ name ] = value;
  25857. parameters[ name ].getDefaultOutput().events.addEventListener( 'refresh', this.onRefresh );
  25858. } else if ( value && value.isScriptableValueNode ) {
  25859. this.deleteParameter( name );
  25860. parameters[ name ] = value;
  25861. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  25862. } else if ( parameters[ name ] === undefined ) {
  25863. parameters[ name ] = scriptableValue( value );
  25864. parameters[ name ].events.addEventListener( 'refresh', this.onRefresh );
  25865. } else {
  25866. parameters[ name ].value = value;
  25867. }
  25868. return this;
  25869. }
  25870. /**
  25871. * Returns the value of this node which is the value of
  25872. * the default output.
  25873. *
  25874. * @return {Node} The value.
  25875. */
  25876. getValue() {
  25877. return this.getDefaultOutput().getValue();
  25878. }
  25879. /**
  25880. * Deletes a parameter from the script.
  25881. *
  25882. * @param {string} name - The parameter to remove.
  25883. * @return {ScriptableNode} A reference to this node.
  25884. */
  25885. deleteParameter( name ) {
  25886. let valueNode = this.parameters[ name ];
  25887. if ( valueNode ) {
  25888. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  25889. valueNode.events.removeEventListener( 'refresh', this.onRefresh );
  25890. }
  25891. return this;
  25892. }
  25893. /**
  25894. * Deletes all parameters from the script.
  25895. *
  25896. * @return {ScriptableNode} A reference to this node.
  25897. */
  25898. clearParameters() {
  25899. for ( const name of Object.keys( this.parameters ) ) {
  25900. this.deleteParameter( name );
  25901. }
  25902. this.needsUpdate = true;
  25903. return this;
  25904. }
  25905. /**
  25906. * Calls a function from the script.
  25907. *
  25908. * @param {string} name - The function name.
  25909. * @param {...any} params - A list of parameters.
  25910. * @return {any} The result of the function call.
  25911. */
  25912. call( name, ...params ) {
  25913. const object = this.getObject();
  25914. const method = object[ name ];
  25915. if ( typeof method === 'function' ) {
  25916. return method( ...params );
  25917. }
  25918. }
  25919. /**
  25920. * Asynchronously calls a function from the script.
  25921. *
  25922. * @param {string} name - The function name.
  25923. * @param {...any} params - A list of parameters.
  25924. * @return {Promise<any>} The result of the function call.
  25925. */
  25926. async callAsync( name, ...params ) {
  25927. const object = this.getObject();
  25928. const method = object[ name ];
  25929. if ( typeof method === 'function' ) {
  25930. return method.constructor.name === 'AsyncFunction' ? await method( ...params ) : method( ...params );
  25931. }
  25932. }
  25933. /**
  25934. * Overwritten since the node types is inferred from the script's output.
  25935. *
  25936. * @param {NodeBuilder} builder - The current node builder
  25937. * @return {string} The node type.
  25938. */
  25939. getNodeType( builder ) {
  25940. return this.getDefaultOutputNode().getNodeType( builder );
  25941. }
  25942. /**
  25943. * Refreshes the script node.
  25944. *
  25945. * @param {?string} [output=null] - An optional output.
  25946. */
  25947. refresh( output = null ) {
  25948. if ( output !== null ) {
  25949. this.getOutput( output ).refresh();
  25950. } else {
  25951. this._refresh();
  25952. }
  25953. }
  25954. /**
  25955. * Returns an object representation of the script.
  25956. *
  25957. * @return {Object} The result object.
  25958. */
  25959. getObject() {
  25960. if ( this.needsUpdate ) this.dispose();
  25961. if ( this._object !== null ) return this._object;
  25962. //
  25963. const refresh = () => this.refresh();
  25964. const setOutput = ( id, value ) => this.setOutput( id, value );
  25965. const parameters = new Parameters( this );
  25966. const THREE = ScriptableNodeResources.get( 'THREE' );
  25967. const TSL = ScriptableNodeResources.get( 'TSL' );
  25968. const method = this.getMethod();
  25969. const params = [ parameters, this._local, ScriptableNodeResources, refresh, setOutput, THREE, TSL ];
  25970. this._object = method( ...params );
  25971. const layout = this._object.layout;
  25972. if ( layout ) {
  25973. if ( layout.cache === false ) {
  25974. this._local.clear();
  25975. }
  25976. // default output
  25977. this._output.outputType = layout.outputType || null;
  25978. if ( Array.isArray( layout.elements ) ) {
  25979. for ( const element of layout.elements ) {
  25980. const id = element.id || element.name;
  25981. if ( element.inputType ) {
  25982. if ( this.getParameter( id ) === undefined ) this.setParameter( id, null );
  25983. this.getParameter( id ).inputType = element.inputType;
  25984. }
  25985. if ( element.outputType ) {
  25986. if ( this.getOutput( id ) === undefined ) this.setOutput( id, null );
  25987. this.getOutput( id ).outputType = element.outputType;
  25988. }
  25989. }
  25990. }
  25991. }
  25992. return this._object;
  25993. }
  25994. deserialize( data ) {
  25995. super.deserialize( data );
  25996. for ( const name in this.parameters ) {
  25997. let valueNode = this.parameters[ name ];
  25998. if ( valueNode.isScriptableNode ) valueNode = valueNode.getDefaultOutput();
  25999. valueNode.events.addEventListener( 'refresh', this.onRefresh );
  26000. }
  26001. }
  26002. /**
  26003. * Returns the layout of the script.
  26004. *
  26005. * @return {Object} The script's layout.
  26006. */
  26007. getLayout() {
  26008. return this.getObject().layout;
  26009. }
  26010. /**
  26011. * Returns default node output of the script.
  26012. *
  26013. * @return {Node} The default node output.
  26014. */
  26015. getDefaultOutputNode() {
  26016. const output = this.getDefaultOutput().value;
  26017. if ( output && output.isNode ) {
  26018. return output;
  26019. }
  26020. return float();
  26021. }
  26022. /**
  26023. * Returns default output of the script.
  26024. *
  26025. * @return {ScriptableValueNode} The default output.
  26026. */
  26027. getDefaultOutput() {
  26028. return this._exec()._output;
  26029. }
  26030. /**
  26031. * Returns a function created from the node's script.
  26032. *
  26033. * @return {Function} The function representing the node's code.
  26034. */
  26035. getMethod() {
  26036. if ( this.needsUpdate ) this.dispose();
  26037. if ( this._method !== null ) return this._method;
  26038. //
  26039. const parametersProps = [ 'parameters', 'local', 'global', 'refresh', 'setOutput', 'THREE', 'TSL' ];
  26040. const interfaceProps = [ 'layout', 'init', 'main', 'dispose' ];
  26041. const properties = interfaceProps.join( ', ' );
  26042. const declarations = 'var ' + properties + '; var output = {};\n';
  26043. const returns = '\nreturn { ...output, ' + properties + ' };';
  26044. const code = declarations + this.codeNode.code + returns;
  26045. //
  26046. this._method = new Function( ...parametersProps, code );
  26047. return this._method;
  26048. }
  26049. /**
  26050. * Frees all internal resources.
  26051. */
  26052. dispose() {
  26053. if ( this._method === null ) return;
  26054. if ( this._object && typeof this._object.dispose === 'function' ) {
  26055. this._object.dispose();
  26056. }
  26057. this._method = null;
  26058. this._object = null;
  26059. this._source = null;
  26060. this._value = null;
  26061. this._needsOutputUpdate = true;
  26062. this._output.value = null;
  26063. this._outputs = {};
  26064. }
  26065. setup() {
  26066. return this.getDefaultOutputNode();
  26067. }
  26068. getCacheKey( force ) {
  26069. const values = [ hashString( this.source ), this.getDefaultOutputNode().getCacheKey( force ) ];
  26070. for ( const param in this.parameters ) {
  26071. values.push( this.parameters[ param ].getCacheKey( force ) );
  26072. }
  26073. return hashArray( values );
  26074. }
  26075. set needsUpdate( value ) {
  26076. if ( value === true ) this.dispose();
  26077. }
  26078. get needsUpdate() {
  26079. return this.source !== this._source;
  26080. }
  26081. /**
  26082. * Executes the `main` function of the script.
  26083. *
  26084. * @private
  26085. * @return {ScriptableNode} A reference to this node.
  26086. */
  26087. _exec() {
  26088. if ( this.codeNode === null ) return this;
  26089. if ( this._needsOutputUpdate === true ) {
  26090. this._value = this.call( 'main' );
  26091. this._needsOutputUpdate = false;
  26092. }
  26093. this._output.value = this._value;
  26094. return this;
  26095. }
  26096. /**
  26097. * Executes the refresh.
  26098. *
  26099. * @private
  26100. */
  26101. _refresh() {
  26102. this.needsUpdate = true;
  26103. this._exec();
  26104. this._output.refresh();
  26105. }
  26106. }
  26107. /**
  26108. * TSL function for creating a scriptable node.
  26109. *
  26110. * @tsl
  26111. * @function
  26112. * @param {CodeNode} [codeNode] - The code node.
  26113. * @param {?Object} [parameters={}] - The parameters definition.
  26114. * @returns {ScriptableNode}
  26115. */
  26116. const scriptable = /*@__PURE__*/ nodeProxy( ScriptableNode ).setParameterLength( 1, 2 );
  26117. /**
  26118. * Returns a node that represents the `z` coordinate in view space
  26119. * for the current fragment. It's a different representation of the
  26120. * default depth value.
  26121. *
  26122. * This value can be part of a computation that defines how the fog
  26123. * density increases when moving away from the camera.
  26124. *
  26125. * @param {NodeBuilder} builder - The current node builder.
  26126. * @return {Node} The viewZ node.
  26127. */
  26128. function getViewZNode( builder ) {
  26129. let viewZ;
  26130. const getViewZ = builder.context.getViewZ;
  26131. if ( getViewZ !== undefined ) {
  26132. viewZ = getViewZ( this );
  26133. }
  26134. return ( viewZ || positionView.z ).negate();
  26135. }
  26136. /**
  26137. * Constructs a new range factor node.
  26138. *
  26139. * @tsl
  26140. * @function
  26141. * @param {Node} near - Defines the near value.
  26142. * @param {Node} far - Defines the far value.
  26143. */
  26144. const rangeFogFactor = Fn( ( [ near, far ], builder ) => {
  26145. const viewZ = getViewZNode( builder );
  26146. return smoothstep( near, far, viewZ );
  26147. } );
  26148. /**
  26149. * Represents an exponential squared fog. This type of fog gives
  26150. * a clear view near the camera and a faster than exponentially
  26151. * densening fog farther from the camera.
  26152. *
  26153. * @tsl
  26154. * @function
  26155. * @param {Node} density - Defines the fog density.
  26156. */
  26157. const densityFogFactor = Fn( ( [ density ], builder ) => {
  26158. const viewZ = getViewZNode( builder );
  26159. return density.mul( density, viewZ, viewZ ).negate().exp().oneMinus();
  26160. } );
  26161. /**
  26162. * This class can be used to configure a fog for the scene.
  26163. * Nodes of this type are assigned to `Scene.fogNode`.
  26164. *
  26165. * @tsl
  26166. * @function
  26167. * @param {Node} color - Defines the color of the fog.
  26168. * @param {Node} factor - Defines how the fog is factored in the scene.
  26169. */
  26170. const fog = Fn( ( [ color, factor ] ) => {
  26171. return vec4( factor.toFloat().mix( output.rgb, color.toVec3() ), output.a );
  26172. } );
  26173. // Deprecated
  26174. /**
  26175. * @tsl
  26176. * @function
  26177. * @deprecated since r171. Use `fog( color, rangeFogFactor( near, far ) )` instead.
  26178. *
  26179. * @param {Node} color
  26180. * @param {Node} near
  26181. * @param {Node} far
  26182. * @returns {Function}
  26183. */
  26184. function rangeFog( color, near, far ) { // @deprecated, r171
  26185. console.warn( 'THREE.TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.' );
  26186. return fog( color, rangeFogFactor( near, far ) );
  26187. }
  26188. /**
  26189. * @tsl
  26190. * @function
  26191. * @deprecated since r171. Use `fog( color, densityFogFactor( density ) )` instead.
  26192. *
  26193. * @param {Node} color
  26194. * @param {Node} density
  26195. * @returns {Function}
  26196. */
  26197. function densityFog( color, density ) { // @deprecated, r171
  26198. console.warn( 'THREE.TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.' );
  26199. return fog( color, densityFogFactor( density ) );
  26200. }
  26201. let min = null;
  26202. let max = null;
  26203. /**
  26204. * `RangeNode` generates random instanced attribute data in a defined range.
  26205. * An exemplary use case for this utility node is to generate random per-instance
  26206. * colors:
  26207. * ```js
  26208. * const material = new MeshBasicNodeMaterial();
  26209. * material.colorNode = range( new Color( 0x000000 ), new Color( 0xFFFFFF ) );
  26210. * const mesh = new InstancedMesh( geometry, material, count );
  26211. * ```
  26212. * @augments Node
  26213. */
  26214. class RangeNode extends Node {
  26215. static get type() {
  26216. return 'RangeNode';
  26217. }
  26218. /**
  26219. * Constructs a new range node.
  26220. *
  26221. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  26222. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  26223. */
  26224. constructor( minNode = float(), maxNode = float() ) {
  26225. super();
  26226. /**
  26227. * A node defining the lower bound of the range.
  26228. *
  26229. * @type {Node<any>}
  26230. * @default float()
  26231. */
  26232. this.minNode = minNode;
  26233. /**
  26234. * A node defining the upper bound of the range.
  26235. *
  26236. * @type {Node<any>}
  26237. * @default float()
  26238. */
  26239. this.maxNode = maxNode;
  26240. }
  26241. /**
  26242. * Returns the vector length which is computed based on the range definition.
  26243. *
  26244. * @param {NodeBuilder} builder - The current node builder.
  26245. * @return {number} The vector length.
  26246. */
  26247. getVectorLength( builder ) {
  26248. const minLength = builder.getTypeLength( getValueType( this.minNode.value ) );
  26249. const maxLength = builder.getTypeLength( getValueType( this.maxNode.value ) );
  26250. return minLength > maxLength ? minLength : maxLength;
  26251. }
  26252. /**
  26253. * This method is overwritten since the node type is inferred from range definition.
  26254. *
  26255. * @param {NodeBuilder} builder - The current node builder.
  26256. * @return {string} The node type.
  26257. */
  26258. getNodeType( builder ) {
  26259. return builder.object.count > 1 ? builder.getTypeFromLength( this.getVectorLength( builder ) ) : 'float';
  26260. }
  26261. setup( builder ) {
  26262. const object = builder.object;
  26263. let output = null;
  26264. if ( object.count > 1 ) {
  26265. const minValue = this.minNode.value;
  26266. const maxValue = this.maxNode.value;
  26267. const minLength = builder.getTypeLength( getValueType( minValue ) );
  26268. const maxLength = builder.getTypeLength( getValueType( maxValue ) );
  26269. min = min || new Vector4();
  26270. max = max || new Vector4();
  26271. min.setScalar( 0 );
  26272. max.setScalar( 0 );
  26273. if ( minLength === 1 ) min.setScalar( minValue );
  26274. else if ( minValue.isColor ) min.set( minValue.r, minValue.g, minValue.b, 1 );
  26275. else min.set( minValue.x, minValue.y, minValue.z || 0, minValue.w || 0 );
  26276. if ( maxLength === 1 ) max.setScalar( maxValue );
  26277. else if ( maxValue.isColor ) max.set( maxValue.r, maxValue.g, maxValue.b, 1 );
  26278. else max.set( maxValue.x, maxValue.y, maxValue.z || 0, maxValue.w || 0 );
  26279. const stride = 4;
  26280. const length = stride * object.count;
  26281. const array = new Float32Array( length );
  26282. for ( let i = 0; i < length; i ++ ) {
  26283. const index = i % stride;
  26284. const minElementValue = min.getComponent( index );
  26285. const maxElementValue = max.getComponent( index );
  26286. array[ i ] = MathUtils.lerp( minElementValue, maxElementValue, Math.random() );
  26287. }
  26288. const nodeType = this.getNodeType( builder );
  26289. if ( object.count <= 4096 ) {
  26290. output = buffer( array, 'vec4', object.count ).element( instanceIndex ).convert( nodeType );
  26291. } else {
  26292. // TODO: Improve anonymous buffer attribute creation removing this part
  26293. const bufferAttribute = new InstancedBufferAttribute( array, 4 );
  26294. builder.geometry.setAttribute( '__range' + this.id, bufferAttribute );
  26295. output = instancedBufferAttribute( bufferAttribute ).convert( nodeType );
  26296. }
  26297. } else {
  26298. output = float( 0 );
  26299. }
  26300. return output;
  26301. }
  26302. }
  26303. /**
  26304. * TSL function for creating a range node.
  26305. *
  26306. * @tsl
  26307. * @function
  26308. * @param {Node<any>} [minNode=float()] - A node defining the lower bound of the range.
  26309. * @param {Node<any>} [maxNode=float()] - A node defining the upper bound of the range.
  26310. * @returns {RangeNode}
  26311. */
  26312. const range = /*@__PURE__*/ nodeProxy( RangeNode ).setParameterLength( 2 );
  26313. /**
  26314. * `ComputeBuiltinNode` represents a compute-scope builtin value that expose information
  26315. * about the currently running dispatch and/or the device it is running on.
  26316. *
  26317. * This node can only be used with a WebGPU backend.
  26318. *
  26319. * @augments Node
  26320. */
  26321. class ComputeBuiltinNode extends Node {
  26322. static get type() {
  26323. return 'ComputeBuiltinNode';
  26324. }
  26325. /**
  26326. * Constructs a new compute builtin node.
  26327. *
  26328. * @param {string} builtinName - The built-in name.
  26329. * @param {string} nodeType - The node type.
  26330. */
  26331. constructor( builtinName, nodeType ) {
  26332. super( nodeType );
  26333. /**
  26334. * The built-in name.
  26335. *
  26336. * @private
  26337. * @type {string}
  26338. */
  26339. this._builtinName = builtinName;
  26340. }
  26341. /**
  26342. * This method is overwritten since hash is derived from the built-in name.
  26343. *
  26344. * @param {NodeBuilder} builder - The current node builder.
  26345. * @return {string} The hash.
  26346. */
  26347. getHash( builder ) {
  26348. return this.getBuiltinName( builder );
  26349. }
  26350. /**
  26351. * This method is overwritten since the node type is simply derived from `nodeType`..
  26352. *
  26353. * @param {NodeBuilder} builder - The current node builder.
  26354. * @return {string} The node type.
  26355. */
  26356. getNodeType( /*builder*/ ) {
  26357. return this.nodeType;
  26358. }
  26359. /**
  26360. * Sets the builtin name.
  26361. *
  26362. * @param {string} builtinName - The built-in name.
  26363. * @return {ComputeBuiltinNode} A reference to this node.
  26364. */
  26365. setBuiltinName( builtinName ) {
  26366. this._builtinName = builtinName;
  26367. return this;
  26368. }
  26369. /**
  26370. * Returns the builtin name.
  26371. *
  26372. * @param {NodeBuilder} builder - The current node builder.
  26373. * @return {string} The builtin name.
  26374. */
  26375. getBuiltinName( /*builder*/ ) {
  26376. return this._builtinName;
  26377. }
  26378. /**
  26379. * Whether the current node builder has the builtin or not.
  26380. *
  26381. * @param {NodeBuilder} builder - The current node builder.
  26382. * @return {boolean} Whether the builder has the builtin or not.
  26383. */
  26384. hasBuiltin( builder ) {
  26385. return builder.hasBuiltin( this._builtinName );
  26386. }
  26387. generate( builder, output ) {
  26388. const builtinName = this.getBuiltinName( builder );
  26389. const nodeType = this.getNodeType( builder );
  26390. if ( builder.shaderStage === 'compute' ) {
  26391. return builder.format( builtinName, nodeType, output );
  26392. } else {
  26393. console.warn( `ComputeBuiltinNode: Compute built-in value ${builtinName} can not be accessed in the ${builder.shaderStage} stage` );
  26394. return builder.generateConst( nodeType );
  26395. }
  26396. }
  26397. serialize( data ) {
  26398. super.serialize( data );
  26399. data.global = this.global;
  26400. data._builtinName = this._builtinName;
  26401. }
  26402. deserialize( data ) {
  26403. super.deserialize( data );
  26404. this.global = data.global;
  26405. this._builtinName = data._builtinName;
  26406. }
  26407. }
  26408. /**
  26409. * TSL function for creating a compute builtin node.
  26410. *
  26411. * @tsl
  26412. * @function
  26413. * @param {string} name - The built-in name.
  26414. * @param {string} nodeType - The node type.
  26415. * @returns {ComputeBuiltinNode}
  26416. */
  26417. const computeBuiltin = ( name, nodeType ) => nodeObject( new ComputeBuiltinNode( name, nodeType ) );
  26418. /**
  26419. * Represents the number of workgroups dispatched by the compute shader.
  26420. * ```js
  26421. * // Run 512 invocations/threads with a workgroup size of 128.
  26422. * const computeFn = Fn(() => {
  26423. *
  26424. * // numWorkgroups.x = 4
  26425. * storageBuffer.element(0).assign(numWorkgroups.x)
  26426. *
  26427. * })().compute(512, [128]);
  26428. *
  26429. * // Run 512 invocations/threads with the default workgroup size of 64.
  26430. * const computeFn = Fn(() => {
  26431. *
  26432. * // numWorkgroups.x = 8
  26433. * storageBuffer.element(0).assign(numWorkgroups.x)
  26434. *
  26435. * })().compute(512);
  26436. * ```
  26437. *
  26438. * @tsl
  26439. * @type {ComputeBuiltinNode<uvec3>}
  26440. */
  26441. const numWorkgroups = /*@__PURE__*/ computeBuiltin( 'numWorkgroups', 'uvec3' );
  26442. /**
  26443. * Represents the 3-dimensional index of the workgroup the current compute invocation belongs to.
  26444. * ```js
  26445. * // Execute 12 compute threads with a workgroup size of 3.
  26446. * const computeFn = Fn( () => {
  26447. *
  26448. * If( workgroupId.x.mod( 2 ).equal( 0 ), () => {
  26449. *
  26450. * storageBuffer.element( instanceIndex ).assign( instanceIndex );
  26451. *
  26452. * } ).Else( () => {
  26453. *
  26454. * storageBuffer.element( instanceIndex ).assign( 0 );
  26455. *
  26456. * } );
  26457. *
  26458. * } )().compute( 12, [ 3 ] );
  26459. *
  26460. * // workgroupId.x = [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3];
  26461. * // Buffer Output = [0, 1, 2, 0, 0, 0, 6, 7, 8, 0, 0, 0];
  26462. * ```
  26463. *
  26464. * @tsl
  26465. * @type {ComputeBuiltinNode<uvec3>}
  26466. */
  26467. const workgroupId = /*@__PURE__*/ computeBuiltin( 'workgroupId', 'uvec3' );
  26468. /**
  26469. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D global grid.
  26470. *
  26471. * @tsl
  26472. * @type {ComputeBuiltinNode<uvec3>}
  26473. */
  26474. const globalId = /*@__PURE__*/ computeBuiltin( 'globalId', 'uvec3' );
  26475. /**
  26476. * A non-linearized 3-dimensional representation of the current invocation's position within a 3D workgroup grid.
  26477. *
  26478. * @tsl
  26479. * @type {ComputeBuiltinNode<uvec3>}
  26480. */
  26481. const localId = /*@__PURE__*/ computeBuiltin( 'localId', 'uvec3' );
  26482. /**
  26483. * A device dependent variable that exposes the size of the current invocation's subgroup.
  26484. *
  26485. * @tsl
  26486. * @type {ComputeBuiltinNode<uint>}
  26487. */
  26488. const subgroupSize = /*@__PURE__*/ computeBuiltin( 'subgroupSize', 'uint' );
  26489. /**
  26490. * Represents a GPU control barrier that synchronizes compute operations within a given scope.
  26491. *
  26492. * This node can only be used with a WebGPU backend.
  26493. *
  26494. * @augments Node
  26495. */
  26496. class BarrierNode extends Node {
  26497. /**
  26498. * Constructs a new barrier node.
  26499. *
  26500. * @param {string} scope - The scope defines the behavior of the node.
  26501. */
  26502. constructor( scope ) {
  26503. super();
  26504. this.scope = scope;
  26505. }
  26506. generate( builder ) {
  26507. const { scope } = this;
  26508. const { renderer } = builder;
  26509. if ( renderer.backend.isWebGLBackend === true ) {
  26510. builder.addFlowCode( `\t// ${scope}Barrier \n` );
  26511. } else {
  26512. builder.addLineFlowCode( `${scope}Barrier()`, this );
  26513. }
  26514. }
  26515. }
  26516. /**
  26517. * TSL function for creating a barrier node.
  26518. *
  26519. * @tsl
  26520. * @function
  26521. * @param {string} scope - The scope defines the behavior of the node..
  26522. * @returns {BarrierNode}
  26523. */
  26524. const barrier = nodeProxy( BarrierNode );
  26525. /**
  26526. * TSL function for creating a workgroup barrier. All compute shader
  26527. * invocations must wait for each invocation within a workgroup to
  26528. * complete before the barrier can be surpassed.
  26529. *
  26530. * @tsl
  26531. * @function
  26532. * @returns {BarrierNode}
  26533. */
  26534. const workgroupBarrier = () => barrier( 'workgroup' ).toStack();
  26535. /**
  26536. * TSL function for creating a storage barrier. All invocations must
  26537. * wait for each access to variables within the 'storage' address space
  26538. * to complete before the barrier can be passed.
  26539. *
  26540. * @tsl
  26541. * @function
  26542. * @returns {BarrierNode}
  26543. */
  26544. const storageBarrier = () => barrier( 'storage' ).toStack();
  26545. /**
  26546. * TSL function for creating a texture barrier. All invocations must
  26547. * wait for each access to variables within the 'texture' address space
  26548. * to complete before the barrier can be passed.
  26549. *
  26550. * @tsl
  26551. * @function
  26552. * @returns {BarrierNode}
  26553. */
  26554. const textureBarrier = () => barrier( 'texture' ).toStack();
  26555. /**
  26556. * Represents an element of a 'workgroup' scoped buffer.
  26557. *
  26558. * @augments ArrayElementNode
  26559. */
  26560. class WorkgroupInfoElementNode extends ArrayElementNode {
  26561. /**
  26562. * Constructs a new workgroup info element node.
  26563. *
  26564. * @param {Node} workgroupInfoNode - The workgroup info node.
  26565. * @param {Node} indexNode - The index node that defines the element access.
  26566. */
  26567. constructor( workgroupInfoNode, indexNode ) {
  26568. super( workgroupInfoNode, indexNode );
  26569. /**
  26570. * This flag can be used for type testing.
  26571. *
  26572. * @type {boolean}
  26573. * @readonly
  26574. * @default true
  26575. */
  26576. this.isWorkgroupInfoElementNode = true;
  26577. }
  26578. generate( builder, output ) {
  26579. let snippet;
  26580. const isAssignContext = builder.context.assign;
  26581. snippet = super.generate( builder );
  26582. if ( isAssignContext !== true ) {
  26583. const type = this.getNodeType( builder );
  26584. snippet = builder.format( snippet, type, output );
  26585. }
  26586. // TODO: Possibly activate clip distance index on index access rather than from clipping context
  26587. return snippet;
  26588. }
  26589. }
  26590. /**
  26591. * A node allowing the user to create a 'workgroup' scoped buffer within the
  26592. * context of a compute shader. Typically, workgroup scoped buffers are
  26593. * created to hold data that is transferred from a global storage scope into
  26594. * a local workgroup scope. For invocations within a workgroup, data
  26595. * access speeds on 'workgroup' scoped buffers can be significantly faster
  26596. * than similar access operations on globally accessible storage buffers.
  26597. *
  26598. * This node can only be used with a WebGPU backend.
  26599. *
  26600. * @augments Node
  26601. */
  26602. class WorkgroupInfoNode extends Node {
  26603. /**
  26604. * Constructs a new buffer scoped to type scope.
  26605. *
  26606. * @param {string} scope - TODO.
  26607. * @param {string} bufferType - The data type of a 'workgroup' scoped buffer element.
  26608. * @param {number} [bufferCount=0] - The number of elements in the buffer.
  26609. */
  26610. constructor( scope, bufferType, bufferCount = 0 ) {
  26611. super( bufferType );
  26612. /**
  26613. * The buffer type.
  26614. *
  26615. * @type {string}
  26616. */
  26617. this.bufferType = bufferType;
  26618. /**
  26619. * The buffer count.
  26620. *
  26621. * @type {number}
  26622. * @default 0
  26623. */
  26624. this.bufferCount = bufferCount;
  26625. /**
  26626. * This flag can be used for type testing.
  26627. *
  26628. * @type {boolean}
  26629. * @readonly
  26630. * @default true
  26631. */
  26632. this.isWorkgroupInfoNode = true;
  26633. /**
  26634. * The data type of the array buffer.
  26635. *
  26636. * @type {string}
  26637. */
  26638. this.elementType = bufferType;
  26639. /**
  26640. * TODO.
  26641. *
  26642. * @type {string}
  26643. */
  26644. this.scope = scope;
  26645. }
  26646. /**
  26647. * Sets the name/label of this node.
  26648. *
  26649. * @param {string} name - The name to set.
  26650. * @return {WorkgroupInfoNode} A reference to this node.
  26651. */
  26652. label( name ) {
  26653. this.name = name;
  26654. return this;
  26655. }
  26656. /**
  26657. * Sets the scope of this node.
  26658. *
  26659. * @param {string} scope - The scope to set.
  26660. * @return {WorkgroupInfoNode} A reference to this node.
  26661. */
  26662. setScope( scope ) {
  26663. this.scope = scope;
  26664. return this;
  26665. }
  26666. /**
  26667. * The data type of the array buffer.
  26668. *
  26669. * @return {string} The element type.
  26670. */
  26671. getElementType() {
  26672. return this.elementType;
  26673. }
  26674. /**
  26675. * Overwrites the default implementation since the input type
  26676. * is inferred from the scope.
  26677. *
  26678. * @param {NodeBuilder} builder - The current node builder.
  26679. * @return {string} The input type.
  26680. */
  26681. getInputType( /*builder*/ ) {
  26682. return `${this.scope}Array`;
  26683. }
  26684. /**
  26685. * This method can be used to access elements via an index node.
  26686. *
  26687. * @param {IndexNode} indexNode - indexNode.
  26688. * @return {WorkgroupInfoElementNode} A reference to an element.
  26689. */
  26690. element( indexNode ) {
  26691. return nodeObject( new WorkgroupInfoElementNode( this, indexNode ) );
  26692. }
  26693. generate( builder ) {
  26694. return builder.getScopedArray( this.name || `${this.scope}Array_${this.id}`, this.scope.toLowerCase(), this.bufferType, this.bufferCount );
  26695. }
  26696. }
  26697. /**
  26698. * TSL function for creating a workgroup info node.
  26699. * Creates a new 'workgroup' scoped array buffer.
  26700. *
  26701. * @tsl
  26702. * @function
  26703. * @param {string} type - The data type of a 'workgroup' scoped buffer element.
  26704. * @param {number} [count=0] - The number of elements in the buffer.
  26705. * @returns {WorkgroupInfoNode}
  26706. */
  26707. const workgroupArray = ( type, count ) => nodeObject( new WorkgroupInfoNode( 'Workgroup', type, count ) );
  26708. /**
  26709. * `AtomicFunctionNode` represents any function that can operate on atomic variable types
  26710. * within a shader. In an atomic function, any modification to an atomic variable will
  26711. * occur as an indivisible step with a defined order relative to other modifications.
  26712. * Accordingly, even if multiple atomic functions are modifying an atomic variable at once
  26713. * atomic operations will not interfere with each other.
  26714. *
  26715. * This node can only be used with a WebGPU backend.
  26716. *
  26717. * @augments Node
  26718. */
  26719. class AtomicFunctionNode extends Node {
  26720. static get type() {
  26721. return 'AtomicFunctionNode';
  26722. }
  26723. /**
  26724. * Constructs a new atomic function node.
  26725. *
  26726. * @param {string} method - The signature of the atomic function to construct.
  26727. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26728. * @param {Node} valueNode - The value that mutates the atomic variable.
  26729. */
  26730. constructor( method, pointerNode, valueNode ) {
  26731. super( 'uint' );
  26732. /**
  26733. * The signature of the atomic function to construct.
  26734. *
  26735. * @type {string}
  26736. */
  26737. this.method = method;
  26738. /**
  26739. * An atomic variable or element of an atomic buffer.
  26740. *
  26741. * @type {Node}
  26742. */
  26743. this.pointerNode = pointerNode;
  26744. /**
  26745. * A value that modifies the atomic variable.
  26746. *
  26747. * @type {Node}
  26748. */
  26749. this.valueNode = valueNode;
  26750. /**
  26751. * Creates a list of the parents for this node for detecting if the node needs to return a value.
  26752. *
  26753. * @type {boolean}
  26754. * @default true
  26755. */
  26756. this.parents = true;
  26757. }
  26758. /**
  26759. * Overwrites the default implementation to return the type of
  26760. * the pointer node.
  26761. *
  26762. * @param {NodeBuilder} builder - The current node builder.
  26763. * @return {string} The input type.
  26764. */
  26765. getInputType( builder ) {
  26766. return this.pointerNode.getNodeType( builder );
  26767. }
  26768. /**
  26769. * Overwritten since the node type is inferred from the input type.
  26770. *
  26771. * @param {NodeBuilder} builder - The current node builder.
  26772. * @return {string} The node type.
  26773. */
  26774. getNodeType( builder ) {
  26775. return this.getInputType( builder );
  26776. }
  26777. generate( builder ) {
  26778. const properties = builder.getNodeProperties( this );
  26779. const parents = properties.parents;
  26780. const method = this.method;
  26781. const type = this.getNodeType( builder );
  26782. const inputType = this.getInputType( builder );
  26783. const a = this.pointerNode;
  26784. const b = this.valueNode;
  26785. const params = [];
  26786. params.push( `&${ a.build( builder, inputType ) }` );
  26787. if ( b !== null ) {
  26788. params.push( b.build( builder, inputType ) );
  26789. }
  26790. const methodSnippet = `${ builder.getMethod( method, type ) }( ${ params.join( ', ' ) } )`;
  26791. const isVoid = parents.length === 1 && parents[ 0 ].isStackNode === true;
  26792. if ( isVoid ) {
  26793. builder.addLineFlowCode( methodSnippet, this );
  26794. } else {
  26795. if ( properties.constNode === undefined ) {
  26796. properties.constNode = expression( methodSnippet, type ).toConst();
  26797. }
  26798. return properties.constNode.build( builder );
  26799. }
  26800. }
  26801. }
  26802. AtomicFunctionNode.ATOMIC_LOAD = 'atomicLoad';
  26803. AtomicFunctionNode.ATOMIC_STORE = 'atomicStore';
  26804. AtomicFunctionNode.ATOMIC_ADD = 'atomicAdd';
  26805. AtomicFunctionNode.ATOMIC_SUB = 'atomicSub';
  26806. AtomicFunctionNode.ATOMIC_MAX = 'atomicMax';
  26807. AtomicFunctionNode.ATOMIC_MIN = 'atomicMin';
  26808. AtomicFunctionNode.ATOMIC_AND = 'atomicAnd';
  26809. AtomicFunctionNode.ATOMIC_OR = 'atomicOr';
  26810. AtomicFunctionNode.ATOMIC_XOR = 'atomicXor';
  26811. /**
  26812. * TSL function for creating an atomic function node.
  26813. *
  26814. * @tsl
  26815. * @function
  26816. * @param {string} method - The signature of the atomic function to construct.
  26817. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26818. * @param {Node} valueNode - The value that mutates the atomic variable.
  26819. * @returns {AtomicFunctionNode}
  26820. */
  26821. const atomicNode = nodeProxy( AtomicFunctionNode );
  26822. /**
  26823. * TSL function for appending an atomic function call into the programmatic flow of a compute shader.
  26824. *
  26825. * @tsl
  26826. * @function
  26827. * @param {string} method - The signature of the atomic function to construct.
  26828. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26829. * @param {Node} valueNode - The value that mutates the atomic variable.
  26830. * @returns {AtomicFunctionNode}
  26831. */
  26832. const atomicFunc = ( method, pointerNode, valueNode ) => {
  26833. return atomicNode( method, pointerNode, valueNode ).toStack();
  26834. };
  26835. /**
  26836. * Loads the value stored in the atomic variable.
  26837. *
  26838. * @tsl
  26839. * @function
  26840. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26841. * @returns {AtomicFunctionNode}
  26842. */
  26843. const atomicLoad = ( pointerNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_LOAD, pointerNode, null );
  26844. /**
  26845. * Stores a value in the atomic variable.
  26846. *
  26847. * @tsl
  26848. * @function
  26849. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26850. * @param {Node} valueNode - The value that mutates the atomic variable.
  26851. * @returns {AtomicFunctionNode}
  26852. */
  26853. const atomicStore = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_STORE, pointerNode, valueNode );
  26854. /**
  26855. * Increments the value stored in the atomic variable.
  26856. *
  26857. * @tsl
  26858. * @function
  26859. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26860. * @param {Node} valueNode - The value that mutates the atomic variable.
  26861. * @returns {AtomicFunctionNode}
  26862. */
  26863. const atomicAdd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_ADD, pointerNode, valueNode );
  26864. /**
  26865. * Decrements the value stored in the atomic variable.
  26866. *
  26867. * @tsl
  26868. * @function
  26869. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26870. * @param {Node} valueNode - The value that mutates the atomic variable.
  26871. * @returns {AtomicFunctionNode}
  26872. */
  26873. const atomicSub = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_SUB, pointerNode, valueNode );
  26874. /**
  26875. * Stores in an atomic variable the maximum between its current value and a parameter.
  26876. *
  26877. * @tsl
  26878. * @function
  26879. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26880. * @param {Node} valueNode - The value that mutates the atomic variable.
  26881. * @returns {AtomicFunctionNode}
  26882. */
  26883. const atomicMax = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MAX, pointerNode, valueNode );
  26884. /**
  26885. * Stores in an atomic variable the minimum between its current value and a parameter.
  26886. *
  26887. * @tsl
  26888. * @function
  26889. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26890. * @param {Node} valueNode - The value that mutates the atomic variable.
  26891. * @returns {AtomicFunctionNode}
  26892. */
  26893. const atomicMin = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_MIN, pointerNode, valueNode );
  26894. /**
  26895. * Stores in an atomic variable the bitwise AND of its value with a parameter.
  26896. *
  26897. * @tsl
  26898. * @function
  26899. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26900. * @param {Node} valueNode - The value that mutates the atomic variable.
  26901. * @returns {AtomicFunctionNode}
  26902. */
  26903. const atomicAnd = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_AND, pointerNode, valueNode );
  26904. /**
  26905. * Stores in an atomic variable the bitwise OR of its value with a parameter.
  26906. *
  26907. * @tsl
  26908. * @function
  26909. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26910. * @param {Node} valueNode - The value that mutates the atomic variable.
  26911. * @returns {AtomicFunctionNode}
  26912. */
  26913. const atomicOr = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_OR, pointerNode, valueNode );
  26914. /**
  26915. * Stores in an atomic variable the bitwise XOR of its value with a parameter.
  26916. *
  26917. * @tsl
  26918. * @function
  26919. * @param {Node} pointerNode - An atomic variable or element of an atomic buffer.
  26920. * @param {Node} valueNode - The value that mutates the atomic variable.
  26921. * @returns {AtomicFunctionNode}
  26922. */
  26923. const atomicXor = ( pointerNode, valueNode ) => atomicFunc( AtomicFunctionNode.ATOMIC_XOR, pointerNode, valueNode );
  26924. let uniformsLib;
  26925. function getLightData( light ) {
  26926. uniformsLib = uniformsLib || new WeakMap();
  26927. let uniforms = uniformsLib.get( light );
  26928. if ( uniforms === undefined ) uniformsLib.set( light, uniforms = {} );
  26929. return uniforms;
  26930. }
  26931. /**
  26932. * TSL function for getting a shadow matrix uniform node for the given light.
  26933. *
  26934. * @tsl
  26935. * @function
  26936. * @param {Light} light -The light source.
  26937. * @returns {UniformNode<mat4>} The shadow matrix uniform node.
  26938. */
  26939. function lightShadowMatrix( light ) {
  26940. const data = getLightData( light );
  26941. return data.shadowMatrix || ( data.shadowMatrix = uniform( 'mat4' ).setGroup( renderGroup ).onRenderUpdate( ( frame ) => {
  26942. if ( light.castShadow !== true || frame.renderer.shadowMap.enabled === false ) {
  26943. light.shadow.updateMatrices( light );
  26944. }
  26945. return light.shadow.matrix;
  26946. } ) );
  26947. }
  26948. /**
  26949. * TSL function for getting projected uv coordinates for the given light.
  26950. * Relevant when using maps with spot lights.
  26951. *
  26952. * @tsl
  26953. * @function
  26954. * @param {Light} light -The light source.
  26955. * @param {Node<vec3>} [position=positionWorld] -The position to project.
  26956. * @returns {Node<vec3>} The projected uvs.
  26957. */
  26958. function lightProjectionUV( light, position = positionWorld ) {
  26959. const spotLightCoord = lightShadowMatrix( light ).mul( position );
  26960. const projectionUV = spotLightCoord.xyz.div( spotLightCoord.w );
  26961. return projectionUV;
  26962. }
  26963. /**
  26964. * TSL function for getting the position in world space for the given light.
  26965. *
  26966. * @tsl
  26967. * @function
  26968. * @param {Light} light -The light source.
  26969. * @returns {UniformNode<vec3>} The light's position in world space.
  26970. */
  26971. function lightPosition( light ) {
  26972. const data = getLightData( light );
  26973. return data.position || ( data.position = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.matrixWorld ) ) );
  26974. }
  26975. /**
  26976. * TSL function for getting the light target position in world space for the given light.
  26977. *
  26978. * @tsl
  26979. * @function
  26980. * @param {Light} light -The light source.
  26981. * @returns {UniformNode<vec3>} The light target position in world space.
  26982. */
  26983. function lightTargetPosition( light ) {
  26984. const data = getLightData( light );
  26985. return data.targetPosition || ( data.targetPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( _, self ) => self.value.setFromMatrixPosition( light.target.matrixWorld ) ) );
  26986. }
  26987. /**
  26988. * TSL function for getting the position in view space for the given light.
  26989. *
  26990. * @tsl
  26991. * @function
  26992. * @param {Light} light - The light source.
  26993. * @returns {UniformNode<vec3>} The light's position in view space.
  26994. */
  26995. function lightViewPosition( light ) {
  26996. const data = getLightData( light );
  26997. return data.viewPosition || ( data.viewPosition = uniform( new Vector3() ).setGroup( renderGroup ).onRenderUpdate( ( { camera }, self ) => {
  26998. self.value = self.value || new Vector3();
  26999. self.value.setFromMatrixPosition( light.matrixWorld );
  27000. self.value.applyMatrix4( camera.matrixWorldInverse );
  27001. } ) );
  27002. }
  27003. /**
  27004. * TSL function for getting the light target direction for the given light.
  27005. *
  27006. * @tsl
  27007. * @function
  27008. * @param {Light} light -The light source.
  27009. * @returns {Node<vec3>} The light's target direction.
  27010. */
  27011. const lightTargetDirection = ( light ) => cameraViewMatrix.transformDirection( lightPosition( light ).sub( lightTargetPosition( light ) ) );
  27012. const sortLights = ( lights ) => {
  27013. return lights.sort( ( a, b ) => a.id - b.id );
  27014. };
  27015. const getLightNodeById = ( id, lightNodes ) => {
  27016. for ( const lightNode of lightNodes ) {
  27017. if ( lightNode.isAnalyticLightNode && lightNode.light.id === id ) {
  27018. return lightNode;
  27019. }
  27020. }
  27021. return null;
  27022. };
  27023. const _lightsNodeRef = /*@__PURE__*/ new WeakMap();
  27024. const _hashData = [];
  27025. /**
  27026. * This node represents the scene's lighting and manages the lighting model's life cycle
  27027. * for the current build 3D object. It is responsible for computing the total outgoing
  27028. * light in a given lighting context.
  27029. *
  27030. * @augments Node
  27031. */
  27032. class LightsNode extends Node {
  27033. static get type() {
  27034. return 'LightsNode';
  27035. }
  27036. /**
  27037. * Constructs a new lights node.
  27038. */
  27039. constructor() {
  27040. super( 'vec3' );
  27041. /**
  27042. * A node representing the total diffuse light.
  27043. *
  27044. * @type {Node<vec3>}
  27045. */
  27046. this.totalDiffuseNode = vec3().toVar();
  27047. /**
  27048. * A node representing the total specular light.
  27049. *
  27050. * @type {Node<vec3>}
  27051. */
  27052. this.totalSpecularNode = vec3().toVar();
  27053. /**
  27054. * A node representing the outgoing light.
  27055. *
  27056. * @type {Node<vec3>}
  27057. */
  27058. this.outgoingLightNode = vec3().toVar();
  27059. /**
  27060. * An array representing the lights in the scene.
  27061. *
  27062. * @private
  27063. * @type {Array<Light>}
  27064. */
  27065. this._lights = [];
  27066. /**
  27067. * For each light in the scene, this node will create a
  27068. * corresponding light node.
  27069. *
  27070. * @private
  27071. * @type {?Array<LightingNode>}
  27072. * @default null
  27073. */
  27074. this._lightNodes = null;
  27075. /**
  27076. * A hash for identifying the current light nodes setup.
  27077. *
  27078. * @private
  27079. * @type {?string}
  27080. * @default null
  27081. */
  27082. this._lightNodesHash = null;
  27083. /**
  27084. * `LightsNode` sets this property to `true` by default.
  27085. *
  27086. * @type {boolean}
  27087. * @default true
  27088. */
  27089. this.global = true;
  27090. }
  27091. /**
  27092. * Overwrites the default {@link Node#customCacheKey} implementation by including
  27093. * light data into the cache key.
  27094. *
  27095. * @return {number} The custom cache key.
  27096. */
  27097. customCacheKey() {
  27098. const lights = this._lights;
  27099. for ( let i = 0; i < lights.length; i ++ ) {
  27100. const light = lights[ i ];
  27101. _hashData.push( light.id );
  27102. _hashData.push( light.castShadow ? 1 : 0 );
  27103. if ( light.isSpotLight === true ) {
  27104. const hashMap = ( light.map !== null ) ? light.map.id : -1;
  27105. const hashColorNode = ( light.colorNode ) ? light.colorNode.getCacheKey() : -1;
  27106. _hashData.push( hashMap, hashColorNode );
  27107. }
  27108. }
  27109. const cacheKey = hashArray( _hashData );
  27110. _hashData.length = 0;
  27111. return cacheKey;
  27112. }
  27113. /**
  27114. * Computes a hash value for identifying the current light nodes setup.
  27115. *
  27116. * @param {NodeBuilder} builder - A reference to the current node builder.
  27117. * @return {string} The computed hash.
  27118. */
  27119. getHash( builder ) {
  27120. if ( this._lightNodesHash === null ) {
  27121. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  27122. const hash = [];
  27123. for ( const lightNode of this._lightNodes ) {
  27124. hash.push( lightNode.getSelf().getHash() );
  27125. }
  27126. this._lightNodesHash = 'lights-' + hash.join( ',' );
  27127. }
  27128. return this._lightNodesHash;
  27129. }
  27130. analyze( builder ) {
  27131. const properties = builder.getNodeProperties( this );
  27132. for ( const node of properties.nodes ) {
  27133. node.build( builder );
  27134. }
  27135. properties.outputNode.build( builder );
  27136. }
  27137. /**
  27138. * Creates lighting nodes for each scene light. This makes it possible to further
  27139. * process lights in the node system.
  27140. *
  27141. * @param {NodeBuilder} builder - A reference to the current node builder.
  27142. */
  27143. setupLightsNode( builder ) {
  27144. const lightNodes = [];
  27145. const previousLightNodes = this._lightNodes;
  27146. const lights = sortLights( this._lights );
  27147. const nodeLibrary = builder.renderer.library;
  27148. for ( const light of lights ) {
  27149. if ( light.isNode ) {
  27150. lightNodes.push( nodeObject( light ) );
  27151. } else {
  27152. let lightNode = null;
  27153. if ( previousLightNodes !== null ) {
  27154. lightNode = getLightNodeById( light.id, previousLightNodes ); // reuse existing light node
  27155. }
  27156. if ( lightNode === null ) {
  27157. // find the corresponding node type for a given light
  27158. const lightNodeClass = nodeLibrary.getLightNodeClass( light.constructor );
  27159. if ( lightNodeClass === null ) {
  27160. console.warn( `LightsNode.setupNodeLights: Light node not found for ${ light.constructor.name }` );
  27161. continue;
  27162. }
  27163. let lightNode = null;
  27164. if ( ! _lightsNodeRef.has( light ) ) {
  27165. lightNode = nodeObject( new lightNodeClass( light ) );
  27166. _lightsNodeRef.set( light, lightNode );
  27167. } else {
  27168. lightNode = _lightsNodeRef.get( light );
  27169. }
  27170. lightNodes.push( lightNode );
  27171. }
  27172. }
  27173. }
  27174. this._lightNodes = lightNodes;
  27175. }
  27176. /**
  27177. * Sets up a direct light in the lighting model.
  27178. *
  27179. * @param {Object} builder - The builder object containing the context and stack.
  27180. * @param {Object} lightNode - The light node.
  27181. * @param {Object} lightData - The light object containing color and direction properties.
  27182. */
  27183. setupDirectLight( builder, lightNode, lightData ) {
  27184. const { lightingModel, reflectedLight } = builder.context;
  27185. lightingModel.direct( {
  27186. ...lightData,
  27187. lightNode,
  27188. reflectedLight
  27189. }, builder );
  27190. }
  27191. setupDirectRectAreaLight( builder, lightNode, lightData ) {
  27192. const { lightingModel, reflectedLight } = builder.context;
  27193. lightingModel.directRectArea( {
  27194. ...lightData,
  27195. lightNode,
  27196. reflectedLight
  27197. }, builder );
  27198. }
  27199. /**
  27200. * Setups the internal lights by building all respective
  27201. * light nodes.
  27202. *
  27203. * @param {NodeBuilder} builder - A reference to the current node builder.
  27204. * @param {Array<LightingNode>} lightNodes - An array of lighting nodes.
  27205. */
  27206. setupLights( builder, lightNodes ) {
  27207. for ( const lightNode of lightNodes ) {
  27208. lightNode.build( builder );
  27209. }
  27210. }
  27211. getLightNodes( builder ) {
  27212. if ( this._lightNodes === null ) this.setupLightsNode( builder );
  27213. return this._lightNodes;
  27214. }
  27215. /**
  27216. * The implementation makes sure that for each light in the scene
  27217. * there is a corresponding light node. By building the light nodes
  27218. * and evaluating the lighting model the outgoing light is computed.
  27219. *
  27220. * @param {NodeBuilder} builder - A reference to the current node builder.
  27221. * @return {Node<vec3>} A node representing the outgoing light.
  27222. */
  27223. setup( builder ) {
  27224. const currentLightsNode = builder.lightsNode;
  27225. builder.lightsNode = this;
  27226. //
  27227. let outgoingLightNode = this.outgoingLightNode;
  27228. const context = builder.context;
  27229. const lightingModel = context.lightingModel;
  27230. const properties = builder.getNodeProperties( this );
  27231. if ( lightingModel ) {
  27232. const { totalDiffuseNode, totalSpecularNode } = this;
  27233. context.outgoingLight = outgoingLightNode;
  27234. const stack = builder.addStack();
  27235. //
  27236. properties.nodes = stack.nodes;
  27237. //
  27238. lightingModel.start( builder );
  27239. //
  27240. const { backdrop, backdropAlpha } = context;
  27241. const { directDiffuse, directSpecular, indirectDiffuse, indirectSpecular } = context.reflectedLight;
  27242. let totalDiffuse = directDiffuse.add( indirectDiffuse );
  27243. if ( backdrop !== null ) {
  27244. if ( backdropAlpha !== null ) {
  27245. totalDiffuse = vec3( backdropAlpha.mix( totalDiffuse, backdrop ) );
  27246. } else {
  27247. totalDiffuse = vec3( backdrop );
  27248. }
  27249. context.material.transparent = true;
  27250. }
  27251. totalDiffuseNode.assign( totalDiffuse );
  27252. totalSpecularNode.assign( directSpecular.add( indirectSpecular ) );
  27253. outgoingLightNode.assign( totalDiffuseNode.add( totalSpecularNode ) );
  27254. //
  27255. lightingModel.finish( builder );
  27256. //
  27257. outgoingLightNode = outgoingLightNode.bypass( builder.removeStack() );
  27258. } else {
  27259. properties.nodes = [];
  27260. }
  27261. //
  27262. builder.lightsNode = currentLightsNode;
  27263. return outgoingLightNode;
  27264. }
  27265. /**
  27266. * Configures this node with an array of lights.
  27267. *
  27268. * @param {Array<Light>} lights - An array of lights.
  27269. * @return {LightsNode} A reference to this node.
  27270. */
  27271. setLights( lights ) {
  27272. this._lights = lights;
  27273. this._lightNodes = null;
  27274. this._lightNodesHash = null;
  27275. return this;
  27276. }
  27277. /**
  27278. * Returns an array of the scene's lights.
  27279. *
  27280. * @return {Array<Light>} The scene's lights.
  27281. */
  27282. getLights() {
  27283. return this._lights;
  27284. }
  27285. /**
  27286. * Whether the scene has lights or not.
  27287. *
  27288. * @type {boolean}
  27289. */
  27290. get hasLights() {
  27291. return this._lights.length > 0;
  27292. }
  27293. }
  27294. /**
  27295. * TSL function for creating an instance of `LightsNode` and configuring
  27296. * it with the given array of lights.
  27297. *
  27298. * @tsl
  27299. * @function
  27300. * @param {Array<Light>} lights - An array of lights.
  27301. * @return {LightsNode} The created lights node.
  27302. */
  27303. const lights = ( lights = [] ) => nodeObject( new LightsNode() ).setLights( lights );
  27304. /**
  27305. * Base class for all shadow nodes.
  27306. *
  27307. * Shadow nodes encapsulate shadow related logic and are always coupled to lighting nodes.
  27308. * Lighting nodes might share the same shadow node type or use specific ones depending on
  27309. * their requirements.
  27310. *
  27311. * @augments Node
  27312. */
  27313. class ShadowBaseNode extends Node {
  27314. static get type() {
  27315. return 'ShadowBaseNode';
  27316. }
  27317. /**
  27318. * Constructs a new shadow base node.
  27319. *
  27320. * @param {Light} light - The shadow casting light.
  27321. */
  27322. constructor( light ) {
  27323. super();
  27324. /**
  27325. * The shadow casting light.
  27326. *
  27327. * @type {Light}
  27328. */
  27329. this.light = light;
  27330. /**
  27331. * Overwritten since shadows are updated by default per render.
  27332. *
  27333. * @type {string}
  27334. * @default 'render'
  27335. */
  27336. this.updateBeforeType = NodeUpdateType.RENDER;
  27337. /**
  27338. * This flag can be used for type testing.
  27339. *
  27340. * @type {boolean}
  27341. * @readonly
  27342. * @default true
  27343. */
  27344. this.isShadowBaseNode = true;
  27345. }
  27346. /**
  27347. * Setups the shadow position node which is by default the predefined TSL node object `shadowPositionWorld`.
  27348. *
  27349. * @param {NodeBuilder} object - A configuration object that must at least hold a material reference.
  27350. */
  27351. setupShadowPosition( { context, material } ) {
  27352. // Use assign inside an Fn()
  27353. shadowPositionWorld.assign( material.receivedShadowPositionNode || context.shadowPositionWorld || positionWorld );
  27354. }
  27355. }
  27356. /**
  27357. * TSL object that represents the vertex position in world space during the shadow pass.
  27358. *
  27359. * @tsl
  27360. * @type {Node<vec3>}
  27361. */
  27362. const shadowPositionWorld = /*@__PURE__*/ property( 'vec3', 'shadowPositionWorld' );
  27363. /**
  27364. * Saves the state of the given renderer and stores it into the given state object.
  27365. *
  27366. * If not state object is provided, the function creates one.
  27367. *
  27368. * @function
  27369. * @param {Renderer} renderer - The renderer.
  27370. * @param {Object} [state={}] - The state.
  27371. * @return {Object} The state.
  27372. */
  27373. function saveRendererState( renderer, state = {} ) {
  27374. state.toneMapping = renderer.toneMapping;
  27375. state.toneMappingExposure = renderer.toneMappingExposure;
  27376. state.outputColorSpace = renderer.outputColorSpace;
  27377. state.renderTarget = renderer.getRenderTarget();
  27378. state.activeCubeFace = renderer.getActiveCubeFace();
  27379. state.activeMipmapLevel = renderer.getActiveMipmapLevel();
  27380. state.renderObjectFunction = renderer.getRenderObjectFunction();
  27381. state.pixelRatio = renderer.getPixelRatio();
  27382. state.mrt = renderer.getMRT();
  27383. state.clearColor = renderer.getClearColor( state.clearColor || new Color() );
  27384. state.clearAlpha = renderer.getClearAlpha();
  27385. state.autoClear = renderer.autoClear;
  27386. state.scissorTest = renderer.getScissorTest();
  27387. return state;
  27388. }
  27389. /**
  27390. * Saves the state of the given renderer and stores it into the given state object.
  27391. * Besides, the function also resets the state of the renderer to its default values.
  27392. *
  27393. * If not state object is provided, the function creates one.
  27394. *
  27395. * @function
  27396. * @param {Renderer} renderer - The renderer.
  27397. * @param {Object} [state={}] - The state.
  27398. * @return {Object} The state.
  27399. */
  27400. function resetRendererState( renderer, state ) {
  27401. state = saveRendererState( renderer, state );
  27402. renderer.setMRT( null );
  27403. renderer.setRenderObjectFunction( null );
  27404. renderer.setClearColor( 0x000000, 1 );
  27405. renderer.autoClear = true;
  27406. return state;
  27407. }
  27408. /**
  27409. * Restores the state of the given renderer from the given state object.
  27410. *
  27411. * @function
  27412. * @param {Renderer} renderer - The renderer.
  27413. * @param {Object} state - The state to restore.
  27414. */
  27415. function restoreRendererState( renderer, state ) {
  27416. renderer.toneMapping = state.toneMapping;
  27417. renderer.toneMappingExposure = state.toneMappingExposure;
  27418. renderer.outputColorSpace = state.outputColorSpace;
  27419. renderer.setRenderTarget( state.renderTarget, state.activeCubeFace, state.activeMipmapLevel );
  27420. renderer.setRenderObjectFunction( state.renderObjectFunction );
  27421. renderer.setPixelRatio( state.pixelRatio );
  27422. renderer.setMRT( state.mrt );
  27423. renderer.setClearColor( state.clearColor, state.clearAlpha );
  27424. renderer.autoClear = state.autoClear;
  27425. renderer.setScissorTest( state.scissorTest );
  27426. }
  27427. /**
  27428. * Saves the state of the given scene and stores it into the given state object.
  27429. *
  27430. * If not state object is provided, the function creates one.
  27431. *
  27432. * @function
  27433. * @param {Scene} scene - The scene.
  27434. * @param {Object} [state={}] - The state.
  27435. * @return {Object} The state.
  27436. */
  27437. function saveSceneState( scene, state = {} ) {
  27438. state.background = scene.background;
  27439. state.backgroundNode = scene.backgroundNode;
  27440. state.overrideMaterial = scene.overrideMaterial;
  27441. return state;
  27442. }
  27443. /**
  27444. * Saves the state of the given scene and stores it into the given state object.
  27445. * Besides, the function also resets the state of the scene to its default values.
  27446. *
  27447. * If not state object is provided, the function creates one.
  27448. *
  27449. * @function
  27450. * @param {Scene} scene - The scene.
  27451. * @param {Object} [state={}] - The state.
  27452. * @return {Object} The state.
  27453. */
  27454. function resetSceneState( scene, state ) {
  27455. state = saveSceneState( scene, state );
  27456. scene.background = null;
  27457. scene.backgroundNode = null;
  27458. scene.overrideMaterial = null;
  27459. return state;
  27460. }
  27461. /**
  27462. * Restores the state of the given scene from the given state object.
  27463. *
  27464. * @function
  27465. * @param {Scene} scene - The scene.
  27466. * @param {Object} state - The state to restore.
  27467. */
  27468. function restoreSceneState( scene, state ) {
  27469. scene.background = state.background;
  27470. scene.backgroundNode = state.backgroundNode;
  27471. scene.overrideMaterial = state.overrideMaterial;
  27472. }
  27473. /**
  27474. * Saves the state of the given renderer and scene and stores it into the given state object.
  27475. *
  27476. * If not state object is provided, the function creates one.
  27477. *
  27478. * @function
  27479. * @param {Renderer} renderer - The renderer.
  27480. * @param {Scene} scene - The scene.
  27481. * @param {Object} [state={}] - The state.
  27482. * @return {Object} The state.
  27483. */
  27484. function saveRendererAndSceneState( renderer, scene, state = {} ) {
  27485. state = saveRendererState( renderer, state );
  27486. state = saveSceneState( scene, state );
  27487. return state;
  27488. }
  27489. /**
  27490. * Saves the state of the given renderer and scene and stores it into the given state object.
  27491. * Besides, the function also resets the state of the renderer and scene to its default values.
  27492. *
  27493. * If not state object is provided, the function creates one.
  27494. *
  27495. * @function
  27496. * @param {Renderer} renderer - The renderer.
  27497. * @param {Scene} scene - The scene.
  27498. * @param {Object} [state={}] - The state.
  27499. * @return {Object} The state.
  27500. */
  27501. function resetRendererAndSceneState( renderer, scene, state ) {
  27502. state = resetRendererState( renderer, state );
  27503. state = resetSceneState( scene, state );
  27504. return state;
  27505. }
  27506. /**
  27507. * Restores the state of the given renderer and scene from the given state object.
  27508. *
  27509. * @function
  27510. * @param {Renderer} renderer - The renderer.
  27511. * @param {Scene} scene - The scene.
  27512. * @param {Object} state - The state to restore.
  27513. */
  27514. function restoreRendererAndSceneState( renderer, scene, state ) {
  27515. restoreRendererState( renderer, state );
  27516. restoreSceneState( scene, state );
  27517. }
  27518. var RendererUtils = /*#__PURE__*/Object.freeze({
  27519. __proto__: null,
  27520. resetRendererAndSceneState: resetRendererAndSceneState,
  27521. resetRendererState: resetRendererState,
  27522. resetSceneState: resetSceneState,
  27523. restoreRendererAndSceneState: restoreRendererAndSceneState,
  27524. restoreRendererState: restoreRendererState,
  27525. restoreSceneState: restoreSceneState,
  27526. saveRendererAndSceneState: saveRendererAndSceneState,
  27527. saveRendererState: saveRendererState,
  27528. saveSceneState: saveSceneState
  27529. });
  27530. const shadowMaterialLib = /*@__PURE__*/ new WeakMap();
  27531. /**
  27532. * A shadow filtering function performing basic filtering. This is in fact an unfiltered version of the shadow map
  27533. * with a binary `[0,1]` result.
  27534. *
  27535. * @method
  27536. * @param {Object} inputs - The input parameter object.
  27537. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27538. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27539. * @return {Node<float>} The filtering result.
  27540. */
  27541. const BasicShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  27542. let basic = texture( depthTexture, shadowCoord.xy ).label( 't_basic' );
  27543. if ( depthTexture.isArrayTexture ) {
  27544. basic = basic.depth( depthLayer );
  27545. }
  27546. return basic.compare( shadowCoord.z );
  27547. } );
  27548. /**
  27549. * A shadow filtering function performing PCF filtering.
  27550. *
  27551. * @method
  27552. * @param {Object} inputs - The input parameter object.
  27553. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27554. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27555. * @param {LightShadow} inputs.shadow - The light shadow.
  27556. * @return {Node<float>} The filtering result.
  27557. */
  27558. const PCFShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  27559. const depthCompare = ( uv, compare ) => {
  27560. let depth = texture( depthTexture, uv );
  27561. if ( depthTexture.isArrayTexture ) {
  27562. depth = depth.depth( depthLayer );
  27563. }
  27564. return depth.compare( compare );
  27565. };
  27566. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27567. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  27568. const texelSize = vec2( 1 ).div( mapSize );
  27569. const dx0 = texelSize.x.negate().mul( radius );
  27570. const dy0 = texelSize.y.negate().mul( radius );
  27571. const dx1 = texelSize.x.mul( radius );
  27572. const dy1 = texelSize.y.mul( radius );
  27573. const dx2 = dx0.div( 2 );
  27574. const dy2 = dy0.div( 2 );
  27575. const dx3 = dx1.div( 2 );
  27576. const dy3 = dy1.div( 2 );
  27577. return add(
  27578. depthCompare( shadowCoord.xy.add( vec2( dx0, dy0 ) ), shadowCoord.z ),
  27579. depthCompare( shadowCoord.xy.add( vec2( 0, dy0 ) ), shadowCoord.z ),
  27580. depthCompare( shadowCoord.xy.add( vec2( dx1, dy0 ) ), shadowCoord.z ),
  27581. depthCompare( shadowCoord.xy.add( vec2( dx2, dy2 ) ), shadowCoord.z ),
  27582. depthCompare( shadowCoord.xy.add( vec2( 0, dy2 ) ), shadowCoord.z ),
  27583. depthCompare( shadowCoord.xy.add( vec2( dx3, dy2 ) ), shadowCoord.z ),
  27584. depthCompare( shadowCoord.xy.add( vec2( dx0, 0 ) ), shadowCoord.z ),
  27585. depthCompare( shadowCoord.xy.add( vec2( dx2, 0 ) ), shadowCoord.z ),
  27586. depthCompare( shadowCoord.xy, shadowCoord.z ),
  27587. depthCompare( shadowCoord.xy.add( vec2( dx3, 0 ) ), shadowCoord.z ),
  27588. depthCompare( shadowCoord.xy.add( vec2( dx1, 0 ) ), shadowCoord.z ),
  27589. depthCompare( shadowCoord.xy.add( vec2( dx2, dy3 ) ), shadowCoord.z ),
  27590. depthCompare( shadowCoord.xy.add( vec2( 0, dy3 ) ), shadowCoord.z ),
  27591. depthCompare( shadowCoord.xy.add( vec2( dx3, dy3 ) ), shadowCoord.z ),
  27592. depthCompare( shadowCoord.xy.add( vec2( dx0, dy1 ) ), shadowCoord.z ),
  27593. depthCompare( shadowCoord.xy.add( vec2( 0, dy1 ) ), shadowCoord.z ),
  27594. depthCompare( shadowCoord.xy.add( vec2( dx1, dy1 ) ), shadowCoord.z )
  27595. ).mul( 1 / 17 );
  27596. } );
  27597. /**
  27598. * A shadow filtering function performing PCF soft filtering.
  27599. *
  27600. * @method
  27601. * @param {Object} inputs - The input parameter object.
  27602. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27603. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27604. * @param {LightShadow} inputs.shadow - The light shadow.
  27605. * @return {Node<float>} The filtering result.
  27606. */
  27607. const PCFSoftShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, shadow, depthLayer } ) => {
  27608. const depthCompare = ( uv, compare ) => {
  27609. let depth = texture( depthTexture, uv );
  27610. if ( depthTexture.isArrayTexture ) {
  27611. depth = depth.depth( depthLayer );
  27612. }
  27613. return depth.compare( compare );
  27614. };
  27615. const mapSize = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  27616. const texelSize = vec2( 1 ).div( mapSize );
  27617. const dx = texelSize.x;
  27618. const dy = texelSize.y;
  27619. const uv = shadowCoord.xy;
  27620. const f = fract( uv.mul( mapSize ).add( 0.5 ) );
  27621. uv.subAssign( f.mul( texelSize ) );
  27622. return add(
  27623. depthCompare( uv, shadowCoord.z ),
  27624. depthCompare( uv.add( vec2( dx, 0 ) ), shadowCoord.z ),
  27625. depthCompare( uv.add( vec2( 0, dy ) ), shadowCoord.z ),
  27626. depthCompare( uv.add( texelSize ), shadowCoord.z ),
  27627. mix(
  27628. depthCompare( uv.add( vec2( dx.negate(), 0 ) ), shadowCoord.z ),
  27629. depthCompare( uv.add( vec2( dx.mul( 2 ), 0 ) ), shadowCoord.z ),
  27630. f.x
  27631. ),
  27632. mix(
  27633. depthCompare( uv.add( vec2( dx.negate(), dy ) ), shadowCoord.z ),
  27634. depthCompare( uv.add( vec2( dx.mul( 2 ), dy ) ), shadowCoord.z ),
  27635. f.x
  27636. ),
  27637. mix(
  27638. depthCompare( uv.add( vec2( 0, dy.negate() ) ), shadowCoord.z ),
  27639. depthCompare( uv.add( vec2( 0, dy.mul( 2 ) ) ), shadowCoord.z ),
  27640. f.y
  27641. ),
  27642. mix(
  27643. depthCompare( uv.add( vec2( dx, dy.negate() ) ), shadowCoord.z ),
  27644. depthCompare( uv.add( vec2( dx, dy.mul( 2 ) ) ), shadowCoord.z ),
  27645. f.y
  27646. ),
  27647. mix(
  27648. mix(
  27649. depthCompare( uv.add( vec2( dx.negate(), dy.negate() ) ), shadowCoord.z ),
  27650. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.negate() ) ), shadowCoord.z ),
  27651. f.x
  27652. ),
  27653. mix(
  27654. depthCompare( uv.add( vec2( dx.negate(), dy.mul( 2 ) ) ), shadowCoord.z ),
  27655. depthCompare( uv.add( vec2( dx.mul( 2 ), dy.mul( 2 ) ) ), shadowCoord.z ),
  27656. f.x
  27657. ),
  27658. f.y
  27659. )
  27660. ).mul( 1 / 9 );
  27661. } );
  27662. /**
  27663. * A shadow filtering function performing VSM filtering.
  27664. *
  27665. * @method
  27666. * @param {Object} inputs - The input parameter object.
  27667. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27668. * @param {Node<vec3>} inputs.shadowCoord - The shadow coordinates.
  27669. * @return {Node<float>} The filtering result.
  27670. */
  27671. const VSMShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, shadowCoord, depthLayer } ) => {
  27672. const occlusion = float( 1 ).toVar();
  27673. let distribution = texture( depthTexture ).sample( shadowCoord.xy );
  27674. if ( depthTexture.isArrayTexture ) {
  27675. distribution = distribution.depth( depthLayer );
  27676. }
  27677. distribution = distribution.rg;
  27678. const hardShadow = step( shadowCoord.z, distribution.x );
  27679. If( hardShadow.notEqual( float( 1.0 ) ), () => {
  27680. const distance = shadowCoord.z.sub( distribution.x );
  27681. const variance = max$1( 0, distribution.y.mul( distribution.y ) );
  27682. let softnessProbability = variance.div( variance.add( distance.mul( distance ) ) ); // Chebeyshevs inequality
  27683. softnessProbability = clamp( sub( softnessProbability, 0.3 ).div( 0.95 - 0.3 ) );
  27684. occlusion.assign( clamp( max$1( hardShadow, softnessProbability ) ) );
  27685. } );
  27686. return occlusion;
  27687. } );
  27688. //
  27689. const linearDistance = /*@__PURE__*/ Fn( ( [ position, cameraNear, cameraFar ] ) => {
  27690. let dist = positionWorld.sub( position ).length();
  27691. dist = dist.sub( cameraNear ).div( cameraFar.sub( cameraNear ) );
  27692. dist = dist.saturate(); // clamp to [ 0, 1 ]
  27693. return dist;
  27694. } );
  27695. const linearShadowDistance = ( light ) => {
  27696. const camera = light.shadow.camera;
  27697. const nearDistance = reference( 'near', 'float', camera ).setGroup( renderGroup );
  27698. const farDistance = reference( 'far', 'float', camera ).setGroup( renderGroup );
  27699. const referencePosition = objectPosition( light );
  27700. return linearDistance( referencePosition, nearDistance, farDistance );
  27701. };
  27702. /**
  27703. * Retrieves or creates a shadow material for the given light source.
  27704. *
  27705. * This function checks if a shadow material already exists for the provided light.
  27706. * If not, it creates a new `NodeMaterial` configured for shadow rendering and stores it
  27707. * in the `shadowMaterialLib` for future use.
  27708. *
  27709. * @param {Light} light - The light source for which the shadow material is needed.
  27710. * If the light is a point light, a depth node is calculated
  27711. * using the linear shadow distance.
  27712. * @returns {NodeMaterial} The shadow material associated with the given light.
  27713. */
  27714. const getShadowMaterial = ( light ) => {
  27715. let material = shadowMaterialLib.get( light );
  27716. if ( material === undefined ) {
  27717. const depthNode = light.isPointLight ? linearShadowDistance( light ) : null;
  27718. material = new NodeMaterial();
  27719. material.colorNode = vec4( 0, 0, 0, 1 );
  27720. material.depthNode = depthNode;
  27721. material.isShadowPassMaterial = true; // Use to avoid other overrideMaterial override material.colorNode unintentionally when using material.shadowNode
  27722. material.name = 'ShadowMaterial';
  27723. material.fog = false;
  27724. shadowMaterialLib.set( light, material );
  27725. }
  27726. return material;
  27727. };
  27728. //
  27729. const _shadowRenderObjectLibrary = /*@__PURE__*/ new ChainMap();
  27730. const _shadowRenderObjectKeys = [];
  27731. /**
  27732. * Creates a function to render shadow objects in a scene.
  27733. *
  27734. * @param {Renderer} renderer - The renderer.
  27735. * @param {LightShadow} shadow - The light shadow object containing shadow properties.
  27736. * @param {number} shadowType - The type of shadow map (e.g., BasicShadowMap).
  27737. * @param {boolean} useVelocity - Whether to use velocity data for rendering.
  27738. * @return {Function} A function that renders shadow objects.
  27739. *
  27740. * The returned function has the following parameters:
  27741. * @param {Object3D} object - The 3D object to render.
  27742. * @param {Scene} scene - The scene containing the object.
  27743. * @param {Camera} _camera - The camera used for rendering.
  27744. * @param {BufferGeometry} geometry - The geometry of the object.
  27745. * @param {Material} material - The material of the object.
  27746. * @param {Group} group - The group the object belongs to.
  27747. * @param {...any} params - Additional parameters for rendering.
  27748. */
  27749. const getShadowRenderObjectFunction = ( renderer, shadow, shadowType, useVelocity ) => {
  27750. _shadowRenderObjectKeys[ 0 ] = renderer;
  27751. _shadowRenderObjectKeys[ 1 ] = shadow;
  27752. let renderObjectFunction = _shadowRenderObjectLibrary.get( _shadowRenderObjectKeys );
  27753. if ( renderObjectFunction === undefined || ( renderObjectFunction.shadowType !== shadowType || renderObjectFunction.useVelocity !== useVelocity ) ) {
  27754. renderObjectFunction = ( object, scene, _camera, geometry, material, group, ...params ) => {
  27755. if ( object.castShadow === true || ( object.receiveShadow && shadowType === VSMShadowMap ) ) {
  27756. if ( useVelocity ) {
  27757. getDataFromObject( object ).useVelocity = true;
  27758. }
  27759. object.onBeforeShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  27760. renderer.renderObject( object, scene, _camera, geometry, material, group, ...params );
  27761. object.onAfterShadow( renderer, object, _camera, shadow.camera, geometry, scene.overrideMaterial, group );
  27762. }
  27763. };
  27764. renderObjectFunction.shadowType = shadowType;
  27765. renderObjectFunction.useVelocity = useVelocity;
  27766. _shadowRenderObjectLibrary.set( _shadowRenderObjectKeys, renderObjectFunction );
  27767. }
  27768. _shadowRenderObjectKeys[ 0 ] = null;
  27769. _shadowRenderObjectKeys[ 1 ] = null;
  27770. return renderObjectFunction;
  27771. };
  27772. /**
  27773. * Represents the shader code for the first VSM render pass.
  27774. *
  27775. * @method
  27776. * @param {Object} inputs - The input parameter object.
  27777. * @param {Node<float>} inputs.samples - The number of samples
  27778. * @param {Node<float>} inputs.radius - The radius.
  27779. * @param {Node<float>} inputs.size - The size.
  27780. * @param {TextureNode} inputs.shadowPass - A reference to the render target's depth data.
  27781. * @return {Node<vec2>} The VSM output.
  27782. */
  27783. const VSMPassVertical = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  27784. const mean = float( 0 ).toVar( 'meanVertical' );
  27785. const squaredMean = float( 0 ).toVar( 'squareMeanVertical' );
  27786. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  27787. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  27788. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  27789. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  27790. let depth = shadowPass.sample( add( screenCoordinate.xy, vec2( 0, uvOffset ).mul( radius ) ).div( size ) );
  27791. if ( shadowPass.value.isArrayTexture ) {
  27792. depth = depth.depth( depthLayer );
  27793. }
  27794. depth = depth.x;
  27795. mean.addAssign( depth );
  27796. squaredMean.addAssign( depth.mul( depth ) );
  27797. } );
  27798. mean.divAssign( samples );
  27799. squaredMean.divAssign( samples );
  27800. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  27801. return vec2( mean, std_dev );
  27802. } );
  27803. /**
  27804. * Represents the shader code for the second VSM render pass.
  27805. *
  27806. * @method
  27807. * @param {Object} inputs - The input parameter object.
  27808. * @param {Node<float>} inputs.samples - The number of samples
  27809. * @param {Node<float>} inputs.radius - The radius.
  27810. * @param {Node<float>} inputs.size - The size.
  27811. * @param {TextureNode} inputs.shadowPass - The result of the first VSM render pass.
  27812. * @return {Node<vec2>} The VSM output.
  27813. */
  27814. const VSMPassHorizontal = /*@__PURE__*/ Fn( ( { samples, radius, size, shadowPass, depthLayer } ) => {
  27815. const mean = float( 0 ).toVar( 'meanHorizontal' );
  27816. const squaredMean = float( 0 ).toVar( 'squareMeanHorizontal' );
  27817. const uvStride = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( 2 ).div( samples.sub( 1 ) ) );
  27818. const uvStart = samples.lessThanEqual( float( 1 ) ).select( float( 0 ), float( -1 ) );
  27819. Loop( { start: int( 0 ), end: int( samples ), type: 'int', condition: '<' }, ( { i } ) => {
  27820. const uvOffset = uvStart.add( float( i ).mul( uvStride ) );
  27821. let distribution = shadowPass.sample( add( screenCoordinate.xy, vec2( uvOffset, 0 ).mul( radius ) ).div( size ) );
  27822. if ( shadowPass.value.isArrayTexture ) {
  27823. distribution = distribution.depth( depthLayer );
  27824. }
  27825. mean.addAssign( distribution.x );
  27826. squaredMean.addAssign( add( distribution.y.mul( distribution.y ), distribution.x.mul( distribution.x ) ) );
  27827. } );
  27828. mean.divAssign( samples );
  27829. squaredMean.divAssign( samples );
  27830. const std_dev = sqrt( squaredMean.sub( mean.mul( mean ) ) );
  27831. return vec2( mean, std_dev );
  27832. } );
  27833. const _shadowFilterLib = [ BasicShadowFilter, PCFShadowFilter, PCFSoftShadowFilter, VSMShadowFilter ];
  27834. //
  27835. let _rendererState;
  27836. const _quadMesh = /*@__PURE__*/ new QuadMesh();
  27837. /**
  27838. * Represents the default shadow implementation for lighting nodes.
  27839. *
  27840. * @augments ShadowBaseNode
  27841. */
  27842. class ShadowNode extends ShadowBaseNode {
  27843. static get type() {
  27844. return 'ShadowNode';
  27845. }
  27846. /**
  27847. * Constructs a new shadow node.
  27848. *
  27849. * @param {Light} light - The shadow casting light.
  27850. * @param {?LightShadow} [shadow=null] - An optional light shadow.
  27851. */
  27852. constructor( light, shadow = null ) {
  27853. super( light );
  27854. /**
  27855. * The light shadow which defines the properties light's
  27856. * shadow.
  27857. *
  27858. * @type {?LightShadow}
  27859. * @default null
  27860. */
  27861. this.shadow = shadow || light.shadow;
  27862. /**
  27863. * A reference to the shadow map which is a render target.
  27864. *
  27865. * @type {?RenderTarget}
  27866. * @default null
  27867. */
  27868. this.shadowMap = null;
  27869. /**
  27870. * Only relevant for VSM shadows. Render target for the
  27871. * first VSM render pass.
  27872. *
  27873. * @type {?RenderTarget}
  27874. * @default null
  27875. */
  27876. this.vsmShadowMapVertical = null;
  27877. /**
  27878. * Only relevant for VSM shadows. Render target for the
  27879. * second VSM render pass.
  27880. *
  27881. * @type {?RenderTarget}
  27882. * @default null
  27883. */
  27884. this.vsmShadowMapHorizontal = null;
  27885. /**
  27886. * Only relevant for VSM shadows. Node material which
  27887. * is used to render the first VSM pass.
  27888. *
  27889. * @type {?NodeMaterial}
  27890. * @default null
  27891. */
  27892. this.vsmMaterialVertical = null;
  27893. /**
  27894. * Only relevant for VSM shadows. Node material which
  27895. * is used to render the second VSM pass.
  27896. *
  27897. * @type {?NodeMaterial}
  27898. * @default null
  27899. */
  27900. this.vsmMaterialHorizontal = null;
  27901. /**
  27902. * A reference to the output node which defines the
  27903. * final result of this shadow node.
  27904. *
  27905. * @type {?Node}
  27906. * @private
  27907. * @default null
  27908. */
  27909. this._node = null;
  27910. this._cameraFrameId = new WeakMap();
  27911. /**
  27912. * This flag can be used for type testing.
  27913. *
  27914. * @type {boolean}
  27915. * @readonly
  27916. * @default true
  27917. */
  27918. this.isShadowNode = true;
  27919. /**
  27920. * This index can be used when overriding setupRenderTarget with a RenderTarget Array to specify the depth layer.
  27921. *
  27922. * @type {number}
  27923. * @readonly
  27924. * @default true
  27925. */
  27926. this.depthLayer = 0;
  27927. }
  27928. /**
  27929. * Setups the shadow filtering.
  27930. *
  27931. * @param {NodeBuilder} builder - A reference to the current node builder.
  27932. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  27933. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  27934. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  27935. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  27936. * @param {LightShadow} inputs.shadow - The light shadow.
  27937. * @return {Node<float>} The result node of the shadow filtering.
  27938. */
  27939. setupShadowFilter( builder, { filterFn, depthTexture, shadowCoord, shadow, depthLayer } ) {
  27940. const frustumTest = shadowCoord.x.greaterThanEqual( 0 )
  27941. .and( shadowCoord.x.lessThanEqual( 1 ) )
  27942. .and( shadowCoord.y.greaterThanEqual( 0 ) )
  27943. .and( shadowCoord.y.lessThanEqual( 1 ) )
  27944. .and( shadowCoord.z.lessThanEqual( 1 ) );
  27945. const shadowNode = filterFn( { depthTexture, shadowCoord, shadow, depthLayer } );
  27946. return frustumTest.select( shadowNode, float( 1 ) );
  27947. }
  27948. /**
  27949. * Setups the shadow coordinates.
  27950. *
  27951. * @param {NodeBuilder} builder - A reference to the current node builder.
  27952. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  27953. * @return {Node<vec3>} The shadow coordinates.
  27954. */
  27955. setupShadowCoord( builder, shadowPosition ) {
  27956. const { shadow } = this;
  27957. const { renderer } = builder;
  27958. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  27959. let shadowCoord = shadowPosition;
  27960. let coordZ;
  27961. if ( shadow.camera.isOrthographicCamera || renderer.logarithmicDepthBuffer !== true ) {
  27962. shadowCoord = shadowCoord.xyz.div( shadowCoord.w );
  27963. coordZ = shadowCoord.z;
  27964. if ( renderer.coordinateSystem === WebGPUCoordinateSystem ) {
  27965. coordZ = coordZ.mul( 2 ).sub( 1 ); // WebGPU: Conversion [ 0, 1 ] to [ - 1, 1 ]
  27966. }
  27967. } else {
  27968. const w = shadowCoord.w;
  27969. shadowCoord = shadowCoord.xy.div( w ); // <-- Only divide X/Y coords since we don't need Z
  27970. // The normally available "cameraNear" and "cameraFar" nodes cannot be used here because they do not get
  27971. // updated to use the shadow camera. So, we have to declare our own "local" ones here.
  27972. // TODO: How do we get the cameraNear/cameraFar nodes to use the shadow camera so we don't have to declare local ones here?
  27973. const cameraNearLocal = reference( 'near', 'float', shadow.camera ).setGroup( renderGroup );
  27974. const cameraFarLocal = reference( 'far', 'float', shadow.camera ).setGroup( renderGroup );
  27975. coordZ = viewZToLogarithmicDepth( w.negate(), cameraNearLocal, cameraFarLocal );
  27976. }
  27977. shadowCoord = vec3(
  27978. shadowCoord.x,
  27979. shadowCoord.y.oneMinus(), // follow webgpu standards
  27980. coordZ.add( bias )
  27981. );
  27982. return shadowCoord;
  27983. }
  27984. /**
  27985. * Returns the shadow filtering function for the given shadow type.
  27986. *
  27987. * @param {number} type - The shadow type.
  27988. * @return {Function} The filtering function.
  27989. */
  27990. getShadowFilterFn( type ) {
  27991. return _shadowFilterLib[ type ];
  27992. }
  27993. setupRenderTarget( shadow, builder ) {
  27994. const depthTexture = new DepthTexture( shadow.mapSize.width, shadow.mapSize.height );
  27995. depthTexture.name = 'ShadowDepthTexture';
  27996. depthTexture.compareFunction = LessCompare;
  27997. const shadowMap = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height );
  27998. shadowMap.texture.name = 'ShadowMap';
  27999. shadowMap.texture.type = shadow.mapType;
  28000. shadowMap.depthTexture = depthTexture;
  28001. return { shadowMap, depthTexture };
  28002. }
  28003. /**
  28004. * Setups the shadow output node.
  28005. *
  28006. * @param {NodeBuilder} builder - A reference to the current node builder.
  28007. * @return {Node<vec3>} The shadow output node.
  28008. */
  28009. setupShadow( builder ) {
  28010. const { renderer } = builder;
  28011. const { light, shadow } = this;
  28012. const shadowMapType = renderer.shadowMap.type;
  28013. const { depthTexture, shadowMap } = this.setupRenderTarget( shadow, builder );
  28014. shadow.camera.updateProjectionMatrix();
  28015. // VSM
  28016. if ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  28017. depthTexture.compareFunction = null; // VSM does not use textureSampleCompare()/texture2DCompare()
  28018. if ( shadowMap.depth > 1 ) {
  28019. if ( ! shadowMap._vsmShadowMapVertical ) {
  28020. shadowMap._vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  28021. shadowMap._vsmShadowMapVertical.texture.name = 'VSMVertical';
  28022. }
  28023. this.vsmShadowMapVertical = shadowMap._vsmShadowMapVertical;
  28024. if ( ! shadowMap._vsmShadowMapHorizontal ) {
  28025. shadowMap._vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depth: shadowMap.depth, depthBuffer: false } );
  28026. shadowMap._vsmShadowMapHorizontal.texture.name = 'VSMHorizontal';
  28027. }
  28028. this.vsmShadowMapHorizontal = shadowMap._vsmShadowMapHorizontal;
  28029. } else {
  28030. this.vsmShadowMapVertical = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  28031. this.vsmShadowMapHorizontal = builder.createRenderTarget( shadow.mapSize.width, shadow.mapSize.height, { format: RGFormat, type: HalfFloatType, depthBuffer: false } );
  28032. }
  28033. let shadowPassVertical = texture( depthTexture );
  28034. if ( depthTexture.isArrayTexture ) {
  28035. shadowPassVertical = shadowPassVertical.depth( this.depthLayer );
  28036. }
  28037. let shadowPassHorizontal = texture( this.vsmShadowMapVertical.texture );
  28038. if ( depthTexture.isArrayTexture ) {
  28039. shadowPassHorizontal = shadowPassHorizontal.depth( this.depthLayer );
  28040. }
  28041. const samples = reference( 'blurSamples', 'float', shadow ).setGroup( renderGroup );
  28042. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  28043. const size = reference( 'mapSize', 'vec2', shadow ).setGroup( renderGroup );
  28044. let material = this.vsmMaterialVertical || ( this.vsmMaterialVertical = new NodeMaterial() );
  28045. material.fragmentNode = VSMPassVertical( { samples, radius, size, shadowPass: shadowPassVertical, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  28046. material.name = 'VSMVertical';
  28047. material = this.vsmMaterialHorizontal || ( this.vsmMaterialHorizontal = new NodeMaterial() );
  28048. material.fragmentNode = VSMPassHorizontal( { samples, radius, size, shadowPass: shadowPassHorizontal, depthLayer: this.depthLayer } ).context( builder.getSharedContext() );
  28049. material.name = 'VSMHorizontal';
  28050. }
  28051. //
  28052. const shadowIntensity = reference( 'intensity', 'float', shadow ).setGroup( renderGroup );
  28053. const normalBias = reference( 'normalBias', 'float', shadow ).setGroup( renderGroup );
  28054. const shadowPosition = lightShadowMatrix( light ).mul( shadowPositionWorld.add( transformedNormalWorld.mul( normalBias ) ) );
  28055. const shadowCoord = this.setupShadowCoord( builder, shadowPosition );
  28056. //
  28057. const filterFn = shadow.filterNode || this.getShadowFilterFn( renderer.shadowMap.type ) || null;
  28058. if ( filterFn === null ) {
  28059. throw new Error( 'THREE.WebGPURenderer: Shadow map type not supported yet.' );
  28060. }
  28061. const shadowDepthTexture = ( shadowMapType === VSMShadowMap && shadow.isPointLightShadow !== true ) ? this.vsmShadowMapHorizontal.texture : depthTexture;
  28062. const shadowNode = this.setupShadowFilter( builder, { filterFn, shadowTexture: shadowMap.texture, depthTexture: shadowDepthTexture, shadowCoord, shadow, depthLayer: this.depthLayer } );
  28063. let shadowColor = texture( shadowMap.texture, shadowCoord );
  28064. if ( depthTexture.isArrayTexture ) {
  28065. shadowColor = shadowColor.depth( this.depthLayer );
  28066. }
  28067. const shadowOutput = mix( 1, shadowNode.rgb.mix( shadowColor, 1 ), shadowIntensity.mul( shadowColor.a ) ).toVar();
  28068. this.shadowMap = shadowMap;
  28069. this.shadow.map = shadowMap;
  28070. return shadowOutput;
  28071. }
  28072. /**
  28073. * The implementation performs the setup of the output node. An output is only
  28074. * produces if shadow mapping is globally enabled in the renderer.
  28075. *
  28076. * @param {NodeBuilder} builder - A reference to the current node builder.
  28077. * @return {ShaderCallNodeInternal} The output node.
  28078. */
  28079. setup( builder ) {
  28080. if ( builder.renderer.shadowMap.enabled === false ) return;
  28081. return Fn( () => {
  28082. let node = this._node;
  28083. this.setupShadowPosition( builder );
  28084. if ( node === null ) {
  28085. this._node = node = this.setupShadow( builder );
  28086. }
  28087. if ( builder.material.shadowNode ) { // @deprecated, r171
  28088. console.warn( 'THREE.NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.' );
  28089. }
  28090. if ( builder.material.receivedShadowNode ) {
  28091. node = builder.material.receivedShadowNode( node );
  28092. }
  28093. return node;
  28094. } )();
  28095. }
  28096. /**
  28097. * Renders the shadow. The logic of this function could be included
  28098. * into {@link ShadowNode#updateShadow} however more specialized shadow
  28099. * nodes might require a custom shadow map rendering. By having a
  28100. * dedicated method, it's easier to overwrite the default behavior.
  28101. *
  28102. * @param {NodeFrame} frame - A reference to the current node frame.
  28103. */
  28104. renderShadow( frame ) {
  28105. const { shadow, shadowMap, light } = this;
  28106. const { renderer, scene } = frame;
  28107. shadow.updateMatrices( light );
  28108. shadowMap.setSize( shadow.mapSize.width, shadow.mapSize.height, shadowMap.depth );
  28109. renderer.render( scene, shadow.camera );
  28110. }
  28111. /**
  28112. * Updates the shadow.
  28113. *
  28114. * @param {NodeFrame} frame - A reference to the current node frame.
  28115. */
  28116. updateShadow( frame ) {
  28117. const { shadowMap, light, shadow } = this;
  28118. const { renderer, scene, camera } = frame;
  28119. const shadowType = renderer.shadowMap.type;
  28120. const depthVersion = shadowMap.depthTexture.version;
  28121. this._depthVersionCached = depthVersion;
  28122. const _shadowCameraLayer = shadow.camera.layers.mask;
  28123. if ( ( shadow.camera.layers.mask & 0xFFFFFFFE ) === 0 ) {
  28124. shadow.camera.layers.mask = camera.layers.mask;
  28125. }
  28126. const currentRenderObjectFunction = renderer.getRenderObjectFunction();
  28127. const currentMRT = renderer.getMRT();
  28128. const useVelocity = currentMRT ? currentMRT.has( 'velocity' ) : false;
  28129. _rendererState = resetRendererAndSceneState( renderer, scene, _rendererState );
  28130. scene.overrideMaterial = getShadowMaterial( light );
  28131. renderer.setRenderObjectFunction( getShadowRenderObjectFunction( renderer, shadow, shadowType, useVelocity ) );
  28132. renderer.setClearColor( 0x000000, 0 );
  28133. renderer.setRenderTarget( shadowMap );
  28134. this.renderShadow( frame );
  28135. renderer.setRenderObjectFunction( currentRenderObjectFunction );
  28136. // vsm blur pass
  28137. if ( shadowType === VSMShadowMap && shadow.isPointLightShadow !== true ) {
  28138. this.vsmPass( renderer );
  28139. }
  28140. shadow.camera.layers.mask = _shadowCameraLayer;
  28141. restoreRendererAndSceneState( renderer, scene, _rendererState );
  28142. }
  28143. /**
  28144. * For VSM additional render passes are required.
  28145. *
  28146. * @param {Renderer} renderer - A reference to the current renderer.
  28147. */
  28148. vsmPass( renderer ) {
  28149. const { shadow } = this;
  28150. const depth = this.shadowMap.depth;
  28151. this.vsmShadowMapVertical.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  28152. this.vsmShadowMapHorizontal.setSize( shadow.mapSize.width, shadow.mapSize.height, depth );
  28153. renderer.setRenderTarget( this.vsmShadowMapVertical );
  28154. _quadMesh.material = this.vsmMaterialVertical;
  28155. _quadMesh.render( renderer );
  28156. renderer.setRenderTarget( this.vsmShadowMapHorizontal );
  28157. _quadMesh.material = this.vsmMaterialHorizontal;
  28158. _quadMesh.render( renderer );
  28159. }
  28160. /**
  28161. * Frees the internal resources of this shadow node.
  28162. */
  28163. dispose() {
  28164. this.shadowMap.dispose();
  28165. this.shadowMap = null;
  28166. if ( this.vsmShadowMapVertical !== null ) {
  28167. this.vsmShadowMapVertical.dispose();
  28168. this.vsmShadowMapVertical = null;
  28169. this.vsmMaterialVertical.dispose();
  28170. this.vsmMaterialVertical = null;
  28171. }
  28172. if ( this.vsmShadowMapHorizontal !== null ) {
  28173. this.vsmShadowMapHorizontal.dispose();
  28174. this.vsmShadowMapHorizontal = null;
  28175. this.vsmMaterialHorizontal.dispose();
  28176. this.vsmMaterialHorizontal = null;
  28177. }
  28178. super.dispose();
  28179. }
  28180. /**
  28181. * The implementation performs the update of the shadow map if necessary.
  28182. *
  28183. * @param {NodeFrame} frame - A reference to the current node frame.
  28184. */
  28185. updateBefore( frame ) {
  28186. const { shadow } = this;
  28187. let needsUpdate = shadow.needsUpdate || shadow.autoUpdate;
  28188. if ( needsUpdate ) {
  28189. if ( this._cameraFrameId[ frame.camera ] === frame.frameId ) {
  28190. needsUpdate = false;
  28191. }
  28192. this._cameraFrameId[ frame.camera ] = frame.frameId;
  28193. }
  28194. if ( needsUpdate ) {
  28195. this.updateShadow( frame );
  28196. if ( this.shadowMap.depthTexture.version === this._depthVersionCached ) {
  28197. shadow.needsUpdate = false;
  28198. }
  28199. }
  28200. }
  28201. }
  28202. /**
  28203. * TSL function for creating an instance of `ShadowNode`.
  28204. *
  28205. * @tsl
  28206. * @function
  28207. * @param {Light} light - The shadow casting light.
  28208. * @param {?LightShadow} [shadow] - The light shadow.
  28209. * @return {ShadowNode} The created shadow node.
  28210. */
  28211. const shadow = ( light, shadow ) => nodeObject( new ShadowNode( light, shadow ) );
  28212. const _clearColor$1 = /*@__PURE__*/ new Color();
  28213. // cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D
  28214. // vector suitable for 2D texture mapping. This code uses the following layout for the
  28215. // 2D texture:
  28216. //
  28217. // xzXZ
  28218. // y Y
  28219. //
  28220. // Y - Positive y direction
  28221. // y - Negative y direction
  28222. // X - Positive x direction
  28223. // x - Negative x direction
  28224. // Z - Positive z direction
  28225. // z - Negative z direction
  28226. //
  28227. // Source and test bed:
  28228. // https://gist.github.com/tschw/da10c43c467ce8afd0c4
  28229. const cubeToUV = /*@__PURE__*/ Fn( ( [ pos, texelSizeY ] ) => {
  28230. const v = pos.toVar();
  28231. // Number of texels to avoid at the edge of each square
  28232. const absV = abs( v );
  28233. // Intersect unit cube
  28234. const scaleToCube = div( 1.0, max$1( absV.x, max$1( absV.y, absV.z ) ) );
  28235. absV.mulAssign( scaleToCube );
  28236. // Apply scale to avoid seams
  28237. // two texels less per square (one texel will do for NEAREST)
  28238. v.mulAssign( scaleToCube.mul( texelSizeY.mul( 2 ).oneMinus() ) );
  28239. // Unwrap
  28240. // space: -1 ... 1 range for each square
  28241. //
  28242. // #X## dim := ( 4 , 2 )
  28243. // # # center := ( 1 , 1 )
  28244. const planar = vec2( v.xy ).toVar();
  28245. const almostATexel = texelSizeY.mul( 1.5 );
  28246. const almostOne = almostATexel.oneMinus();
  28247. If( absV.z.greaterThanEqual( almostOne ), () => {
  28248. If( v.z.greaterThan( 0.0 ), () => {
  28249. planar.x.assign( sub( 4.0, v.x ) );
  28250. } );
  28251. } ).ElseIf( absV.x.greaterThanEqual( almostOne ), () => {
  28252. const signX = sign( v.x );
  28253. planar.x.assign( v.z.mul( signX ).add( signX.mul( 2.0 ) ) );
  28254. } ).ElseIf( absV.y.greaterThanEqual( almostOne ), () => {
  28255. const signY = sign( v.y );
  28256. planar.x.assign( v.x.add( signY.mul( 2.0 ) ).add( 2.0 ) );
  28257. planar.y.assign( v.z.mul( signY ).sub( 2.0 ) );
  28258. } );
  28259. // Transform to UV space
  28260. // scale := 0.5 / dim
  28261. // translate := ( center + 0.5 ) / dim
  28262. return vec2( 0.125, 0.25 ).mul( planar ).add( vec2( 0.375, 0.75 ) ).flipY();
  28263. } ).setLayout( {
  28264. name: 'cubeToUV',
  28265. type: 'vec2',
  28266. inputs: [
  28267. { name: 'pos', type: 'vec3' },
  28268. { name: 'texelSizeY', type: 'float' }
  28269. ]
  28270. } );
  28271. const BasicPointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize } ) => {
  28272. return texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp );
  28273. } );
  28274. const PointShadowFilter = /*@__PURE__*/ Fn( ( { depthTexture, bd3D, dp, texelSize, shadow } ) => {
  28275. const radius = reference( 'radius', 'float', shadow ).setGroup( renderGroup );
  28276. const offset = vec2( -1, 1.0 ).mul( radius ).mul( texelSize.y );
  28277. return texture( depthTexture, cubeToUV( bd3D.add( offset.xyy ), texelSize.y ) ).compare( dp )
  28278. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyy ), texelSize.y ) ).compare( dp ) )
  28279. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xyx ), texelSize.y ) ).compare( dp ) )
  28280. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yyx ), texelSize.y ) ).compare( dp ) )
  28281. .add( texture( depthTexture, cubeToUV( bd3D, texelSize.y ) ).compare( dp ) )
  28282. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxy ), texelSize.y ) ).compare( dp ) )
  28283. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxy ), texelSize.y ) ).compare( dp ) )
  28284. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.xxx ), texelSize.y ) ).compare( dp ) )
  28285. .add( texture( depthTexture, cubeToUV( bd3D.add( offset.yxx ), texelSize.y ) ).compare( dp ) )
  28286. .mul( 1.0 / 9.0 );
  28287. } );
  28288. const pointShadowFilter = /*@__PURE__*/ Fn( ( { filterFn, depthTexture, shadowCoord, shadow } ) => {
  28289. // for point lights, the uniform @vShadowCoord is re-purposed to hold
  28290. // the vector from the light to the world-space position of the fragment.
  28291. const lightToPosition = shadowCoord.xyz.toVar();
  28292. const lightToPositionLength = lightToPosition.length();
  28293. const cameraNearLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.near );
  28294. const cameraFarLocal = uniform( 'float' ).setGroup( renderGroup ).onRenderUpdate( () => shadow.camera.far );
  28295. const bias = reference( 'bias', 'float', shadow ).setGroup( renderGroup );
  28296. const mapSize = uniform( shadow.mapSize ).setGroup( renderGroup );
  28297. const result = float( 1.0 ).toVar();
  28298. If( lightToPositionLength.sub( cameraFarLocal ).lessThanEqual( 0.0 ).and( lightToPositionLength.sub( cameraNearLocal ).greaterThanEqual( 0.0 ) ), () => {
  28299. // dp = normalized distance from light to fragment position
  28300. const dp = lightToPositionLength.sub( cameraNearLocal ).div( cameraFarLocal.sub( cameraNearLocal ) ).toVar(); // need to clamp?
  28301. dp.addAssign( bias );
  28302. // bd3D = base direction 3D
  28303. const bd3D = lightToPosition.normalize();
  28304. const texelSize = vec2( 1.0 ).div( mapSize.mul( vec2( 4.0, 2.0 ) ) );
  28305. // percentage-closer filtering
  28306. result.assign( filterFn( { depthTexture, bd3D, dp, texelSize, shadow } ) );
  28307. } );
  28308. return result;
  28309. } );
  28310. const _viewport = /*@__PURE__*/ new Vector4();
  28311. const _viewportSize = /*@__PURE__*/ new Vector2();
  28312. const _shadowMapSize = /*@__PURE__*/ new Vector2();
  28313. /**
  28314. * Represents the shadow implementation for point light nodes.
  28315. *
  28316. * @augments ShadowNode
  28317. */
  28318. class PointShadowNode extends ShadowNode {
  28319. static get type() {
  28320. return 'PointShadowNode';
  28321. }
  28322. /**
  28323. * Constructs a new point shadow node.
  28324. *
  28325. * @param {PointLight} light - The shadow casting point light.
  28326. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  28327. */
  28328. constructor( light, shadow = null ) {
  28329. super( light, shadow );
  28330. }
  28331. /**
  28332. * Overwrites the default implementation to return point light shadow specific
  28333. * filtering functions.
  28334. *
  28335. * @param {number} type - The shadow type.
  28336. * @return {Function} The filtering function.
  28337. */
  28338. getShadowFilterFn( type ) {
  28339. return type === BasicShadowMap ? BasicPointShadowFilter : PointShadowFilter;
  28340. }
  28341. /**
  28342. * Overwrites the default implementation so the unaltered shadow position is used.
  28343. *
  28344. * @param {NodeBuilder} builder - A reference to the current node builder.
  28345. * @param {Node<vec3>} shadowPosition - A node representing the shadow position.
  28346. * @return {Node<vec3>} The shadow coordinates.
  28347. */
  28348. setupShadowCoord( builder, shadowPosition ) {
  28349. return shadowPosition;
  28350. }
  28351. /**
  28352. * Overwrites the default implementation to only use point light specific
  28353. * shadow filter functions.
  28354. *
  28355. * @param {NodeBuilder} builder - A reference to the current node builder.
  28356. * @param {Object} inputs - A configuration object that defines the shadow filtering.
  28357. * @param {Function} inputs.filterFn - This function defines the filtering type of the shadow map e.g. PCF.
  28358. * @param {Texture} inputs.shadowTexture - A reference to the shadow map's texture.
  28359. * @param {DepthTexture} inputs.depthTexture - A reference to the shadow map's texture data.
  28360. * @param {Node<vec3>} inputs.shadowCoord - Shadow coordinates which are used to sample from the shadow map.
  28361. * @param {LightShadow} inputs.shadow - The light shadow.
  28362. * @return {Node<float>} The result node of the shadow filtering.
  28363. */
  28364. setupShadowFilter( builder, { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } ) {
  28365. return pointShadowFilter( { filterFn, shadowTexture, depthTexture, shadowCoord, shadow } );
  28366. }
  28367. /**
  28368. * Overwrites the default implementation with point light specific
  28369. * rendering code.
  28370. *
  28371. * @param {NodeFrame} frame - A reference to the current node frame.
  28372. */
  28373. renderShadow( frame ) {
  28374. const { shadow, shadowMap, light } = this;
  28375. const { renderer, scene } = frame;
  28376. const shadowFrameExtents = shadow.getFrameExtents();
  28377. _shadowMapSize.copy( shadow.mapSize );
  28378. _shadowMapSize.multiply( shadowFrameExtents );
  28379. shadowMap.setSize( _shadowMapSize.width, _shadowMapSize.height );
  28380. _viewportSize.copy( shadow.mapSize );
  28381. //
  28382. const previousAutoClear = renderer.autoClear;
  28383. const previousClearColor = renderer.getClearColor( _clearColor$1 );
  28384. const previousClearAlpha = renderer.getClearAlpha();
  28385. renderer.autoClear = false;
  28386. renderer.setClearColor( shadow.clearColor, shadow.clearAlpha );
  28387. renderer.clear();
  28388. const viewportCount = shadow.getViewportCount();
  28389. for ( let vp = 0; vp < viewportCount; vp ++ ) {
  28390. const viewport = shadow.getViewport( vp );
  28391. const x = _viewportSize.x * viewport.x;
  28392. const y = _shadowMapSize.y - _viewportSize.y - ( _viewportSize.y * viewport.y );
  28393. _viewport.set(
  28394. x,
  28395. y,
  28396. _viewportSize.x * viewport.z,
  28397. _viewportSize.y * viewport.w
  28398. );
  28399. shadowMap.viewport.copy( _viewport );
  28400. shadow.updateMatrices( light, vp );
  28401. renderer.render( scene, shadow.camera );
  28402. }
  28403. //
  28404. renderer.autoClear = previousAutoClear;
  28405. renderer.setClearColor( previousClearColor, previousClearAlpha );
  28406. }
  28407. }
  28408. /**
  28409. * TSL function for creating an instance of `PointShadowNode`.
  28410. *
  28411. * @tsl
  28412. * @function
  28413. * @param {PointLight} light - The shadow casting point light.
  28414. * @param {?PointLightShadow} [shadow=null] - An optional point light shadow.
  28415. * @return {PointShadowNode} The created point shadow node.
  28416. */
  28417. const pointShadow = ( light, shadow ) => nodeObject( new PointShadowNode( light, shadow ) );
  28418. /**
  28419. * Base class for analytic light nodes.
  28420. *
  28421. * @augments LightingNode
  28422. */
  28423. class AnalyticLightNode extends LightingNode {
  28424. static get type() {
  28425. return 'AnalyticLightNode';
  28426. }
  28427. /**
  28428. * Constructs a new analytic light node.
  28429. *
  28430. * @param {?Light} [light=null] - The light source.
  28431. */
  28432. constructor( light = null ) {
  28433. super();
  28434. /**
  28435. * The light source.
  28436. *
  28437. * @type {?Light}
  28438. * @default null
  28439. */
  28440. this.light = light;
  28441. /**
  28442. * The light's color value.
  28443. *
  28444. * @type {Color}
  28445. */
  28446. this.color = new Color();
  28447. /**
  28448. * The light's color node. Points to `colorNode` of the light source, if set. Otherwise
  28449. * it creates a uniform node based on {@link AnalyticLightNode#color}.
  28450. *
  28451. * @type {Node}
  28452. */
  28453. this.colorNode = ( light && light.colorNode ) || uniform( this.color ).setGroup( renderGroup );
  28454. /**
  28455. * This property is used to retain a reference to the original value of {@link AnalyticLightNode#colorNode}.
  28456. * The final color node is represented by a different node when using shadows.
  28457. *
  28458. * @type {?Node}
  28459. * @default null
  28460. */
  28461. this.baseColorNode = null;
  28462. /**
  28463. * Represents the light's shadow.
  28464. *
  28465. * @type {?ShadowNode}
  28466. * @default null
  28467. */
  28468. this.shadowNode = null;
  28469. /**
  28470. * Represents the light's shadow color.
  28471. *
  28472. * @type {?Node}
  28473. * @default null
  28474. */
  28475. this.shadowColorNode = null;
  28476. /**
  28477. * This flag can be used for type testing.
  28478. *
  28479. * @type {boolean}
  28480. * @readonly
  28481. * @default true
  28482. */
  28483. this.isAnalyticLightNode = true;
  28484. /**
  28485. * Overwritten since analytic light nodes are updated
  28486. * once per frame.
  28487. *
  28488. * @type {string}
  28489. * @default 'frame'
  28490. */
  28491. this.updateType = NodeUpdateType.FRAME;
  28492. }
  28493. getHash() {
  28494. return this.light.uuid;
  28495. }
  28496. /**
  28497. * Returns a node representing a direction vector which points from the current
  28498. * position in view space to the light's position in view space.
  28499. *
  28500. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  28501. * @return {Node<vec3>} The light vector node.
  28502. */
  28503. getLightVector( builder ) {
  28504. return lightViewPosition( this.light ).sub( builder.context.positionView || positionView );
  28505. }
  28506. /**
  28507. * Sets up the direct lighting for the analytic light node.
  28508. *
  28509. * @abstract
  28510. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  28511. * @return {Object|undefined} The direct light data (color and direction).
  28512. */
  28513. setupDirect( /*builder*/ ) { }
  28514. /**
  28515. * Sets up the direct rect area lighting for the analytic light node.
  28516. *
  28517. * @abstract
  28518. * @param {NodeBuilder} builder - The builder object used for setting up the light.
  28519. * @return {Object|undefined} The direct rect area light data.
  28520. */
  28521. setupDirectRectArea( /*builder*/ ) { }
  28522. /**
  28523. * Setups the shadow node for this light. The method exists so concrete light classes
  28524. * can setup different types of shadow nodes.
  28525. *
  28526. * @return {ShadowNode} The created shadow node.
  28527. */
  28528. setupShadowNode() {
  28529. return shadow( this.light );
  28530. }
  28531. /**
  28532. * Setups the shadow for this light. This method is only executed if the light
  28533. * cast shadows and the current build object receives shadows. It incorporates
  28534. * shadows into the lighting computation.
  28535. *
  28536. * @param {NodeBuilder} builder - The current node builder.
  28537. */
  28538. setupShadow( builder ) {
  28539. const { renderer } = builder;
  28540. if ( renderer.shadowMap.enabled === false ) return;
  28541. let shadowColorNode = this.shadowColorNode;
  28542. if ( shadowColorNode === null ) {
  28543. const customShadowNode = this.light.shadow.shadowNode;
  28544. let shadowNode;
  28545. if ( customShadowNode !== undefined ) {
  28546. shadowNode = nodeObject( customShadowNode );
  28547. } else {
  28548. shadowNode = this.setupShadowNode();
  28549. }
  28550. this.shadowNode = shadowNode;
  28551. this.shadowColorNode = shadowColorNode = this.colorNode.mul( shadowNode );
  28552. this.baseColorNode = this.colorNode;
  28553. }
  28554. //
  28555. this.colorNode = shadowColorNode;
  28556. }
  28557. /**
  28558. * Unlike most other nodes, lighting nodes do not return a output node in {@link Node#setup}.
  28559. * The main purpose of lighting nodes is to configure the current {@link LightingModel} and/or
  28560. * invocate the respective interface methods.
  28561. *
  28562. * @param {NodeBuilder} builder - The current node builder.
  28563. */
  28564. setup( builder ) {
  28565. this.colorNode = this.baseColorNode || this.colorNode;
  28566. if ( this.light.castShadow ) {
  28567. if ( builder.object.receiveShadow ) {
  28568. this.setupShadow( builder );
  28569. }
  28570. } else if ( this.shadowNode !== null ) {
  28571. this.shadowNode.dispose();
  28572. this.shadowNode = null;
  28573. this.shadowColorNode = null;
  28574. }
  28575. const directLightData = this.setupDirect( builder );
  28576. const directRectAreaLightData = this.setupDirectRectArea( builder );
  28577. if ( directLightData ) {
  28578. builder.lightsNode.setupDirectLight( builder, this, directLightData );
  28579. }
  28580. if ( directRectAreaLightData ) {
  28581. builder.lightsNode.setupDirectRectAreaLight( builder, this, directRectAreaLightData );
  28582. }
  28583. }
  28584. /**
  28585. * The update method is used to update light uniforms per frame.
  28586. * Potentially overwritten in concrete light nodes to update light
  28587. * specific uniforms.
  28588. *
  28589. * @param {NodeFrame} frame - A reference to the current node frame.
  28590. */
  28591. update( /*frame*/ ) {
  28592. const { light } = this;
  28593. this.color.copy( light.color ).multiplyScalar( light.intensity );
  28594. }
  28595. }
  28596. /**
  28597. * Represents a `discard` shader operation in TSL.
  28598. *
  28599. * @method
  28600. * @param {Object} inputs - The input parameter object.
  28601. * @param {Node<float>} inputs.lightDistance - The distance of the light's position to the current fragment position.
  28602. * @param {Node<float>} inputs.cutoffDistance - The light's cutoff distance.
  28603. * @param {Node<float>} inputs.decayExponent - The light's decay exponent.
  28604. * @return {Node<float>} The distance falloff.
  28605. */
  28606. const getDistanceAttenuation = /*@__PURE__*/ Fn( ( { lightDistance, cutoffDistance, decayExponent } ) => {
  28607. // based upon Frostbite 3 Moving to Physically-based Rendering
  28608. // page 32, equation 26: E[window1]
  28609. // https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf
  28610. const distanceFalloff = lightDistance.pow( decayExponent ).max( 0.01 ).reciprocal();
  28611. return cutoffDistance.greaterThan( 0 ).select(
  28612. distanceFalloff.mul( lightDistance.div( cutoffDistance ).pow4().oneMinus().clamp().pow2() ),
  28613. distanceFalloff
  28614. );
  28615. } ); // validated
  28616. const directPointLight = ( { color, lightVector, cutoffDistance, decayExponent } ) => {
  28617. const lightDirection = lightVector.normalize();
  28618. const lightDistance = lightVector.length();
  28619. const attenuation = getDistanceAttenuation( {
  28620. lightDistance,
  28621. cutoffDistance,
  28622. decayExponent
  28623. } );
  28624. const lightColor = color.mul( attenuation );
  28625. return { lightDirection, lightColor };
  28626. };
  28627. /**
  28628. * Module for representing point lights as nodes.
  28629. *
  28630. * @augments AnalyticLightNode
  28631. */
  28632. class PointLightNode extends AnalyticLightNode {
  28633. static get type() {
  28634. return 'PointLightNode';
  28635. }
  28636. /**
  28637. * Constructs a new point light node.
  28638. *
  28639. * @param {?PointLight} [light=null] - The point light source.
  28640. */
  28641. constructor( light = null ) {
  28642. super( light );
  28643. /**
  28644. * Uniform node representing the cutoff distance.
  28645. *
  28646. * @type {UniformNode<float>}
  28647. */
  28648. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  28649. /**
  28650. * Uniform node representing the decay exponent.
  28651. *
  28652. * @type {UniformNode<float>}
  28653. */
  28654. this.decayExponentNode = uniform( 2 ).setGroup( renderGroup );
  28655. }
  28656. /**
  28657. * Overwritten to updated point light specific uniforms.
  28658. *
  28659. * @param {NodeFrame} frame - A reference to the current node frame.
  28660. */
  28661. update( frame ) {
  28662. const { light } = this;
  28663. super.update( frame );
  28664. this.cutoffDistanceNode.value = light.distance;
  28665. this.decayExponentNode.value = light.decay;
  28666. }
  28667. /**
  28668. * Overwritten to setup point light specific shadow.
  28669. *
  28670. * @return {PointShadowNode}
  28671. */
  28672. setupShadowNode() {
  28673. return pointShadow( this.light );
  28674. }
  28675. setupDirect( builder ) {
  28676. return directPointLight( {
  28677. color: this.colorNode,
  28678. lightVector: this.getLightVector( builder ),
  28679. cutoffDistance: this.cutoffDistanceNode,
  28680. decayExponent: this.decayExponentNode
  28681. } );
  28682. }
  28683. }
  28684. /**
  28685. * Creates a 2x2 checkerboard pattern that can be used as procedural texture data.
  28686. *
  28687. * @tsl
  28688. * @function
  28689. * @param {Node<vec2>} coord - The uv coordinates.
  28690. * @return {Node<float>} The result data.
  28691. */
  28692. const checker = /*@__PURE__*/ Fn( ( [ coord = uv() ] ) => {
  28693. const uv = coord.mul( 2.0 );
  28694. const cx = uv.x.floor();
  28695. const cy = uv.y.floor();
  28696. const result = cx.add( cy ).mod( 2.0 );
  28697. return result.sign();
  28698. } );
  28699. /**
  28700. * Generates a circle based on the uv coordinates.
  28701. *
  28702. * @tsl
  28703. * @function
  28704. * @param {Node<vec2>} coord - The uv to generate the circle.
  28705. * @return {Node<float>} The circle shape.
  28706. */
  28707. const shapeCircle = Fn( ( [ coord = uv() ], { renderer, material } ) => {
  28708. const len2 = lengthSq( coord.mul( 2 ).sub( 1 ) );
  28709. let alpha;
  28710. if ( material.alphaToCoverage && renderer.samples > 1 ) {
  28711. const dlen = float( len2.fwidth() ).toVar();
  28712. alpha = smoothstep( dlen.oneMinus(), dlen.add( 1 ), len2 ).oneMinus();
  28713. } else {
  28714. alpha = select( len2.greaterThan( 1.0 ), 0, 1 );
  28715. }
  28716. return alpha;
  28717. } );
  28718. // Three.js Transpiler
  28719. // https://raw.githubusercontent.com/AcademySoftwareFoundation/MaterialX/main/libraries/stdlib/genglsl/lib/mx_noise.glsl
  28720. const mx_select = /*@__PURE__*/ Fn( ( [ b_immutable, t_immutable, f_immutable ] ) => {
  28721. const f = float( f_immutable ).toVar();
  28722. const t = float( t_immutable ).toVar();
  28723. const b = bool( b_immutable ).toVar();
  28724. return select( b, t, f );
  28725. } ).setLayout( {
  28726. name: 'mx_select',
  28727. type: 'float',
  28728. inputs: [
  28729. { name: 'b', type: 'bool' },
  28730. { name: 't', type: 'float' },
  28731. { name: 'f', type: 'float' }
  28732. ]
  28733. } );
  28734. const mx_negate_if = /*@__PURE__*/ Fn( ( [ val_immutable, b_immutable ] ) => {
  28735. const b = bool( b_immutable ).toVar();
  28736. const val = float( val_immutable ).toVar();
  28737. return select( b, val.negate(), val );
  28738. } ).setLayout( {
  28739. name: 'mx_negate_if',
  28740. type: 'float',
  28741. inputs: [
  28742. { name: 'val', type: 'float' },
  28743. { name: 'b', type: 'bool' }
  28744. ]
  28745. } );
  28746. const mx_floor = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  28747. const x = float( x_immutable ).toVar();
  28748. return int( floor( x ) );
  28749. } ).setLayout( {
  28750. name: 'mx_floor',
  28751. type: 'int',
  28752. inputs: [
  28753. { name: 'x', type: 'float' }
  28754. ]
  28755. } );
  28756. const mx_floorfrac = /*@__PURE__*/ Fn( ( [ x_immutable, i ] ) => {
  28757. const x = float( x_immutable ).toVar();
  28758. i.assign( mx_floor( x ) );
  28759. return x.sub( float( i ) );
  28760. } );
  28761. const mx_bilerp_0 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  28762. const t = float( t_immutable ).toVar();
  28763. const s = float( s_immutable ).toVar();
  28764. const v3 = float( v3_immutable ).toVar();
  28765. const v2 = float( v2_immutable ).toVar();
  28766. const v1 = float( v1_immutable ).toVar();
  28767. const v0 = float( v0_immutable ).toVar();
  28768. const s1 = float( sub( 1.0, s ) ).toVar();
  28769. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  28770. } ).setLayout( {
  28771. name: 'mx_bilerp_0',
  28772. type: 'float',
  28773. inputs: [
  28774. { name: 'v0', type: 'float' },
  28775. { name: 'v1', type: 'float' },
  28776. { name: 'v2', type: 'float' },
  28777. { name: 'v3', type: 'float' },
  28778. { name: 's', type: 'float' },
  28779. { name: 't', type: 'float' }
  28780. ]
  28781. } );
  28782. const mx_bilerp_1 = /*@__PURE__*/ Fn( ( [ v0_immutable, v1_immutable, v2_immutable, v3_immutable, s_immutable, t_immutable ] ) => {
  28783. const t = float( t_immutable ).toVar();
  28784. const s = float( s_immutable ).toVar();
  28785. const v3 = vec3( v3_immutable ).toVar();
  28786. const v2 = vec3( v2_immutable ).toVar();
  28787. const v1 = vec3( v1_immutable ).toVar();
  28788. const v0 = vec3( v0_immutable ).toVar();
  28789. const s1 = float( sub( 1.0, s ) ).toVar();
  28790. return sub( 1.0, t ).mul( v0.mul( s1 ).add( v1.mul( s ) ) ).add( t.mul( v2.mul( s1 ).add( v3.mul( s ) ) ) );
  28791. } ).setLayout( {
  28792. name: 'mx_bilerp_1',
  28793. type: 'vec3',
  28794. inputs: [
  28795. { name: 'v0', type: 'vec3' },
  28796. { name: 'v1', type: 'vec3' },
  28797. { name: 'v2', type: 'vec3' },
  28798. { name: 'v3', type: 'vec3' },
  28799. { name: 's', type: 'float' },
  28800. { name: 't', type: 'float' }
  28801. ]
  28802. } );
  28803. const mx_bilerp = /*@__PURE__*/ overloadingFn( [ mx_bilerp_0, mx_bilerp_1 ] );
  28804. 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 ] ) => {
  28805. const r = float( r_immutable ).toVar();
  28806. const t = float( t_immutable ).toVar();
  28807. const s = float( s_immutable ).toVar();
  28808. const v7 = float( v7_immutable ).toVar();
  28809. const v6 = float( v6_immutable ).toVar();
  28810. const v5 = float( v5_immutable ).toVar();
  28811. const v4 = float( v4_immutable ).toVar();
  28812. const v3 = float( v3_immutable ).toVar();
  28813. const v2 = float( v2_immutable ).toVar();
  28814. const v1 = float( v1_immutable ).toVar();
  28815. const v0 = float( v0_immutable ).toVar();
  28816. const s1 = float( sub( 1.0, s ) ).toVar();
  28817. const t1 = float( sub( 1.0, t ) ).toVar();
  28818. const r1 = float( sub( 1.0, r ) ).toVar();
  28819. 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 ) ) ) ) ) );
  28820. } ).setLayout( {
  28821. name: 'mx_trilerp_0',
  28822. type: 'float',
  28823. inputs: [
  28824. { name: 'v0', type: 'float' },
  28825. { name: 'v1', type: 'float' },
  28826. { name: 'v2', type: 'float' },
  28827. { name: 'v3', type: 'float' },
  28828. { name: 'v4', type: 'float' },
  28829. { name: 'v5', type: 'float' },
  28830. { name: 'v6', type: 'float' },
  28831. { name: 'v7', type: 'float' },
  28832. { name: 's', type: 'float' },
  28833. { name: 't', type: 'float' },
  28834. { name: 'r', type: 'float' }
  28835. ]
  28836. } );
  28837. 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 ] ) => {
  28838. const r = float( r_immutable ).toVar();
  28839. const t = float( t_immutable ).toVar();
  28840. const s = float( s_immutable ).toVar();
  28841. const v7 = vec3( v7_immutable ).toVar();
  28842. const v6 = vec3( v6_immutable ).toVar();
  28843. const v5 = vec3( v5_immutable ).toVar();
  28844. const v4 = vec3( v4_immutable ).toVar();
  28845. const v3 = vec3( v3_immutable ).toVar();
  28846. const v2 = vec3( v2_immutable ).toVar();
  28847. const v1 = vec3( v1_immutable ).toVar();
  28848. const v0 = vec3( v0_immutable ).toVar();
  28849. const s1 = float( sub( 1.0, s ) ).toVar();
  28850. const t1 = float( sub( 1.0, t ) ).toVar();
  28851. const r1 = float( sub( 1.0, r ) ).toVar();
  28852. 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 ) ) ) ) ) );
  28853. } ).setLayout( {
  28854. name: 'mx_trilerp_1',
  28855. type: 'vec3',
  28856. inputs: [
  28857. { name: 'v0', type: 'vec3' },
  28858. { name: 'v1', type: 'vec3' },
  28859. { name: 'v2', type: 'vec3' },
  28860. { name: 'v3', type: 'vec3' },
  28861. { name: 'v4', type: 'vec3' },
  28862. { name: 'v5', type: 'vec3' },
  28863. { name: 'v6', type: 'vec3' },
  28864. { name: 'v7', type: 'vec3' },
  28865. { name: 's', type: 'float' },
  28866. { name: 't', type: 'float' },
  28867. { name: 'r', type: 'float' }
  28868. ]
  28869. } );
  28870. const mx_trilerp = /*@__PURE__*/ overloadingFn( [ mx_trilerp_0, mx_trilerp_1 ] );
  28871. const mx_gradient_float_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  28872. const y = float( y_immutable ).toVar();
  28873. const x = float( x_immutable ).toVar();
  28874. const hash = uint( hash_immutable ).toVar();
  28875. const h = uint( hash.bitAnd( uint( 7 ) ) ).toVar();
  28876. const u = float( mx_select( h.lessThan( uint( 4 ) ), x, y ) ).toVar();
  28877. const v = float( mul( 2.0, mx_select( h.lessThan( uint( 4 ) ), y, x ) ) ).toVar();
  28878. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  28879. } ).setLayout( {
  28880. name: 'mx_gradient_float_0',
  28881. type: 'float',
  28882. inputs: [
  28883. { name: 'hash', type: 'uint' },
  28884. { name: 'x', type: 'float' },
  28885. { name: 'y', type: 'float' }
  28886. ]
  28887. } );
  28888. const mx_gradient_float_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  28889. const z = float( z_immutable ).toVar();
  28890. const y = float( y_immutable ).toVar();
  28891. const x = float( x_immutable ).toVar();
  28892. const hash = uint( hash_immutable ).toVar();
  28893. const h = uint( hash.bitAnd( uint( 15 ) ) ).toVar();
  28894. const u = float( mx_select( h.lessThan( uint( 8 ) ), x, y ) ).toVar();
  28895. const v = float( mx_select( h.lessThan( uint( 4 ) ), y, mx_select( h.equal( uint( 12 ) ).or( h.equal( uint( 14 ) ) ), x, z ) ) ).toVar();
  28896. return mx_negate_if( u, bool( h.bitAnd( uint( 1 ) ) ) ).add( mx_negate_if( v, bool( h.bitAnd( uint( 2 ) ) ) ) );
  28897. } ).setLayout( {
  28898. name: 'mx_gradient_float_1',
  28899. type: 'float',
  28900. inputs: [
  28901. { name: 'hash', type: 'uint' },
  28902. { name: 'x', type: 'float' },
  28903. { name: 'y', type: 'float' },
  28904. { name: 'z', type: 'float' }
  28905. ]
  28906. } );
  28907. const mx_gradient_float = /*@__PURE__*/ overloadingFn( [ mx_gradient_float_0, mx_gradient_float_1 ] );
  28908. const mx_gradient_vec3_0 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable ] ) => {
  28909. const y = float( y_immutable ).toVar();
  28910. const x = float( x_immutable ).toVar();
  28911. const hash = uvec3( hash_immutable ).toVar();
  28912. return vec3( mx_gradient_float( hash.x, x, y ), mx_gradient_float( hash.y, x, y ), mx_gradient_float( hash.z, x, y ) );
  28913. } ).setLayout( {
  28914. name: 'mx_gradient_vec3_0',
  28915. type: 'vec3',
  28916. inputs: [
  28917. { name: 'hash', type: 'uvec3' },
  28918. { name: 'x', type: 'float' },
  28919. { name: 'y', type: 'float' }
  28920. ]
  28921. } );
  28922. const mx_gradient_vec3_1 = /*@__PURE__*/ Fn( ( [ hash_immutable, x_immutable, y_immutable, z_immutable ] ) => {
  28923. const z = float( z_immutable ).toVar();
  28924. const y = float( y_immutable ).toVar();
  28925. const x = float( x_immutable ).toVar();
  28926. const hash = uvec3( hash_immutable ).toVar();
  28927. 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 ) );
  28928. } ).setLayout( {
  28929. name: 'mx_gradient_vec3_1',
  28930. type: 'vec3',
  28931. inputs: [
  28932. { name: 'hash', type: 'uvec3' },
  28933. { name: 'x', type: 'float' },
  28934. { name: 'y', type: 'float' },
  28935. { name: 'z', type: 'float' }
  28936. ]
  28937. } );
  28938. const mx_gradient_vec3 = /*@__PURE__*/ overloadingFn( [ mx_gradient_vec3_0, mx_gradient_vec3_1 ] );
  28939. const mx_gradient_scale2d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28940. const v = float( v_immutable ).toVar();
  28941. return mul( 0.6616, v );
  28942. } ).setLayout( {
  28943. name: 'mx_gradient_scale2d_0',
  28944. type: 'float',
  28945. inputs: [
  28946. { name: 'v', type: 'float' }
  28947. ]
  28948. } );
  28949. const mx_gradient_scale3d_0 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28950. const v = float( v_immutable ).toVar();
  28951. return mul( 0.9820, v );
  28952. } ).setLayout( {
  28953. name: 'mx_gradient_scale3d_0',
  28954. type: 'float',
  28955. inputs: [
  28956. { name: 'v', type: 'float' }
  28957. ]
  28958. } );
  28959. const mx_gradient_scale2d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28960. const v = vec3( v_immutable ).toVar();
  28961. return mul( 0.6616, v );
  28962. } ).setLayout( {
  28963. name: 'mx_gradient_scale2d_1',
  28964. type: 'vec3',
  28965. inputs: [
  28966. { name: 'v', type: 'vec3' }
  28967. ]
  28968. } );
  28969. const mx_gradient_scale2d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale2d_0, mx_gradient_scale2d_1 ] );
  28970. const mx_gradient_scale3d_1 = /*@__PURE__*/ Fn( ( [ v_immutable ] ) => {
  28971. const v = vec3( v_immutable ).toVar();
  28972. return mul( 0.9820, v );
  28973. } ).setLayout( {
  28974. name: 'mx_gradient_scale3d_1',
  28975. type: 'vec3',
  28976. inputs: [
  28977. { name: 'v', type: 'vec3' }
  28978. ]
  28979. } );
  28980. const mx_gradient_scale3d = /*@__PURE__*/ overloadingFn( [ mx_gradient_scale3d_0, mx_gradient_scale3d_1 ] );
  28981. const mx_rotl32 = /*@__PURE__*/ Fn( ( [ x_immutable, k_immutable ] ) => {
  28982. const k = int( k_immutable ).toVar();
  28983. const x = uint( x_immutable ).toVar();
  28984. return x.shiftLeft( k ).bitOr( x.shiftRight( int( 32 ).sub( k ) ) );
  28985. } ).setLayout( {
  28986. name: 'mx_rotl32',
  28987. type: 'uint',
  28988. inputs: [
  28989. { name: 'x', type: 'uint' },
  28990. { name: 'k', type: 'int' }
  28991. ]
  28992. } );
  28993. const mx_bjmix = /*@__PURE__*/ Fn( ( [ a, b, c ] ) => {
  28994. a.subAssign( c );
  28995. a.bitXorAssign( mx_rotl32( c, int( 4 ) ) );
  28996. c.addAssign( b );
  28997. b.subAssign( a );
  28998. b.bitXorAssign( mx_rotl32( a, int( 6 ) ) );
  28999. a.addAssign( c );
  29000. c.subAssign( b );
  29001. c.bitXorAssign( mx_rotl32( b, int( 8 ) ) );
  29002. b.addAssign( a );
  29003. a.subAssign( c );
  29004. a.bitXorAssign( mx_rotl32( c, int( 16 ) ) );
  29005. c.addAssign( b );
  29006. b.subAssign( a );
  29007. b.bitXorAssign( mx_rotl32( a, int( 19 ) ) );
  29008. a.addAssign( c );
  29009. c.subAssign( b );
  29010. c.bitXorAssign( mx_rotl32( b, int( 4 ) ) );
  29011. b.addAssign( a );
  29012. } );
  29013. const mx_bjfinal = /*@__PURE__*/ Fn( ( [ a_immutable, b_immutable, c_immutable ] ) => {
  29014. const c = uint( c_immutable ).toVar();
  29015. const b = uint( b_immutable ).toVar();
  29016. const a = uint( a_immutable ).toVar();
  29017. c.bitXorAssign( b );
  29018. c.subAssign( mx_rotl32( b, int( 14 ) ) );
  29019. a.bitXorAssign( c );
  29020. a.subAssign( mx_rotl32( c, int( 11 ) ) );
  29021. b.bitXorAssign( a );
  29022. b.subAssign( mx_rotl32( a, int( 25 ) ) );
  29023. c.bitXorAssign( b );
  29024. c.subAssign( mx_rotl32( b, int( 16 ) ) );
  29025. a.bitXorAssign( c );
  29026. a.subAssign( mx_rotl32( c, int( 4 ) ) );
  29027. b.bitXorAssign( a );
  29028. b.subAssign( mx_rotl32( a, int( 14 ) ) );
  29029. c.bitXorAssign( b );
  29030. c.subAssign( mx_rotl32( b, int( 24 ) ) );
  29031. return c;
  29032. } ).setLayout( {
  29033. name: 'mx_bjfinal',
  29034. type: 'uint',
  29035. inputs: [
  29036. { name: 'a', type: 'uint' },
  29037. { name: 'b', type: 'uint' },
  29038. { name: 'c', type: 'uint' }
  29039. ]
  29040. } );
  29041. const mx_bits_to_01 = /*@__PURE__*/ Fn( ( [ bits_immutable ] ) => {
  29042. const bits = uint( bits_immutable ).toVar();
  29043. return float( bits ).div( float( uint( int( 0xffffffff ) ) ) );
  29044. } ).setLayout( {
  29045. name: 'mx_bits_to_01',
  29046. type: 'float',
  29047. inputs: [
  29048. { name: 'bits', type: 'uint' }
  29049. ]
  29050. } );
  29051. const mx_fade = /*@__PURE__*/ Fn( ( [ t_immutable ] ) => {
  29052. const t = float( t_immutable ).toVar();
  29053. return t.mul( t ).mul( t ).mul( t.mul( t.mul( 6.0 ).sub( 15.0 ) ).add( 10.0 ) );
  29054. } ).setLayout( {
  29055. name: 'mx_fade',
  29056. type: 'float',
  29057. inputs: [
  29058. { name: 't', type: 'float' }
  29059. ]
  29060. } );
  29061. const mx_hash_int_0 = /*@__PURE__*/ Fn( ( [ x_immutable ] ) => {
  29062. const x = int( x_immutable ).toVar();
  29063. const len = uint( uint( 1 ) ).toVar();
  29064. const seed = uint( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ).toVar();
  29065. return mx_bjfinal( seed.add( uint( x ) ), seed, seed );
  29066. } ).setLayout( {
  29067. name: 'mx_hash_int_0',
  29068. type: 'uint',
  29069. inputs: [
  29070. { name: 'x', type: 'int' }
  29071. ]
  29072. } );
  29073. const mx_hash_int_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  29074. const y = int( y_immutable ).toVar();
  29075. const x = int( x_immutable ).toVar();
  29076. const len = uint( uint( 2 ) ).toVar();
  29077. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29078. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29079. a.addAssign( uint( x ) );
  29080. b.addAssign( uint( y ) );
  29081. return mx_bjfinal( a, b, c );
  29082. } ).setLayout( {
  29083. name: 'mx_hash_int_1',
  29084. type: 'uint',
  29085. inputs: [
  29086. { name: 'x', type: 'int' },
  29087. { name: 'y', type: 'int' }
  29088. ]
  29089. } );
  29090. const mx_hash_int_2 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  29091. const z = int( z_immutable ).toVar();
  29092. const y = int( y_immutable ).toVar();
  29093. const x = int( x_immutable ).toVar();
  29094. const len = uint( uint( 3 ) ).toVar();
  29095. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29096. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29097. a.addAssign( uint( x ) );
  29098. b.addAssign( uint( y ) );
  29099. c.addAssign( uint( z ) );
  29100. return mx_bjfinal( a, b, c );
  29101. } ).setLayout( {
  29102. name: 'mx_hash_int_2',
  29103. type: 'uint',
  29104. inputs: [
  29105. { name: 'x', type: 'int' },
  29106. { name: 'y', type: 'int' },
  29107. { name: 'z', type: 'int' }
  29108. ]
  29109. } );
  29110. const mx_hash_int_3 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable ] ) => {
  29111. const xx = int( xx_immutable ).toVar();
  29112. const z = int( z_immutable ).toVar();
  29113. const y = int( y_immutable ).toVar();
  29114. const x = int( x_immutable ).toVar();
  29115. const len = uint( uint( 4 ) ).toVar();
  29116. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29117. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29118. a.addAssign( uint( x ) );
  29119. b.addAssign( uint( y ) );
  29120. c.addAssign( uint( z ) );
  29121. mx_bjmix( a, b, c );
  29122. a.addAssign( uint( xx ) );
  29123. return mx_bjfinal( a, b, c );
  29124. } ).setLayout( {
  29125. name: 'mx_hash_int_3',
  29126. type: 'uint',
  29127. inputs: [
  29128. { name: 'x', type: 'int' },
  29129. { name: 'y', type: 'int' },
  29130. { name: 'z', type: 'int' },
  29131. { name: 'xx', type: 'int' }
  29132. ]
  29133. } );
  29134. const mx_hash_int_4 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable, xx_immutable, yy_immutable ] ) => {
  29135. const yy = int( yy_immutable ).toVar();
  29136. const xx = int( xx_immutable ).toVar();
  29137. const z = int( z_immutable ).toVar();
  29138. const y = int( y_immutable ).toVar();
  29139. const x = int( x_immutable ).toVar();
  29140. const len = uint( uint( 5 ) ).toVar();
  29141. const a = uint().toVar(), b = uint().toVar(), c = uint().toVar();
  29142. a.assign( b.assign( c.assign( uint( int( 0xdeadbeef ) ).add( len.shiftLeft( uint( 2 ) ) ).add( uint( 13 ) ) ) ) );
  29143. a.addAssign( uint( x ) );
  29144. b.addAssign( uint( y ) );
  29145. c.addAssign( uint( z ) );
  29146. mx_bjmix( a, b, c );
  29147. a.addAssign( uint( xx ) );
  29148. b.addAssign( uint( yy ) );
  29149. return mx_bjfinal( a, b, c );
  29150. } ).setLayout( {
  29151. name: 'mx_hash_int_4',
  29152. type: 'uint',
  29153. inputs: [
  29154. { name: 'x', type: 'int' },
  29155. { name: 'y', type: 'int' },
  29156. { name: 'z', type: 'int' },
  29157. { name: 'xx', type: 'int' },
  29158. { name: 'yy', type: 'int' }
  29159. ]
  29160. } );
  29161. 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 ] );
  29162. const mx_hash_vec3_0 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable ] ) => {
  29163. const y = int( y_immutable ).toVar();
  29164. const x = int( x_immutable ).toVar();
  29165. const h = uint( mx_hash_int( x, y ) ).toVar();
  29166. const result = uvec3().toVar();
  29167. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  29168. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  29169. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  29170. return result;
  29171. } ).setLayout( {
  29172. name: 'mx_hash_vec3_0',
  29173. type: 'uvec3',
  29174. inputs: [
  29175. { name: 'x', type: 'int' },
  29176. { name: 'y', type: 'int' }
  29177. ]
  29178. } );
  29179. const mx_hash_vec3_1 = /*@__PURE__*/ Fn( ( [ x_immutable, y_immutable, z_immutable ] ) => {
  29180. const z = int( z_immutable ).toVar();
  29181. const y = int( y_immutable ).toVar();
  29182. const x = int( x_immutable ).toVar();
  29183. const h = uint( mx_hash_int( x, y, z ) ).toVar();
  29184. const result = uvec3().toVar();
  29185. result.x.assign( h.bitAnd( int( 0xFF ) ) );
  29186. result.y.assign( h.shiftRight( int( 8 ) ).bitAnd( int( 0xFF ) ) );
  29187. result.z.assign( h.shiftRight( int( 16 ) ).bitAnd( int( 0xFF ) ) );
  29188. return result;
  29189. } ).setLayout( {
  29190. name: 'mx_hash_vec3_1',
  29191. type: 'uvec3',
  29192. inputs: [
  29193. { name: 'x', type: 'int' },
  29194. { name: 'y', type: 'int' },
  29195. { name: 'z', type: 'int' }
  29196. ]
  29197. } );
  29198. const mx_hash_vec3 = /*@__PURE__*/ overloadingFn( [ mx_hash_vec3_0, mx_hash_vec3_1 ] );
  29199. const mx_perlin_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29200. const p = vec2( p_immutable ).toVar();
  29201. const X = int().toVar(), Y = int().toVar();
  29202. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29203. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29204. const u = float( mx_fade( fx ) ).toVar();
  29205. const v = float( mx_fade( fy ) ).toVar();
  29206. 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();
  29207. return mx_gradient_scale2d( result );
  29208. } ).setLayout( {
  29209. name: 'mx_perlin_noise_float_0',
  29210. type: 'float',
  29211. inputs: [
  29212. { name: 'p', type: 'vec2' }
  29213. ]
  29214. } );
  29215. const mx_perlin_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29216. const p = vec3( p_immutable ).toVar();
  29217. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29218. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29219. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29220. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  29221. const u = float( mx_fade( fx ) ).toVar();
  29222. const v = float( mx_fade( fy ) ).toVar();
  29223. const w = float( mx_fade( fz ) ).toVar();
  29224. 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();
  29225. return mx_gradient_scale3d( result );
  29226. } ).setLayout( {
  29227. name: 'mx_perlin_noise_float_1',
  29228. type: 'float',
  29229. inputs: [
  29230. { name: 'p', type: 'vec3' }
  29231. ]
  29232. } );
  29233. const mx_perlin_noise_float = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_float_0, mx_perlin_noise_float_1 ] );
  29234. const mx_perlin_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29235. const p = vec2( p_immutable ).toVar();
  29236. const X = int().toVar(), Y = int().toVar();
  29237. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29238. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29239. const u = float( mx_fade( fx ) ).toVar();
  29240. const v = float( mx_fade( fy ) ).toVar();
  29241. 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();
  29242. return mx_gradient_scale2d( result );
  29243. } ).setLayout( {
  29244. name: 'mx_perlin_noise_vec3_0',
  29245. type: 'vec3',
  29246. inputs: [
  29247. { name: 'p', type: 'vec2' }
  29248. ]
  29249. } );
  29250. const mx_perlin_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29251. const p = vec3( p_immutable ).toVar();
  29252. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29253. const fx = float( mx_floorfrac( p.x, X ) ).toVar();
  29254. const fy = float( mx_floorfrac( p.y, Y ) ).toVar();
  29255. const fz = float( mx_floorfrac( p.z, Z ) ).toVar();
  29256. const u = float( mx_fade( fx ) ).toVar();
  29257. const v = float( mx_fade( fy ) ).toVar();
  29258. const w = float( mx_fade( fz ) ).toVar();
  29259. 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();
  29260. return mx_gradient_scale3d( result );
  29261. } ).setLayout( {
  29262. name: 'mx_perlin_noise_vec3_1',
  29263. type: 'vec3',
  29264. inputs: [
  29265. { name: 'p', type: 'vec3' }
  29266. ]
  29267. } );
  29268. const mx_perlin_noise_vec3 = /*@__PURE__*/ overloadingFn( [ mx_perlin_noise_vec3_0, mx_perlin_noise_vec3_1 ] );
  29269. const mx_cell_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29270. const p = float( p_immutable ).toVar();
  29271. const ix = int( mx_floor( p ) ).toVar();
  29272. return mx_bits_to_01( mx_hash_int( ix ) );
  29273. } ).setLayout( {
  29274. name: 'mx_cell_noise_float_0',
  29275. type: 'float',
  29276. inputs: [
  29277. { name: 'p', type: 'float' }
  29278. ]
  29279. } );
  29280. const mx_cell_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29281. const p = vec2( p_immutable ).toVar();
  29282. const ix = int( mx_floor( p.x ) ).toVar();
  29283. const iy = int( mx_floor( p.y ) ).toVar();
  29284. return mx_bits_to_01( mx_hash_int( ix, iy ) );
  29285. } ).setLayout( {
  29286. name: 'mx_cell_noise_float_1',
  29287. type: 'float',
  29288. inputs: [
  29289. { name: 'p', type: 'vec2' }
  29290. ]
  29291. } );
  29292. const mx_cell_noise_float_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29293. const p = vec3( p_immutable ).toVar();
  29294. const ix = int( mx_floor( p.x ) ).toVar();
  29295. const iy = int( mx_floor( p.y ) ).toVar();
  29296. const iz = int( mx_floor( p.z ) ).toVar();
  29297. return mx_bits_to_01( mx_hash_int( ix, iy, iz ) );
  29298. } ).setLayout( {
  29299. name: 'mx_cell_noise_float_2',
  29300. type: 'float',
  29301. inputs: [
  29302. { name: 'p', type: 'vec3' }
  29303. ]
  29304. } );
  29305. const mx_cell_noise_float_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29306. const p = vec4( p_immutable ).toVar();
  29307. const ix = int( mx_floor( p.x ) ).toVar();
  29308. const iy = int( mx_floor( p.y ) ).toVar();
  29309. const iz = int( mx_floor( p.z ) ).toVar();
  29310. const iw = int( mx_floor( p.w ) ).toVar();
  29311. return mx_bits_to_01( mx_hash_int( ix, iy, iz, iw ) );
  29312. } ).setLayout( {
  29313. name: 'mx_cell_noise_float_3',
  29314. type: 'float',
  29315. inputs: [
  29316. { name: 'p', type: 'vec4' }
  29317. ]
  29318. } );
  29319. 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 ] );
  29320. const mx_cell_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29321. const p = float( p_immutable ).toVar();
  29322. const ix = int( mx_floor( p ) ).toVar();
  29323. 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 ) ) ) );
  29324. } ).setLayout( {
  29325. name: 'mx_cell_noise_vec3_0',
  29326. type: 'vec3',
  29327. inputs: [
  29328. { name: 'p', type: 'float' }
  29329. ]
  29330. } );
  29331. const mx_cell_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29332. const p = vec2( p_immutable ).toVar();
  29333. const ix = int( mx_floor( p.x ) ).toVar();
  29334. const iy = int( mx_floor( p.y ) ).toVar();
  29335. 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 ) ) ) );
  29336. } ).setLayout( {
  29337. name: 'mx_cell_noise_vec3_1',
  29338. type: 'vec3',
  29339. inputs: [
  29340. { name: 'p', type: 'vec2' }
  29341. ]
  29342. } );
  29343. const mx_cell_noise_vec3_2 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29344. const p = vec3( p_immutable ).toVar();
  29345. const ix = int( mx_floor( p.x ) ).toVar();
  29346. const iy = int( mx_floor( p.y ) ).toVar();
  29347. const iz = int( mx_floor( p.z ) ).toVar();
  29348. 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 ) ) ) );
  29349. } ).setLayout( {
  29350. name: 'mx_cell_noise_vec3_2',
  29351. type: 'vec3',
  29352. inputs: [
  29353. { name: 'p', type: 'vec3' }
  29354. ]
  29355. } );
  29356. const mx_cell_noise_vec3_3 = /*@__PURE__*/ Fn( ( [ p_immutable ] ) => {
  29357. const p = vec4( p_immutable ).toVar();
  29358. const ix = int( mx_floor( p.x ) ).toVar();
  29359. const iy = int( mx_floor( p.y ) ).toVar();
  29360. const iz = int( mx_floor( p.z ) ).toVar();
  29361. const iw = int( mx_floor( p.w ) ).toVar();
  29362. 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 ) ) ) );
  29363. } ).setLayout( {
  29364. name: 'mx_cell_noise_vec3_3',
  29365. type: 'vec3',
  29366. inputs: [
  29367. { name: 'p', type: 'vec4' }
  29368. ]
  29369. } );
  29370. 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 ] );
  29371. const mx_fractal_noise_float$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29372. const diminish = float( diminish_immutable ).toVar();
  29373. const lacunarity = float( lacunarity_immutable ).toVar();
  29374. const octaves = int( octaves_immutable ).toVar();
  29375. const p = vec3( p_immutable ).toVar();
  29376. const result = float( 0.0 ).toVar();
  29377. const amplitude = float( 1.0 ).toVar();
  29378. Loop( octaves, () => {
  29379. result.addAssign( amplitude.mul( mx_perlin_noise_float( p ) ) );
  29380. amplitude.mulAssign( diminish );
  29381. p.mulAssign( lacunarity );
  29382. } );
  29383. return result;
  29384. } ).setLayout( {
  29385. name: 'mx_fractal_noise_float',
  29386. type: 'float',
  29387. inputs: [
  29388. { name: 'p', type: 'vec3' },
  29389. { name: 'octaves', type: 'int' },
  29390. { name: 'lacunarity', type: 'float' },
  29391. { name: 'diminish', type: 'float' }
  29392. ]
  29393. } );
  29394. const mx_fractal_noise_vec3$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29395. const diminish = float( diminish_immutable ).toVar();
  29396. const lacunarity = float( lacunarity_immutable ).toVar();
  29397. const octaves = int( octaves_immutable ).toVar();
  29398. const p = vec3( p_immutable ).toVar();
  29399. const result = vec3( 0.0 ).toVar();
  29400. const amplitude = float( 1.0 ).toVar();
  29401. Loop( octaves, () => {
  29402. result.addAssign( amplitude.mul( mx_perlin_noise_vec3( p ) ) );
  29403. amplitude.mulAssign( diminish );
  29404. p.mulAssign( lacunarity );
  29405. } );
  29406. return result;
  29407. } ).setLayout( {
  29408. name: 'mx_fractal_noise_vec3',
  29409. type: 'vec3',
  29410. inputs: [
  29411. { name: 'p', type: 'vec3' },
  29412. { name: 'octaves', type: 'int' },
  29413. { name: 'lacunarity', type: 'float' },
  29414. { name: 'diminish', type: 'float' }
  29415. ]
  29416. } );
  29417. const mx_fractal_noise_vec2$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29418. const diminish = float( diminish_immutable ).toVar();
  29419. const lacunarity = float( lacunarity_immutable ).toVar();
  29420. const octaves = int( octaves_immutable ).toVar();
  29421. const p = vec3( p_immutable ).toVar();
  29422. 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 ) );
  29423. } ).setLayout( {
  29424. name: 'mx_fractal_noise_vec2',
  29425. type: 'vec2',
  29426. inputs: [
  29427. { name: 'p', type: 'vec3' },
  29428. { name: 'octaves', type: 'int' },
  29429. { name: 'lacunarity', type: 'float' },
  29430. { name: 'diminish', type: 'float' }
  29431. ]
  29432. } );
  29433. const mx_fractal_noise_vec4$1 = /*@__PURE__*/ Fn( ( [ p_immutable, octaves_immutable, lacunarity_immutable, diminish_immutable ] ) => {
  29434. const diminish = float( diminish_immutable ).toVar();
  29435. const lacunarity = float( lacunarity_immutable ).toVar();
  29436. const octaves = int( octaves_immutable ).toVar();
  29437. const p = vec3( p_immutable ).toVar();
  29438. const c = vec3( mx_fractal_noise_vec3$1( p, octaves, lacunarity, diminish ) ).toVar();
  29439. const f = float( mx_fractal_noise_float$1( p.add( vec3( int( 19 ), int( 193 ), int( 17 ) ) ), octaves, lacunarity, diminish ) ).toVar();
  29440. return vec4( c, f );
  29441. } ).setLayout( {
  29442. name: 'mx_fractal_noise_vec4',
  29443. type: 'vec4',
  29444. inputs: [
  29445. { name: 'p', type: 'vec3' },
  29446. { name: 'octaves', type: 'int' },
  29447. { name: 'lacunarity', type: 'float' },
  29448. { name: 'diminish', type: 'float' }
  29449. ]
  29450. } );
  29451. const mx_worley_distance_0 = /*@__PURE__*/ Fn( ( [ p_immutable, x_immutable, y_immutable, xoff_immutable, yoff_immutable, jitter_immutable, metric_immutable ] ) => {
  29452. const metric = int( metric_immutable ).toVar();
  29453. const jitter = float( jitter_immutable ).toVar();
  29454. const yoff = int( yoff_immutable ).toVar();
  29455. const xoff = int( xoff_immutable ).toVar();
  29456. const y = int( y_immutable ).toVar();
  29457. const x = int( x_immutable ).toVar();
  29458. const p = vec2( p_immutable ).toVar();
  29459. const tmp = vec3( mx_cell_noise_vec3( vec2( x.add( xoff ), y.add( yoff ) ) ) ).toVar();
  29460. const off = vec2( tmp.x, tmp.y ).toVar();
  29461. off.subAssign( 0.5 );
  29462. off.mulAssign( jitter );
  29463. off.addAssign( 0.5 );
  29464. const cellpos = vec2( vec2( float( x ), float( y ) ).add( off ) ).toVar();
  29465. const diff = vec2( cellpos.sub( p ) ).toVar();
  29466. If( metric.equal( int( 2 ) ), () => {
  29467. return abs( diff.x ).add( abs( diff.y ) );
  29468. } );
  29469. If( metric.equal( int( 3 ) ), () => {
  29470. return max$1( abs( diff.x ), abs( diff.y ) );
  29471. } );
  29472. return dot( diff, diff );
  29473. } ).setLayout( {
  29474. name: 'mx_worley_distance_0',
  29475. type: 'float',
  29476. inputs: [
  29477. { name: 'p', type: 'vec2' },
  29478. { name: 'x', type: 'int' },
  29479. { name: 'y', type: 'int' },
  29480. { name: 'xoff', type: 'int' },
  29481. { name: 'yoff', type: 'int' },
  29482. { name: 'jitter', type: 'float' },
  29483. { name: 'metric', type: 'int' }
  29484. ]
  29485. } );
  29486. 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 ] ) => {
  29487. const metric = int( metric_immutable ).toVar();
  29488. const jitter = float( jitter_immutable ).toVar();
  29489. const zoff = int( zoff_immutable ).toVar();
  29490. const yoff = int( yoff_immutable ).toVar();
  29491. const xoff = int( xoff_immutable ).toVar();
  29492. const z = int( z_immutable ).toVar();
  29493. const y = int( y_immutable ).toVar();
  29494. const x = int( x_immutable ).toVar();
  29495. const p = vec3( p_immutable ).toVar();
  29496. const off = vec3( mx_cell_noise_vec3( vec3( x.add( xoff ), y.add( yoff ), z.add( zoff ) ) ) ).toVar();
  29497. off.subAssign( 0.5 );
  29498. off.mulAssign( jitter );
  29499. off.addAssign( 0.5 );
  29500. const cellpos = vec3( vec3( float( x ), float( y ), float( z ) ).add( off ) ).toVar();
  29501. const diff = vec3( cellpos.sub( p ) ).toVar();
  29502. If( metric.equal( int( 2 ) ), () => {
  29503. return abs( diff.x ).add( abs( diff.y ) ).add( abs( diff.z ) );
  29504. } );
  29505. If( metric.equal( int( 3 ) ), () => {
  29506. return max$1( abs( diff.x ), abs( diff.y ), abs( diff.z ) );
  29507. } );
  29508. return dot( diff, diff );
  29509. } ).setLayout( {
  29510. name: 'mx_worley_distance_1',
  29511. type: 'float',
  29512. inputs: [
  29513. { name: 'p', type: 'vec3' },
  29514. { name: 'x', type: 'int' },
  29515. { name: 'y', type: 'int' },
  29516. { name: 'z', type: 'int' },
  29517. { name: 'xoff', type: 'int' },
  29518. { name: 'yoff', type: 'int' },
  29519. { name: 'zoff', type: 'int' },
  29520. { name: 'jitter', type: 'float' },
  29521. { name: 'metric', type: 'int' }
  29522. ]
  29523. } );
  29524. const mx_worley_distance = /*@__PURE__*/ overloadingFn( [ mx_worley_distance_0, mx_worley_distance_1 ] );
  29525. const mx_worley_noise_float_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29526. const metric = int( metric_immutable ).toVar();
  29527. const jitter = float( jitter_immutable ).toVar();
  29528. const p = vec2( p_immutable ).toVar();
  29529. const X = int().toVar(), Y = int().toVar();
  29530. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29531. const sqdist = float( 1e6 ).toVar();
  29532. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29533. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29534. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29535. sqdist.assign( min$1( sqdist, dist ) );
  29536. } );
  29537. } );
  29538. If( metric.equal( int( 0 ) ), () => {
  29539. sqdist.assign( sqrt( sqdist ) );
  29540. } );
  29541. return sqdist;
  29542. } ).setLayout( {
  29543. name: 'mx_worley_noise_float_0',
  29544. type: 'float',
  29545. inputs: [
  29546. { name: 'p', type: 'vec2' },
  29547. { name: 'jitter', type: 'float' },
  29548. { name: 'metric', type: 'int' }
  29549. ]
  29550. } );
  29551. const mx_worley_noise_vec2_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29552. const metric = int( metric_immutable ).toVar();
  29553. const jitter = float( jitter_immutable ).toVar();
  29554. const p = vec2( p_immutable ).toVar();
  29555. const X = int().toVar(), Y = int().toVar();
  29556. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29557. const sqdist = vec2( 1e6, 1e6 ).toVar();
  29558. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29559. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29560. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29561. If( dist.lessThan( sqdist.x ), () => {
  29562. sqdist.y.assign( sqdist.x );
  29563. sqdist.x.assign( dist );
  29564. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29565. sqdist.y.assign( dist );
  29566. } );
  29567. } );
  29568. } );
  29569. If( metric.equal( int( 0 ) ), () => {
  29570. sqdist.assign( sqrt( sqdist ) );
  29571. } );
  29572. return sqdist;
  29573. } ).setLayout( {
  29574. name: 'mx_worley_noise_vec2_0',
  29575. type: 'vec2',
  29576. inputs: [
  29577. { name: 'p', type: 'vec2' },
  29578. { name: 'jitter', type: 'float' },
  29579. { name: 'metric', type: 'int' }
  29580. ]
  29581. } );
  29582. const mx_worley_noise_vec3_0 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29583. const metric = int( metric_immutable ).toVar();
  29584. const jitter = float( jitter_immutable ).toVar();
  29585. const p = vec2( p_immutable ).toVar();
  29586. const X = int().toVar(), Y = int().toVar();
  29587. const localpos = vec2( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ) ).toVar();
  29588. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  29589. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29590. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29591. const dist = float( mx_worley_distance( localpos, x, y, X, Y, jitter, metric ) ).toVar();
  29592. If( dist.lessThan( sqdist.x ), () => {
  29593. sqdist.z.assign( sqdist.y );
  29594. sqdist.y.assign( sqdist.x );
  29595. sqdist.x.assign( dist );
  29596. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29597. sqdist.z.assign( sqdist.y );
  29598. sqdist.y.assign( dist );
  29599. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  29600. sqdist.z.assign( dist );
  29601. } );
  29602. } );
  29603. } );
  29604. If( metric.equal( int( 0 ) ), () => {
  29605. sqdist.assign( sqrt( sqdist ) );
  29606. } );
  29607. return sqdist;
  29608. } ).setLayout( {
  29609. name: 'mx_worley_noise_vec3_0',
  29610. type: 'vec3',
  29611. inputs: [
  29612. { name: 'p', type: 'vec2' },
  29613. { name: 'jitter', type: 'float' },
  29614. { name: 'metric', type: 'int' }
  29615. ]
  29616. } );
  29617. const mx_worley_noise_float_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29618. const metric = int( metric_immutable ).toVar();
  29619. const jitter = float( jitter_immutable ).toVar();
  29620. const p = vec3( p_immutable ).toVar();
  29621. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29622. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29623. const sqdist = float( 1e6 ).toVar();
  29624. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29625. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29626. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29627. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29628. sqdist.assign( min$1( sqdist, dist ) );
  29629. } );
  29630. } );
  29631. } );
  29632. If( metric.equal( int( 0 ) ), () => {
  29633. sqdist.assign( sqrt( sqdist ) );
  29634. } );
  29635. return sqdist;
  29636. } ).setLayout( {
  29637. name: 'mx_worley_noise_float_1',
  29638. type: 'float',
  29639. inputs: [
  29640. { name: 'p', type: 'vec3' },
  29641. { name: 'jitter', type: 'float' },
  29642. { name: 'metric', type: 'int' }
  29643. ]
  29644. } );
  29645. const mx_worley_noise_float$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_float_0, mx_worley_noise_float_1 ] );
  29646. const mx_worley_noise_vec2_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29647. const metric = int( metric_immutable ).toVar();
  29648. const jitter = float( jitter_immutable ).toVar();
  29649. const p = vec3( p_immutable ).toVar();
  29650. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29651. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29652. const sqdist = vec2( 1e6, 1e6 ).toVar();
  29653. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29654. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29655. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29656. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29657. If( dist.lessThan( sqdist.x ), () => {
  29658. sqdist.y.assign( sqdist.x );
  29659. sqdist.x.assign( dist );
  29660. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29661. sqdist.y.assign( dist );
  29662. } );
  29663. } );
  29664. } );
  29665. } );
  29666. If( metric.equal( int( 0 ) ), () => {
  29667. sqdist.assign( sqrt( sqdist ) );
  29668. } );
  29669. return sqdist;
  29670. } ).setLayout( {
  29671. name: 'mx_worley_noise_vec2_1',
  29672. type: 'vec2',
  29673. inputs: [
  29674. { name: 'p', type: 'vec3' },
  29675. { name: 'jitter', type: 'float' },
  29676. { name: 'metric', type: 'int' }
  29677. ]
  29678. } );
  29679. const mx_worley_noise_vec2$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec2_0, mx_worley_noise_vec2_1 ] );
  29680. const mx_worley_noise_vec3_1 = /*@__PURE__*/ Fn( ( [ p_immutable, jitter_immutable, metric_immutable ] ) => {
  29681. const metric = int( metric_immutable ).toVar();
  29682. const jitter = float( jitter_immutable ).toVar();
  29683. const p = vec3( p_immutable ).toVar();
  29684. const X = int().toVar(), Y = int().toVar(), Z = int().toVar();
  29685. const localpos = vec3( mx_floorfrac( p.x, X ), mx_floorfrac( p.y, Y ), mx_floorfrac( p.z, Z ) ).toVar();
  29686. const sqdist = vec3( 1e6, 1e6, 1e6 ).toVar();
  29687. Loop( { start: -1, end: int( 1 ), name: 'x', condition: '<=' }, ( { x } ) => {
  29688. Loop( { start: -1, end: int( 1 ), name: 'y', condition: '<=' }, ( { y } ) => {
  29689. Loop( { start: -1, end: int( 1 ), name: 'z', condition: '<=' }, ( { z } ) => {
  29690. const dist = float( mx_worley_distance( localpos, x, y, z, X, Y, Z, jitter, metric ) ).toVar();
  29691. If( dist.lessThan( sqdist.x ), () => {
  29692. sqdist.z.assign( sqdist.y );
  29693. sqdist.y.assign( sqdist.x );
  29694. sqdist.x.assign( dist );
  29695. } ).ElseIf( dist.lessThan( sqdist.y ), () => {
  29696. sqdist.z.assign( sqdist.y );
  29697. sqdist.y.assign( dist );
  29698. } ).ElseIf( dist.lessThan( sqdist.z ), () => {
  29699. sqdist.z.assign( dist );
  29700. } );
  29701. } );
  29702. } );
  29703. } );
  29704. If( metric.equal( int( 0 ) ), () => {
  29705. sqdist.assign( sqrt( sqdist ) );
  29706. } );
  29707. return sqdist;
  29708. } ).setLayout( {
  29709. name: 'mx_worley_noise_vec3_1',
  29710. type: 'vec3',
  29711. inputs: [
  29712. { name: 'p', type: 'vec3' },
  29713. { name: 'jitter', type: 'float' },
  29714. { name: 'metric', type: 'int' }
  29715. ]
  29716. } );
  29717. const mx_worley_noise_vec3$1 = /*@__PURE__*/ overloadingFn( [ mx_worley_noise_vec3_0, mx_worley_noise_vec3_1 ] );
  29718. // Three.js Transpiler
  29719. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_hsv.glsl
  29720. const mx_hsvtorgb = /*@__PURE__*/ Fn( ( [ hsv ] ) => {
  29721. const s = hsv.y;
  29722. const v = hsv.z;
  29723. const result = vec3().toVar();
  29724. If( s.lessThan( 0.0001 ), () => {
  29725. result.assign( vec3( v, v, v ) );
  29726. } ).Else( () => {
  29727. let h = hsv.x;
  29728. h = h.sub( floor( h ) ).mul( 6.0 ).toVar(); // TODO: check what .toVar() is needed in node system cache
  29729. const hi = int( trunc( h ) );
  29730. const f = h.sub( float( hi ) );
  29731. const p = v.mul( s.oneMinus() );
  29732. const q = v.mul( s.mul( f ).oneMinus() );
  29733. const t = v.mul( s.mul( f.oneMinus() ).oneMinus() );
  29734. If( hi.equal( int( 0 ) ), () => {
  29735. result.assign( vec3( v, t, p ) );
  29736. } ).ElseIf( hi.equal( int( 1 ) ), () => {
  29737. result.assign( vec3( q, v, p ) );
  29738. } ).ElseIf( hi.equal( int( 2 ) ), () => {
  29739. result.assign( vec3( p, v, t ) );
  29740. } ).ElseIf( hi.equal( int( 3 ) ), () => {
  29741. result.assign( vec3( p, q, v ) );
  29742. } ).ElseIf( hi.equal( int( 4 ) ), () => {
  29743. result.assign( vec3( t, p, v ) );
  29744. } ).Else( () => {
  29745. result.assign( vec3( v, p, q ) );
  29746. } );
  29747. } );
  29748. return result;
  29749. } ).setLayout( {
  29750. name: 'mx_hsvtorgb',
  29751. type: 'vec3',
  29752. inputs: [
  29753. { name: 'hsv', type: 'vec3' }
  29754. ]
  29755. } );
  29756. const mx_rgbtohsv = /*@__PURE__*/ Fn( ( [ c_immutable ] ) => {
  29757. const c = vec3( c_immutable ).toVar();
  29758. const r = float( c.x ).toVar();
  29759. const g = float( c.y ).toVar();
  29760. const b = float( c.z ).toVar();
  29761. const mincomp = float( min$1( r, min$1( g, b ) ) ).toVar();
  29762. const maxcomp = float( max$1( r, max$1( g, b ) ) ).toVar();
  29763. const delta = float( maxcomp.sub( mincomp ) ).toVar();
  29764. const h = float().toVar(), s = float().toVar(), v = float().toVar();
  29765. v.assign( maxcomp );
  29766. If( maxcomp.greaterThan( 0.0 ), () => {
  29767. s.assign( delta.div( maxcomp ) );
  29768. } ).Else( () => {
  29769. s.assign( 0.0 );
  29770. } );
  29771. If( s.lessThanEqual( 0.0 ), () => {
  29772. h.assign( 0.0 );
  29773. } ).Else( () => {
  29774. If( r.greaterThanEqual( maxcomp ), () => {
  29775. h.assign( g.sub( b ).div( delta ) );
  29776. } ).ElseIf( g.greaterThanEqual( maxcomp ), () => {
  29777. h.assign( add( 2.0, b.sub( r ).div( delta ) ) );
  29778. } ).Else( () => {
  29779. h.assign( add( 4.0, r.sub( g ).div( delta ) ) );
  29780. } );
  29781. h.mulAssign( 1.0 / 6.0 );
  29782. If( h.lessThan( 0.0 ), () => {
  29783. h.addAssign( 1.0 );
  29784. } );
  29785. } );
  29786. return vec3( h, s, v );
  29787. } ).setLayout( {
  29788. name: 'mx_rgbtohsv',
  29789. type: 'vec3',
  29790. inputs: [
  29791. { name: 'c', type: 'vec3' }
  29792. ]
  29793. } );
  29794. // Three.js Transpiler
  29795. // https://github.com/AcademySoftwareFoundation/MaterialX/blob/main/libraries/stdlib/genglsl/lib/mx_transform_color.glsl
  29796. const mx_srgb_texture_to_lin_rec709 = /*@__PURE__*/ Fn( ( [ color_immutable ] ) => {
  29797. const color = vec3( color_immutable ).toVar();
  29798. const isAbove = bvec3( greaterThan( color, vec3( 0.04045 ) ) ).toVar();
  29799. const linSeg = vec3( color.div( 12.92 ) ).toVar();
  29800. const powSeg = vec3( pow( max$1( color.add( vec3( 0.055 ) ), vec3( 0.0 ) ).div( 1.055 ), vec3( 2.4 ) ) ).toVar();
  29801. return mix( linSeg, powSeg, isAbove );
  29802. } ).setLayout( {
  29803. name: 'mx_srgb_texture_to_lin_rec709',
  29804. type: 'vec3',
  29805. inputs: [
  29806. { name: 'color', type: 'vec3' }
  29807. ]
  29808. } );
  29809. const mx_aastep = ( threshold, value ) => {
  29810. threshold = float( threshold );
  29811. value = float( value );
  29812. const afwidth = vec2( value.dFdx(), value.dFdy() ).length().mul( 0.70710678118654757 );
  29813. return smoothstep( threshold.sub( afwidth ), threshold.add( afwidth ), value );
  29814. };
  29815. const _ramp = ( a, b, uv, p ) => mix( a, b, uv[ p ].clamp() );
  29816. const mx_ramplr = ( valuel, valuer, texcoord = uv() ) => _ramp( valuel, valuer, texcoord, 'x' );
  29817. const mx_ramptb = ( valuet, valueb, texcoord = uv() ) => _ramp( valuet, valueb, texcoord, 'y' );
  29818. const _split = ( a, b, center, uv, p ) => mix( a, b, mx_aastep( center, uv[ p ] ) );
  29819. const mx_splitlr = ( valuel, valuer, center, texcoord = uv() ) => _split( valuel, valuer, center, texcoord, 'x' );
  29820. const mx_splittb = ( valuet, valueb, center, texcoord = uv() ) => _split( valuet, valueb, center, texcoord, 'y' );
  29821. const mx_transform_uv = ( uv_scale = 1, uv_offset = 0, uv_geo = uv() ) => uv_geo.mul( uv_scale ).add( uv_offset );
  29822. const mx_safepower = ( in1, in2 = 1 ) => {
  29823. in1 = float( in1 );
  29824. return in1.abs().pow( in2 ).mul( in1.sign() );
  29825. };
  29826. const mx_contrast = ( input, amount = 1, pivot = .5 ) => float( input ).sub( pivot ).mul( amount ).add( pivot );
  29827. const mx_noise_float = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_float( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  29828. //export const mx_noise_vec2 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  29829. const mx_noise_vec3 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => mx_perlin_noise_vec3( texcoord.convert( 'vec2|vec3' ) ).mul( amplitude ).add( pivot );
  29830. const mx_noise_vec4 = ( texcoord = uv(), amplitude = 1, pivot = 0 ) => {
  29831. texcoord = texcoord.convert( 'vec2|vec3' ); // overloading type
  29832. const noise_vec4 = vec4( mx_perlin_noise_vec3( texcoord ), mx_perlin_noise_float( texcoord.add( vec2( 19, 73 ) ) ) );
  29833. return noise_vec4.mul( amplitude ).add( pivot );
  29834. };
  29835. const mx_worley_noise_float = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_float$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  29836. const mx_worley_noise_vec2 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec2$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  29837. const mx_worley_noise_vec3 = ( texcoord = uv(), jitter = 1 ) => mx_worley_noise_vec3$1( texcoord.convert( 'vec2|vec3' ), jitter, int( 1 ) );
  29838. const mx_cell_noise_float = ( texcoord = uv() ) => mx_cell_noise_float$1( texcoord.convert( 'vec2|vec3' ) );
  29839. const mx_fractal_noise_float = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_float$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  29840. const mx_fractal_noise_vec2 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec2$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  29841. const mx_fractal_noise_vec3 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec3$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  29842. const mx_fractal_noise_vec4 = ( position = uv(), octaves = 3, lacunarity = 2, diminish = .5, amplitude = 1 ) => mx_fractal_noise_vec4$1( position, int( octaves ), lacunarity, diminish ).mul( amplitude );
  29843. /**
  29844. * This computes a parallax corrected normal which is used for box-projected cube mapping (BPCEM).
  29845. *
  29846. * Reference: {@link https://devlog-martinsh.blogspot.com/2011/09/box-projected-cube-environment-mapping.html}
  29847. *
  29848. * ```js
  29849. * const uvNode = getParallaxCorrectNormal( reflectVector, vec3( 200, 100, 100 ), vec3( 0, - 50, 0 ) );
  29850. * material.envNode = pmremTexture( renderTarget.texture, uvNode );
  29851. * ```
  29852. *
  29853. * @tsl
  29854. * @function
  29855. * @param {Node<vec3>} normal - The normal to correct.
  29856. * @param {Node<vec3>} cubeSize - The cube size should reflect the size of the environment (BPCEM is usually applied in closed environments like rooms).
  29857. * @param {Node<vec3>} cubePos - The cube position.
  29858. * @return {Node<vec3>} The parallax corrected normal.
  29859. */
  29860. const getParallaxCorrectNormal = /*@__PURE__*/ Fn( ( [ normal, cubeSize, cubePos ] ) => {
  29861. const nDir = normalize( normal ).toVar();
  29862. const rbmax = sub( float( 0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  29863. const rbmin = sub( float( -0.5 ).mul( cubeSize.sub( cubePos ) ), positionWorld ).div( nDir ).toVar();
  29864. const rbminmax = vec3().toVar();
  29865. rbminmax.x = nDir.x.greaterThan( float( 0 ) ).select( rbmax.x, rbmin.x );
  29866. rbminmax.y = nDir.y.greaterThan( float( 0 ) ).select( rbmax.y, rbmin.y );
  29867. rbminmax.z = nDir.z.greaterThan( float( 0 ) ).select( rbmax.z, rbmin.z );
  29868. const correction = min$1( rbminmax.x, rbminmax.y, rbminmax.z ).toVar();
  29869. const boxIntersection = positionWorld.add( nDir.mul( correction ) ).toVar();
  29870. return boxIntersection.sub( cubePos );
  29871. } );
  29872. const getShIrradianceAt = /*@__PURE__*/ Fn( ( [ normal, shCoefficients ] ) => {
  29873. // normal is assumed to have unit length
  29874. const x = normal.x, y = normal.y, z = normal.z;
  29875. // band 0
  29876. let result = shCoefficients.element( 0 ).mul( 0.886227 );
  29877. // band 1
  29878. result = result.add( shCoefficients.element( 1 ).mul( 2.0 * 0.511664 ).mul( y ) );
  29879. result = result.add( shCoefficients.element( 2 ).mul( 2.0 * 0.511664 ).mul( z ) );
  29880. result = result.add( shCoefficients.element( 3 ).mul( 2.0 * 0.511664 ).mul( x ) );
  29881. // band 2
  29882. result = result.add( shCoefficients.element( 4 ).mul( 2.0 * 0.429043 ).mul( x ).mul( y ) );
  29883. result = result.add( shCoefficients.element( 5 ).mul( 2.0 * 0.429043 ).mul( y ).mul( z ) );
  29884. result = result.add( shCoefficients.element( 6 ).mul( z.mul( z ).mul( 0.743125 ).sub( 0.247708 ) ) );
  29885. result = result.add( shCoefficients.element( 7 ).mul( 2.0 * 0.429043 ).mul( x ).mul( z ) );
  29886. result = result.add( shCoefficients.element( 8 ).mul( 0.429043 ).mul( mul( x, x ).sub( mul( y, y ) ) ) );
  29887. return result;
  29888. } );
  29889. // constants
  29890. var TSL = /*#__PURE__*/Object.freeze({
  29891. __proto__: null,
  29892. BRDF_GGX: BRDF_GGX,
  29893. BRDF_Lambert: BRDF_Lambert,
  29894. BasicPointShadowFilter: BasicPointShadowFilter,
  29895. BasicShadowFilter: BasicShadowFilter,
  29896. Break: Break,
  29897. Const: Const,
  29898. Continue: Continue,
  29899. DFGApprox: DFGApprox,
  29900. D_GGX: D_GGX,
  29901. Discard: Discard,
  29902. EPSILON: EPSILON,
  29903. F_Schlick: F_Schlick,
  29904. Fn: Fn,
  29905. INFINITY: INFINITY,
  29906. If: If,
  29907. Loop: Loop,
  29908. NodeAccess: NodeAccess,
  29909. NodeShaderStage: NodeShaderStage,
  29910. NodeType: NodeType,
  29911. NodeUpdateType: NodeUpdateType,
  29912. PCFShadowFilter: PCFShadowFilter,
  29913. PCFSoftShadowFilter: PCFSoftShadowFilter,
  29914. PI: PI,
  29915. PI2: PI2,
  29916. PointShadowFilter: PointShadowFilter,
  29917. Return: Return,
  29918. Schlick_to_F0: Schlick_to_F0,
  29919. ScriptableNodeResources: ScriptableNodeResources,
  29920. ShaderNode: ShaderNode,
  29921. Stack: Stack,
  29922. Switch: Switch,
  29923. TBNViewMatrix: TBNViewMatrix,
  29924. VSMShadowFilter: VSMShadowFilter,
  29925. V_GGX_SmithCorrelated: V_GGX_SmithCorrelated,
  29926. Var: Var,
  29927. abs: abs,
  29928. acesFilmicToneMapping: acesFilmicToneMapping,
  29929. acos: acos,
  29930. add: add,
  29931. addMethodChaining: addMethodChaining,
  29932. addNodeElement: addNodeElement,
  29933. agxToneMapping: agxToneMapping,
  29934. all: all,
  29935. alphaT: alphaT,
  29936. and: and,
  29937. anisotropy: anisotropy,
  29938. anisotropyB: anisotropyB,
  29939. anisotropyT: anisotropyT,
  29940. any: any,
  29941. append: append,
  29942. array: array,
  29943. arrayBuffer: arrayBuffer,
  29944. asin: asin,
  29945. assign: assign,
  29946. atan: atan,
  29947. atan2: atan2,
  29948. atomicAdd: atomicAdd,
  29949. atomicAnd: atomicAnd,
  29950. atomicFunc: atomicFunc,
  29951. atomicLoad: atomicLoad,
  29952. atomicMax: atomicMax,
  29953. atomicMin: atomicMin,
  29954. atomicOr: atomicOr,
  29955. atomicStore: atomicStore,
  29956. atomicSub: atomicSub,
  29957. atomicXor: atomicXor,
  29958. attenuationColor: attenuationColor,
  29959. attenuationDistance: attenuationDistance,
  29960. attribute: attribute,
  29961. attributeArray: attributeArray,
  29962. backgroundBlurriness: backgroundBlurriness,
  29963. backgroundIntensity: backgroundIntensity,
  29964. backgroundRotation: backgroundRotation,
  29965. batch: batch,
  29966. billboarding: billboarding,
  29967. bitAnd: bitAnd,
  29968. bitNot: bitNot,
  29969. bitOr: bitOr,
  29970. bitXor: bitXor,
  29971. bitangentGeometry: bitangentGeometry,
  29972. bitangentLocal: bitangentLocal,
  29973. bitangentView: bitangentView,
  29974. bitangentWorld: bitangentWorld,
  29975. bitcast: bitcast,
  29976. blendBurn: blendBurn,
  29977. blendColor: blendColor,
  29978. blendDodge: blendDodge,
  29979. blendOverlay: blendOverlay,
  29980. blendScreen: blendScreen,
  29981. blur: blur,
  29982. bool: bool,
  29983. buffer: buffer,
  29984. bufferAttribute: bufferAttribute,
  29985. bumpMap: bumpMap,
  29986. burn: burn,
  29987. bvec2: bvec2,
  29988. bvec3: bvec3,
  29989. bvec4: bvec4,
  29990. bypass: bypass,
  29991. cache: cache,
  29992. call: call,
  29993. cameraFar: cameraFar,
  29994. cameraIndex: cameraIndex,
  29995. cameraNear: cameraNear,
  29996. cameraNormalMatrix: cameraNormalMatrix,
  29997. cameraPosition: cameraPosition,
  29998. cameraProjectionMatrix: cameraProjectionMatrix,
  29999. cameraProjectionMatrixInverse: cameraProjectionMatrixInverse,
  30000. cameraViewMatrix: cameraViewMatrix,
  30001. cameraWorldMatrix: cameraWorldMatrix,
  30002. cbrt: cbrt,
  30003. cdl: cdl,
  30004. ceil: ceil,
  30005. checker: checker,
  30006. cineonToneMapping: cineonToneMapping,
  30007. clamp: clamp,
  30008. clearcoat: clearcoat,
  30009. clearcoatRoughness: clearcoatRoughness,
  30010. code: code,
  30011. color: color,
  30012. colorSpaceToWorking: colorSpaceToWorking,
  30013. colorToDirection: colorToDirection,
  30014. compute: compute,
  30015. computeSkinning: computeSkinning,
  30016. cond: cond,
  30017. context: context,
  30018. convert: convert,
  30019. convertColorSpace: convertColorSpace,
  30020. convertToTexture: convertToTexture,
  30021. cos: cos,
  30022. cross: cross,
  30023. cubeTexture: cubeTexture,
  30024. cubeTextureBase: cubeTextureBase,
  30025. cubeToUV: cubeToUV,
  30026. dFdx: dFdx,
  30027. dFdy: dFdy,
  30028. dashSize: dashSize,
  30029. debug: debug,
  30030. decrement: decrement,
  30031. decrementBefore: decrementBefore,
  30032. defaultBuildStages: defaultBuildStages,
  30033. defaultShaderStages: defaultShaderStages,
  30034. defined: defined,
  30035. degrees: degrees,
  30036. deltaTime: deltaTime,
  30037. densityFog: densityFog,
  30038. densityFogFactor: densityFogFactor,
  30039. depth: depth,
  30040. depthPass: depthPass,
  30041. difference: difference,
  30042. diffuseColor: diffuseColor,
  30043. directPointLight: directPointLight,
  30044. directionToColor: directionToColor,
  30045. dispersion: dispersion,
  30046. distance: distance,
  30047. div: div,
  30048. dodge: dodge,
  30049. dot: dot,
  30050. drawIndex: drawIndex,
  30051. dynamicBufferAttribute: dynamicBufferAttribute,
  30052. element: element,
  30053. emissive: emissive,
  30054. equal: equal,
  30055. equals: equals,
  30056. equirectUV: equirectUV,
  30057. exp: exp,
  30058. exp2: exp2,
  30059. expression: expression,
  30060. faceDirection: faceDirection,
  30061. faceForward: faceForward,
  30062. faceforward: faceforward,
  30063. float: float,
  30064. floor: floor,
  30065. fog: fog,
  30066. fract: fract,
  30067. frameGroup: frameGroup,
  30068. frameId: frameId,
  30069. frontFacing: frontFacing,
  30070. fwidth: fwidth,
  30071. gain: gain,
  30072. gapSize: gapSize,
  30073. getConstNodeType: getConstNodeType,
  30074. getCurrentStack: getCurrentStack,
  30075. getDirection: getDirection,
  30076. getDistanceAttenuation: getDistanceAttenuation,
  30077. getGeometryRoughness: getGeometryRoughness,
  30078. getNormalFromDepth: getNormalFromDepth,
  30079. getParallaxCorrectNormal: getParallaxCorrectNormal,
  30080. getRoughness: getRoughness,
  30081. getScreenPosition: getScreenPosition,
  30082. getShIrradianceAt: getShIrradianceAt,
  30083. getShadowMaterial: getShadowMaterial,
  30084. getShadowRenderObjectFunction: getShadowRenderObjectFunction,
  30085. getTextureIndex: getTextureIndex,
  30086. getViewPosition: getViewPosition,
  30087. globalId: globalId,
  30088. glsl: glsl,
  30089. glslFn: glslFn,
  30090. grayscale: grayscale,
  30091. greaterThan: greaterThan,
  30092. greaterThanEqual: greaterThanEqual,
  30093. hash: hash,
  30094. highpModelNormalViewMatrix: highpModelNormalViewMatrix,
  30095. highpModelViewMatrix: highpModelViewMatrix,
  30096. hue: hue,
  30097. increment: increment,
  30098. incrementBefore: incrementBefore,
  30099. instance: instance,
  30100. instanceIndex: instanceIndex,
  30101. instancedArray: instancedArray,
  30102. instancedBufferAttribute: instancedBufferAttribute,
  30103. instancedDynamicBufferAttribute: instancedDynamicBufferAttribute,
  30104. instancedMesh: instancedMesh,
  30105. int: int,
  30106. inverseSqrt: inverseSqrt,
  30107. inversesqrt: inversesqrt,
  30108. invocationLocalIndex: invocationLocalIndex,
  30109. invocationSubgroupIndex: invocationSubgroupIndex,
  30110. ior: ior,
  30111. iridescence: iridescence,
  30112. iridescenceIOR: iridescenceIOR,
  30113. iridescenceThickness: iridescenceThickness,
  30114. ivec2: ivec2,
  30115. ivec3: ivec3,
  30116. ivec4: ivec4,
  30117. js: js,
  30118. label: label,
  30119. length: length,
  30120. lengthSq: lengthSq,
  30121. lessThan: lessThan,
  30122. lessThanEqual: lessThanEqual,
  30123. lightPosition: lightPosition,
  30124. lightProjectionUV: lightProjectionUV,
  30125. lightShadowMatrix: lightShadowMatrix,
  30126. lightTargetDirection: lightTargetDirection,
  30127. lightTargetPosition: lightTargetPosition,
  30128. lightViewPosition: lightViewPosition,
  30129. lightingContext: lightingContext,
  30130. lights: lights,
  30131. linearDepth: linearDepth,
  30132. linearToneMapping: linearToneMapping,
  30133. localId: localId,
  30134. log: log,
  30135. log2: log2,
  30136. logarithmicDepthToViewZ: logarithmicDepthToViewZ,
  30137. loop: loop,
  30138. luminance: luminance,
  30139. mat2: mat2,
  30140. mat3: mat3,
  30141. mat4: mat4,
  30142. matcapUV: matcapUV,
  30143. materialAO: materialAO,
  30144. materialAlphaTest: materialAlphaTest,
  30145. materialAnisotropy: materialAnisotropy,
  30146. materialAnisotropyVector: materialAnisotropyVector,
  30147. materialAttenuationColor: materialAttenuationColor,
  30148. materialAttenuationDistance: materialAttenuationDistance,
  30149. materialClearcoat: materialClearcoat,
  30150. materialClearcoatNormal: materialClearcoatNormal,
  30151. materialClearcoatRoughness: materialClearcoatRoughness,
  30152. materialColor: materialColor,
  30153. materialDispersion: materialDispersion,
  30154. materialEmissive: materialEmissive,
  30155. materialEnvIntensity: materialEnvIntensity,
  30156. materialEnvRotation: materialEnvRotation,
  30157. materialIOR: materialIOR,
  30158. materialIridescence: materialIridescence,
  30159. materialIridescenceIOR: materialIridescenceIOR,
  30160. materialIridescenceThickness: materialIridescenceThickness,
  30161. materialLightMap: materialLightMap,
  30162. materialLineDashOffset: materialLineDashOffset,
  30163. materialLineDashSize: materialLineDashSize,
  30164. materialLineGapSize: materialLineGapSize,
  30165. materialLineScale: materialLineScale,
  30166. materialLineWidth: materialLineWidth,
  30167. materialMetalness: materialMetalness,
  30168. materialNormal: materialNormal,
  30169. materialOpacity: materialOpacity,
  30170. materialPointSize: materialPointSize,
  30171. materialReference: materialReference,
  30172. materialReflectivity: materialReflectivity,
  30173. materialRefractionRatio: materialRefractionRatio,
  30174. materialRotation: materialRotation,
  30175. materialRoughness: materialRoughness,
  30176. materialSheen: materialSheen,
  30177. materialSheenRoughness: materialSheenRoughness,
  30178. materialShininess: materialShininess,
  30179. materialSpecular: materialSpecular,
  30180. materialSpecularColor: materialSpecularColor,
  30181. materialSpecularIntensity: materialSpecularIntensity,
  30182. materialSpecularStrength: materialSpecularStrength,
  30183. materialThickness: materialThickness,
  30184. materialTransmission: materialTransmission,
  30185. max: max$1,
  30186. maxMipLevel: maxMipLevel,
  30187. mediumpModelViewMatrix: mediumpModelViewMatrix,
  30188. metalness: metalness,
  30189. min: min$1,
  30190. mix: mix,
  30191. mixElement: mixElement,
  30192. mod: mod,
  30193. modInt: modInt,
  30194. modelDirection: modelDirection,
  30195. modelNormalMatrix: modelNormalMatrix,
  30196. modelPosition: modelPosition,
  30197. modelRadius: modelRadius,
  30198. modelScale: modelScale,
  30199. modelViewMatrix: modelViewMatrix,
  30200. modelViewPosition: modelViewPosition,
  30201. modelViewProjection: modelViewProjection,
  30202. modelWorldMatrix: modelWorldMatrix,
  30203. modelWorldMatrixInverse: modelWorldMatrixInverse,
  30204. morphReference: morphReference,
  30205. mrt: mrt,
  30206. mul: mul,
  30207. mx_aastep: mx_aastep,
  30208. mx_cell_noise_float: mx_cell_noise_float,
  30209. mx_contrast: mx_contrast,
  30210. mx_fractal_noise_float: mx_fractal_noise_float,
  30211. mx_fractal_noise_vec2: mx_fractal_noise_vec2,
  30212. mx_fractal_noise_vec3: mx_fractal_noise_vec3,
  30213. mx_fractal_noise_vec4: mx_fractal_noise_vec4,
  30214. mx_hsvtorgb: mx_hsvtorgb,
  30215. mx_noise_float: mx_noise_float,
  30216. mx_noise_vec3: mx_noise_vec3,
  30217. mx_noise_vec4: mx_noise_vec4,
  30218. mx_ramplr: mx_ramplr,
  30219. mx_ramptb: mx_ramptb,
  30220. mx_rgbtohsv: mx_rgbtohsv,
  30221. mx_safepower: mx_safepower,
  30222. mx_splitlr: mx_splitlr,
  30223. mx_splittb: mx_splittb,
  30224. mx_srgb_texture_to_lin_rec709: mx_srgb_texture_to_lin_rec709,
  30225. mx_transform_uv: mx_transform_uv,
  30226. mx_worley_noise_float: mx_worley_noise_float,
  30227. mx_worley_noise_vec2: mx_worley_noise_vec2,
  30228. mx_worley_noise_vec3: mx_worley_noise_vec3,
  30229. namespace: namespace,
  30230. negate: negate,
  30231. neutralToneMapping: neutralToneMapping,
  30232. nodeArray: nodeArray,
  30233. nodeImmutable: nodeImmutable,
  30234. nodeObject: nodeObject,
  30235. nodeObjects: nodeObjects,
  30236. nodeProxy: nodeProxy,
  30237. normalFlat: normalFlat,
  30238. normalGeometry: normalGeometry,
  30239. normalLocal: normalLocal,
  30240. normalMap: normalMap,
  30241. normalView: normalView,
  30242. normalWorld: normalWorld,
  30243. normalize: normalize,
  30244. not: not,
  30245. notEqual: notEqual,
  30246. numWorkgroups: numWorkgroups,
  30247. objectDirection: objectDirection,
  30248. objectGroup: objectGroup,
  30249. objectPosition: objectPosition,
  30250. objectRadius: objectRadius,
  30251. objectScale: objectScale,
  30252. objectViewPosition: objectViewPosition,
  30253. objectWorldMatrix: objectWorldMatrix,
  30254. oneMinus: oneMinus,
  30255. or: or,
  30256. orthographicDepthToViewZ: orthographicDepthToViewZ,
  30257. oscSawtooth: oscSawtooth,
  30258. oscSine: oscSine,
  30259. oscSquare: oscSquare,
  30260. oscTriangle: oscTriangle,
  30261. output: output,
  30262. outputStruct: outputStruct,
  30263. overlay: overlay,
  30264. overloadingFn: overloadingFn,
  30265. parabola: parabola,
  30266. parallaxDirection: parallaxDirection,
  30267. parallaxUV: parallaxUV,
  30268. parameter: parameter,
  30269. pass: pass,
  30270. passTexture: passTexture,
  30271. pcurve: pcurve,
  30272. perspectiveDepthToViewZ: perspectiveDepthToViewZ,
  30273. pmremTexture: pmremTexture,
  30274. pointShadow: pointShadow,
  30275. pointUV: pointUV,
  30276. pointWidth: pointWidth,
  30277. positionGeometry: positionGeometry,
  30278. positionLocal: positionLocal,
  30279. positionPrevious: positionPrevious,
  30280. positionView: positionView,
  30281. positionViewDirection: positionViewDirection,
  30282. positionWorld: positionWorld,
  30283. positionWorldDirection: positionWorldDirection,
  30284. posterize: posterize,
  30285. pow: pow,
  30286. pow2: pow2,
  30287. pow3: pow3,
  30288. pow4: pow4,
  30289. premultiplyAlpha: premultiplyAlpha,
  30290. property: property,
  30291. radians: radians,
  30292. rand: rand,
  30293. range: range,
  30294. rangeFog: rangeFog,
  30295. rangeFogFactor: rangeFogFactor,
  30296. reciprocal: reciprocal,
  30297. reference: reference,
  30298. referenceBuffer: referenceBuffer,
  30299. reflect: reflect,
  30300. reflectVector: reflectVector,
  30301. reflectView: reflectView,
  30302. reflector: reflector,
  30303. refract: refract,
  30304. refractVector: refractVector,
  30305. refractView: refractView,
  30306. reinhardToneMapping: reinhardToneMapping,
  30307. remainder: remainder,
  30308. remap: remap,
  30309. remapClamp: remapClamp,
  30310. renderGroup: renderGroup,
  30311. renderOutput: renderOutput,
  30312. rendererReference: rendererReference,
  30313. rotate: rotate,
  30314. rotateUV: rotateUV,
  30315. roughness: roughness,
  30316. round: round,
  30317. rtt: rtt,
  30318. sRGBTransferEOTF: sRGBTransferEOTF,
  30319. sRGBTransferOETF: sRGBTransferOETF,
  30320. sampler: sampler,
  30321. samplerComparison: samplerComparison,
  30322. saturate: saturate,
  30323. saturation: saturation,
  30324. screen: screen,
  30325. screenCoordinate: screenCoordinate,
  30326. screenSize: screenSize,
  30327. screenUV: screenUV,
  30328. scriptable: scriptable,
  30329. scriptableValue: scriptableValue,
  30330. select: select,
  30331. setCurrentStack: setCurrentStack,
  30332. shaderStages: shaderStages,
  30333. shadow: shadow,
  30334. shadowPositionWorld: shadowPositionWorld,
  30335. shapeCircle: shapeCircle,
  30336. sharedUniformGroup: sharedUniformGroup,
  30337. sheen: sheen,
  30338. sheenRoughness: sheenRoughness,
  30339. shiftLeft: shiftLeft,
  30340. shiftRight: shiftRight,
  30341. shininess: shininess,
  30342. sign: sign,
  30343. sin: sin,
  30344. sinc: sinc,
  30345. skinning: skinning,
  30346. smoothstep: smoothstep,
  30347. smoothstepElement: smoothstepElement,
  30348. specularColor: specularColor,
  30349. specularF90: specularF90,
  30350. spherizeUV: spherizeUV,
  30351. split: split,
  30352. spritesheetUV: spritesheetUV,
  30353. sqrt: sqrt,
  30354. stack: stack,
  30355. step: step,
  30356. storage: storage,
  30357. storageBarrier: storageBarrier,
  30358. storageObject: storageObject,
  30359. storageTexture: storageTexture,
  30360. string: string,
  30361. struct: struct,
  30362. sub: sub,
  30363. subgroupIndex: subgroupIndex,
  30364. subgroupSize: subgroupSize,
  30365. tan: tan,
  30366. tangentGeometry: tangentGeometry,
  30367. tangentLocal: tangentLocal,
  30368. tangentView: tangentView,
  30369. tangentWorld: tangentWorld,
  30370. temp: temp,
  30371. texture: texture,
  30372. texture3D: texture3D,
  30373. textureBarrier: textureBarrier,
  30374. textureBicubic: textureBicubic,
  30375. textureCubeUV: textureCubeUV,
  30376. textureLoad: textureLoad,
  30377. textureSize: textureSize,
  30378. textureStore: textureStore,
  30379. thickness: thickness,
  30380. time: time,
  30381. timerDelta: timerDelta,
  30382. timerGlobal: timerGlobal,
  30383. timerLocal: timerLocal,
  30384. toneMapping: toneMapping,
  30385. toneMappingExposure: toneMappingExposure,
  30386. toonOutlinePass: toonOutlinePass,
  30387. transformDirection: transformDirection,
  30388. transformNormal: transformNormal,
  30389. transformNormalToView: transformNormalToView,
  30390. transformedBentNormalView: transformedBentNormalView,
  30391. transformedBitangentView: transformedBitangentView,
  30392. transformedBitangentWorld: transformedBitangentWorld,
  30393. transformedClearcoatNormalView: transformedClearcoatNormalView,
  30394. transformedNormalView: transformedNormalView,
  30395. transformedNormalWorld: transformedNormalWorld,
  30396. transformedTangentView: transformedTangentView,
  30397. transformedTangentWorld: transformedTangentWorld,
  30398. transmission: transmission,
  30399. transpose: transpose,
  30400. triNoise3D: triNoise3D,
  30401. triplanarTexture: triplanarTexture,
  30402. triplanarTextures: triplanarTextures,
  30403. trunc: trunc,
  30404. tslFn: tslFn,
  30405. uint: uint,
  30406. uniform: uniform,
  30407. uniformArray: uniformArray,
  30408. uniformCubeTexture: uniformCubeTexture,
  30409. uniformGroup: uniformGroup,
  30410. uniformTexture: uniformTexture,
  30411. uniforms: uniforms,
  30412. unpremultiplyAlpha: unpremultiplyAlpha,
  30413. userData: userData,
  30414. uv: uv,
  30415. uvec2: uvec2,
  30416. uvec3: uvec3,
  30417. uvec4: uvec4,
  30418. varying: varying,
  30419. varyingProperty: varyingProperty,
  30420. vec2: vec2,
  30421. vec3: vec3,
  30422. vec4: vec4,
  30423. vectorComponents: vectorComponents,
  30424. velocity: velocity,
  30425. vertexColor: vertexColor,
  30426. vertexIndex: vertexIndex,
  30427. vertexStage: vertexStage,
  30428. vibrance: vibrance,
  30429. viewZToLogarithmicDepth: viewZToLogarithmicDepth,
  30430. viewZToOrthographicDepth: viewZToOrthographicDepth,
  30431. viewZToPerspectiveDepth: viewZToPerspectiveDepth,
  30432. viewport: viewport,
  30433. viewportBottomLeft: viewportBottomLeft,
  30434. viewportCoordinate: viewportCoordinate,
  30435. viewportDepthTexture: viewportDepthTexture,
  30436. viewportLinearDepth: viewportLinearDepth,
  30437. viewportMipTexture: viewportMipTexture,
  30438. viewportResolution: viewportResolution,
  30439. viewportSafeUV: viewportSafeUV,
  30440. viewportSharedTexture: viewportSharedTexture,
  30441. viewportSize: viewportSize,
  30442. viewportTexture: viewportTexture,
  30443. viewportTopLeft: viewportTopLeft,
  30444. viewportUV: viewportUV,
  30445. wgsl: wgsl,
  30446. wgslFn: wgslFn,
  30447. workgroupArray: workgroupArray,
  30448. workgroupBarrier: workgroupBarrier,
  30449. workgroupId: workgroupId,
  30450. workingToColorSpace: workingToColorSpace,
  30451. xor: xor
  30452. });
  30453. const _clearColor = /*@__PURE__*/ new Color4();
  30454. /**
  30455. * This renderer module manages the background.
  30456. *
  30457. * @private
  30458. * @augments DataMap
  30459. */
  30460. class Background extends DataMap {
  30461. /**
  30462. * Constructs a new background management component.
  30463. *
  30464. * @param {Renderer} renderer - The renderer.
  30465. * @param {Nodes} nodes - Renderer component for managing nodes related logic.
  30466. */
  30467. constructor( renderer, nodes ) {
  30468. super();
  30469. /**
  30470. * The renderer.
  30471. *
  30472. * @type {Renderer}
  30473. */
  30474. this.renderer = renderer;
  30475. /**
  30476. * Renderer component for managing nodes related logic.
  30477. *
  30478. * @type {Nodes}
  30479. */
  30480. this.nodes = nodes;
  30481. }
  30482. /**
  30483. * Updates the background for the given scene. Depending on how `Scene.background`
  30484. * or `Scene.backgroundNode` are configured, this method might configure a simple clear
  30485. * or add a mesh to the render list for rendering the background as a textured plane
  30486. * or skybox.
  30487. *
  30488. * @param {Scene} scene - The scene.
  30489. * @param {RenderList} renderList - The current render list.
  30490. * @param {RenderContext} renderContext - The current render context.
  30491. */
  30492. update( scene, renderList, renderContext ) {
  30493. const renderer = this.renderer;
  30494. const background = this.nodes.getBackgroundNode( scene ) || scene.background;
  30495. let forceClear = false;
  30496. if ( background === null ) {
  30497. // no background settings, use clear color configuration from the renderer
  30498. renderer._clearColor.getRGB( _clearColor );
  30499. _clearColor.a = renderer._clearColor.a;
  30500. } else if ( background.isColor === true ) {
  30501. // background is an opaque color
  30502. background.getRGB( _clearColor );
  30503. _clearColor.a = 1;
  30504. forceClear = true;
  30505. } else if ( background.isNode === true ) {
  30506. const sceneData = this.get( scene );
  30507. const backgroundNode = background;
  30508. _clearColor.copy( renderer._clearColor );
  30509. let backgroundMesh = sceneData.backgroundMesh;
  30510. if ( backgroundMesh === undefined ) {
  30511. const backgroundMeshNode = context( vec4( backgroundNode ).mul( backgroundIntensity ), {
  30512. // @TODO: Add Texture2D support using node context
  30513. getUV: () => backgroundRotation.mul( normalWorld ),
  30514. getTextureLevel: () => backgroundBlurriness
  30515. } );
  30516. let viewProj = modelViewProjection;
  30517. viewProj = viewProj.setZ( viewProj.w );
  30518. const nodeMaterial = new NodeMaterial();
  30519. nodeMaterial.name = 'Background.material';
  30520. nodeMaterial.side = BackSide;
  30521. nodeMaterial.depthTest = false;
  30522. nodeMaterial.depthWrite = false;
  30523. nodeMaterial.allowOverride = false;
  30524. nodeMaterial.fog = false;
  30525. nodeMaterial.lights = false;
  30526. nodeMaterial.vertexNode = viewProj;
  30527. nodeMaterial.colorNode = backgroundMeshNode;
  30528. sceneData.backgroundMeshNode = backgroundMeshNode;
  30529. sceneData.backgroundMesh = backgroundMesh = new Mesh( new SphereGeometry( 1, 32, 32 ), nodeMaterial );
  30530. backgroundMesh.frustumCulled = false;
  30531. backgroundMesh.name = 'Background.mesh';
  30532. backgroundMesh.onBeforeRender = function ( renderer, scene, camera ) {
  30533. this.matrixWorld.copyPosition( camera.matrixWorld );
  30534. };
  30535. function onBackgroundDispose() {
  30536. background.removeEventListener( 'dispose', onBackgroundDispose );
  30537. backgroundMesh.material.dispose();
  30538. backgroundMesh.geometry.dispose();
  30539. }
  30540. background.addEventListener( 'dispose', onBackgroundDispose );
  30541. }
  30542. const backgroundCacheKey = backgroundNode.getCacheKey();
  30543. if ( sceneData.backgroundCacheKey !== backgroundCacheKey ) {
  30544. sceneData.backgroundMeshNode.node = vec4( backgroundNode ).mul( backgroundIntensity );
  30545. sceneData.backgroundMeshNode.needsUpdate = true;
  30546. backgroundMesh.material.needsUpdate = true;
  30547. sceneData.backgroundCacheKey = backgroundCacheKey;
  30548. }
  30549. renderList.unshift( backgroundMesh, backgroundMesh.geometry, backgroundMesh.material, 0, 0, null, null );
  30550. } else {
  30551. console.error( 'THREE.Renderer: Unsupported background configuration.', background );
  30552. }
  30553. //
  30554. const environmentBlendMode = renderer.xr.getEnvironmentBlendMode();
  30555. if ( environmentBlendMode === 'additive' ) {
  30556. _clearColor.set( 0, 0, 0, 1 );
  30557. } else if ( environmentBlendMode === 'alpha-blend' ) {
  30558. _clearColor.set( 0, 0, 0, 0 );
  30559. }
  30560. //
  30561. if ( renderer.autoClear === true || forceClear === true ) {
  30562. const clearColorValue = renderContext.clearColorValue;
  30563. clearColorValue.r = _clearColor.r;
  30564. clearColorValue.g = _clearColor.g;
  30565. clearColorValue.b = _clearColor.b;
  30566. clearColorValue.a = _clearColor.a;
  30567. // premultiply alpha
  30568. if ( renderer.backend.isWebGLBackend === true || renderer.alpha === true ) {
  30569. clearColorValue.r *= clearColorValue.a;
  30570. clearColorValue.g *= clearColorValue.a;
  30571. clearColorValue.b *= clearColorValue.a;
  30572. }
  30573. //
  30574. renderContext.depthClearValue = renderer._clearDepth;
  30575. renderContext.stencilClearValue = renderer._clearStencil;
  30576. renderContext.clearColor = renderer.autoClearColor === true;
  30577. renderContext.clearDepth = renderer.autoClearDepth === true;
  30578. renderContext.clearStencil = renderer.autoClearStencil === true;
  30579. } else {
  30580. renderContext.clearColor = false;
  30581. renderContext.clearDepth = false;
  30582. renderContext.clearStencil = false;
  30583. }
  30584. }
  30585. }
  30586. let _id$6 = 0;
  30587. /**
  30588. * A bind group represents a collection of bindings and thus a collection
  30589. * or resources. Bind groups are assigned to pipelines to provide them
  30590. * with the required resources (like uniform buffers or textures).
  30591. *
  30592. * @private
  30593. */
  30594. class BindGroup {
  30595. /**
  30596. * Constructs a new bind group.
  30597. *
  30598. * @param {string} name - The bind group's name.
  30599. * @param {Array<Binding>} bindings - An array of bindings.
  30600. * @param {number} index - The group index.
  30601. * @param {Array<Binding>} bindingsReference - An array of reference bindings.
  30602. */
  30603. constructor( name = '', bindings = [], index = 0, bindingsReference = [] ) {
  30604. /**
  30605. * The bind group's name.
  30606. *
  30607. * @type {string}
  30608. */
  30609. this.name = name;
  30610. /**
  30611. * An array of bindings.
  30612. *
  30613. * @type {Array<Binding>}
  30614. */
  30615. this.bindings = bindings;
  30616. /**
  30617. * The group index.
  30618. *
  30619. * @type {number}
  30620. */
  30621. this.index = index;
  30622. /**
  30623. * An array of reference bindings.
  30624. *
  30625. * @type {Array<Binding>}
  30626. */
  30627. this.bindingsReference = bindingsReference;
  30628. /**
  30629. * The group's ID.
  30630. *
  30631. * @type {number}
  30632. */
  30633. this.id = _id$6 ++;
  30634. }
  30635. }
  30636. /**
  30637. * This module represents the state of a node builder after it was
  30638. * used to build the nodes for a render object. The state holds the
  30639. * results of the build for further processing in the renderer.
  30640. *
  30641. * Render objects with identical cache keys share the same node builder state.
  30642. *
  30643. * @private
  30644. */
  30645. class NodeBuilderState {
  30646. /**
  30647. * Constructs a new node builder state.
  30648. *
  30649. * @param {string} vertexShader - The native vertex shader code.
  30650. * @param {string} fragmentShader - The native fragment shader code.
  30651. * @param {string} computeShader - The native compute shader code.
  30652. * @param {Array<NodeAttribute>} nodeAttributes - An array of node attributes.
  30653. * @param {Array<BindGroup>} bindings - An array of bind groups.
  30654. * @param {Array<Node>} updateNodes - An array of nodes that implement their `update()` method.
  30655. * @param {Array<Node>} updateBeforeNodes - An array of nodes that implement their `updateBefore()` method.
  30656. * @param {Array<Node>} updateAfterNodes - An array of nodes that implement their `updateAfter()` method.
  30657. * @param {NodeMaterialObserver} observer - A node material observer.
  30658. * @param {Array<Object>} transforms - An array with transform attribute objects. Only relevant when using compute shaders with WebGL 2.
  30659. */
  30660. constructor( vertexShader, fragmentShader, computeShader, nodeAttributes, bindings, updateNodes, updateBeforeNodes, updateAfterNodes, observer, transforms = [] ) {
  30661. /**
  30662. * The native vertex shader code.
  30663. *
  30664. * @type {string}
  30665. */
  30666. this.vertexShader = vertexShader;
  30667. /**
  30668. * The native fragment shader code.
  30669. *
  30670. * @type {string}
  30671. */
  30672. this.fragmentShader = fragmentShader;
  30673. /**
  30674. * The native compute shader code.
  30675. *
  30676. * @type {string}
  30677. */
  30678. this.computeShader = computeShader;
  30679. /**
  30680. * An array with transform attribute objects.
  30681. * Only relevant when using compute shaders with WebGL 2.
  30682. *
  30683. * @type {Array<Object>}
  30684. */
  30685. this.transforms = transforms;
  30686. /**
  30687. * An array of node attributes representing
  30688. * the attributes of the shaders.
  30689. *
  30690. * @type {Array<NodeAttribute>}
  30691. */
  30692. this.nodeAttributes = nodeAttributes;
  30693. /**
  30694. * An array of bind groups representing the uniform or storage
  30695. * buffers, texture or samplers of the shader.
  30696. *
  30697. * @type {Array<BindGroup>}
  30698. */
  30699. this.bindings = bindings;
  30700. /**
  30701. * An array of nodes that implement their `update()` method.
  30702. *
  30703. * @type {Array<Node>}
  30704. */
  30705. this.updateNodes = updateNodes;
  30706. /**
  30707. * An array of nodes that implement their `updateBefore()` method.
  30708. *
  30709. * @type {Array<Node>}
  30710. */
  30711. this.updateBeforeNodes = updateBeforeNodes;
  30712. /**
  30713. * An array of nodes that implement their `updateAfter()` method.
  30714. *
  30715. * @type {Array<Node>}
  30716. */
  30717. this.updateAfterNodes = updateAfterNodes;
  30718. /**
  30719. * A node material observer.
  30720. *
  30721. * @type {NodeMaterialObserver}
  30722. */
  30723. this.observer = observer;
  30724. /**
  30725. * How often this state is used by render objects.
  30726. *
  30727. * @type {number}
  30728. */
  30729. this.usedTimes = 0;
  30730. }
  30731. /**
  30732. * This method is used to create a array of bind groups based
  30733. * on the existing bind groups of this state. Shared groups are
  30734. * not cloned.
  30735. *
  30736. * @return {Array<BindGroup>} A array of bind groups.
  30737. */
  30738. createBindings() {
  30739. const bindings = [];
  30740. for ( const instanceGroup of this.bindings ) {
  30741. const shared = instanceGroup.bindings[ 0 ].groupNode.shared; // All bindings in the group must have the same groupNode.
  30742. if ( shared !== true ) {
  30743. const bindingsGroup = new BindGroup( instanceGroup.name, [], instanceGroup.index, instanceGroup );
  30744. bindings.push( bindingsGroup );
  30745. for ( const instanceBinding of instanceGroup.bindings ) {
  30746. bindingsGroup.bindings.push( instanceBinding.clone() );
  30747. }
  30748. } else {
  30749. bindings.push( instanceGroup );
  30750. }
  30751. }
  30752. return bindings;
  30753. }
  30754. }
  30755. /**
  30756. * {@link NodeBuilder} is going to create instances of this class during the build process
  30757. * of nodes. They represent the final shader attributes that are going to be generated
  30758. * by the builder. Arrays of node attributes is maintained in {@link NodeBuilder#attributes}
  30759. * and {@link NodeBuilder#bufferAttributes} for this purpose.
  30760. */
  30761. class NodeAttribute {
  30762. /**
  30763. * Constructs a new node attribute.
  30764. *
  30765. * @param {string} name - The name of the attribute.
  30766. * @param {string} type - The type of the attribute.
  30767. * @param {?Node} node - An optional reference to the node.
  30768. */
  30769. constructor( name, type, node = null ) {
  30770. /**
  30771. * This flag can be used for type testing.
  30772. *
  30773. * @type {boolean}
  30774. * @readonly
  30775. * @default true
  30776. */
  30777. this.isNodeAttribute = true;
  30778. /**
  30779. * The name of the attribute.
  30780. *
  30781. * @type {string}
  30782. */
  30783. this.name = name;
  30784. /**
  30785. * The type of the attribute.
  30786. *
  30787. * @type {string}
  30788. */
  30789. this.type = type;
  30790. /**
  30791. * An optional reference to the node.
  30792. *
  30793. * @type {?Node}
  30794. * @default null
  30795. */
  30796. this.node = node;
  30797. }
  30798. }
  30799. /**
  30800. * {@link NodeBuilder} is going to create instances of this class during the build process
  30801. * of nodes. They represent the final shader uniforms that are going to be generated
  30802. * by the builder. A dictionary of node uniforms is maintained in {@link NodeBuilder#uniforms}
  30803. * for this purpose.
  30804. */
  30805. class NodeUniform {
  30806. /**
  30807. * Constructs a new node uniform.
  30808. *
  30809. * @param {string} name - The name of the uniform.
  30810. * @param {string} type - The type of the uniform.
  30811. * @param {UniformNode} node - An reference to the node.
  30812. */
  30813. constructor( name, type, node ) {
  30814. /**
  30815. * This flag can be used for type testing.
  30816. *
  30817. * @type {boolean}
  30818. * @readonly
  30819. * @default true
  30820. */
  30821. this.isNodeUniform = true;
  30822. /**
  30823. * The name of the uniform.
  30824. *
  30825. * @type {string}
  30826. */
  30827. this.name = name;
  30828. /**
  30829. * The type of the uniform.
  30830. *
  30831. * @type {string}
  30832. */
  30833. this.type = type;
  30834. /**
  30835. * An reference to the node.
  30836. *
  30837. * @type {UniformNode}
  30838. */
  30839. this.node = node.getSelf();
  30840. }
  30841. /**
  30842. * The value of the uniform node.
  30843. *
  30844. * @type {any}
  30845. */
  30846. get value() {
  30847. return this.node.value;
  30848. }
  30849. set value( val ) {
  30850. this.node.value = val;
  30851. }
  30852. /**
  30853. * The id of the uniform node.
  30854. *
  30855. * @type {number}
  30856. */
  30857. get id() {
  30858. return this.node.id;
  30859. }
  30860. /**
  30861. * The uniform node's group.
  30862. *
  30863. * @type {UniformGroupNode}
  30864. */
  30865. get groupNode() {
  30866. return this.node.groupNode;
  30867. }
  30868. }
  30869. /**
  30870. * {@link NodeBuilder} is going to create instances of this class during the build process
  30871. * of nodes. They represent the final shader variables that are going to be generated
  30872. * by the builder. A dictionary of node variables is maintained in {@link NodeBuilder#vars} for
  30873. * this purpose.
  30874. */
  30875. class NodeVar {
  30876. /**
  30877. * Constructs a new node variable.
  30878. *
  30879. * @param {string} name - The name of the variable.
  30880. * @param {string} type - The type of the variable.
  30881. * @param {boolean} [readOnly=false] - The read-only flag.
  30882. * @param {?number} [count=null] - The size.
  30883. */
  30884. constructor( name, type, readOnly = false, count = null ) {
  30885. /**
  30886. * This flag can be used for type testing.
  30887. *
  30888. * @type {boolean}
  30889. * @readonly
  30890. * @default true
  30891. */
  30892. this.isNodeVar = true;
  30893. /**
  30894. * The name of the variable.
  30895. *
  30896. * @type {string}
  30897. */
  30898. this.name = name;
  30899. /**
  30900. * The type of the variable.
  30901. *
  30902. * @type {string}
  30903. */
  30904. this.type = type;
  30905. /**
  30906. * The read-only flag.
  30907. *
  30908. * @type {boolean}
  30909. */
  30910. this.readOnly = readOnly;
  30911. /**
  30912. * The size.
  30913. *
  30914. * @type {?number}
  30915. */
  30916. this.count = count;
  30917. }
  30918. }
  30919. /**
  30920. * {@link NodeBuilder} is going to create instances of this class during the build process
  30921. * of nodes. They represent the final shader varyings that are going to be generated
  30922. * by the builder. An array of node varyings is maintained in {@link NodeBuilder#varyings} for
  30923. * this purpose.
  30924. *
  30925. * @augments NodeVar
  30926. */
  30927. class NodeVarying extends NodeVar {
  30928. /**
  30929. * Constructs a new node varying.
  30930. *
  30931. * @param {string} name - The name of the varying.
  30932. * @param {string} type - The type of the varying.
  30933. * @param {?string} interpolationType - The interpolation type of the varying.
  30934. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  30935. */
  30936. constructor( name, type, interpolationType = null, interpolationSampling = null ) {
  30937. super( name, type );
  30938. /**
  30939. * Whether this varying requires interpolation or not. This property can be used
  30940. * to check if the varying can be optimized for a variable.
  30941. *
  30942. * @type {boolean}
  30943. * @default false
  30944. */
  30945. this.needsInterpolation = false;
  30946. /**
  30947. * This flag can be used for type testing.
  30948. *
  30949. * @type {boolean}
  30950. * @readonly
  30951. * @default true
  30952. */
  30953. this.isNodeVarying = true;
  30954. /**
  30955. * The interpolation type of the varying data.
  30956. *
  30957. * @type {?string}
  30958. * @default null
  30959. */
  30960. this.interpolationType = interpolationType;
  30961. /**
  30962. * The interpolation sampling type of varying data.
  30963. *
  30964. * @type {?string}
  30965. * @default null
  30966. */
  30967. this.interpolationSampling = interpolationSampling;
  30968. }
  30969. }
  30970. /**
  30971. * {@link NodeBuilder} is going to create instances of this class during the build process
  30972. * of nodes. They represent user-defined, native shader code portions that are going to be
  30973. * injected by the builder. A dictionary of node codes is maintained in {@link NodeBuilder#codes}
  30974. * for this purpose.
  30975. */
  30976. class NodeCode {
  30977. /**
  30978. * Constructs a new code node.
  30979. *
  30980. * @param {string} name - The name of the code.
  30981. * @param {string} type - The node type.
  30982. * @param {string} [code=''] - The native shader code.
  30983. */
  30984. constructor( name, type, code = '' ) {
  30985. /**
  30986. * The name of the code.
  30987. *
  30988. * @type {string}
  30989. */
  30990. this.name = name;
  30991. /**
  30992. * The node type.
  30993. *
  30994. * @type {string}
  30995. */
  30996. this.type = type;
  30997. /**
  30998. * The native shader code.
  30999. *
  31000. * @type {string}
  31001. * @default ''
  31002. */
  31003. this.code = code;
  31004. Object.defineProperty( this, 'isNodeCode', { value: true } );
  31005. }
  31006. }
  31007. let _id$5 = 0;
  31008. /**
  31009. * This utility class is used in {@link NodeBuilder} as an internal
  31010. * cache data structure for node data.
  31011. */
  31012. class NodeCache {
  31013. /**
  31014. * Constructs a new node cache.
  31015. *
  31016. * @param {?NodeCache} parent - A reference to a parent cache.
  31017. */
  31018. constructor( parent = null ) {
  31019. /**
  31020. * The id of the cache.
  31021. *
  31022. * @type {number}
  31023. * @readonly
  31024. */
  31025. this.id = _id$5 ++;
  31026. /**
  31027. * A weak map for managing node data.
  31028. *
  31029. * @type {WeakMap<Node, Object>}
  31030. */
  31031. this.nodesData = new WeakMap();
  31032. /**
  31033. * Reference to a parent node cache.
  31034. *
  31035. * @type {?NodeCache}
  31036. * @default null
  31037. */
  31038. this.parent = parent;
  31039. }
  31040. /**
  31041. * Returns the data for the given node.
  31042. *
  31043. * @param {Node} node - The node.
  31044. * @return {?Object} The data for the node.
  31045. */
  31046. getData( node ) {
  31047. let data = this.nodesData.get( node );
  31048. if ( data === undefined && this.parent !== null ) {
  31049. data = this.parent.getData( node );
  31050. }
  31051. return data;
  31052. }
  31053. /**
  31054. * Sets the data for a given node.
  31055. *
  31056. * @param {Node} node - The node.
  31057. * @param {Object} data - The data that should be cached.
  31058. */
  31059. setData( node, data ) {
  31060. this.nodesData.set( node, data );
  31061. }
  31062. }
  31063. class StructType {
  31064. constructor( name, members ) {
  31065. this.name = name;
  31066. this.members = members;
  31067. this.output = false;
  31068. }
  31069. }
  31070. /**
  31071. * Abstract base class for uniforms.
  31072. *
  31073. * @abstract
  31074. * @private
  31075. */
  31076. class Uniform {
  31077. /**
  31078. * Constructs a new uniform.
  31079. *
  31080. * @param {string} name - The uniform's name.
  31081. * @param {any} value - The uniform's value.
  31082. */
  31083. constructor( name, value ) {
  31084. /**
  31085. * The uniform's name.
  31086. *
  31087. * @type {string}
  31088. */
  31089. this.name = name;
  31090. /**
  31091. * The uniform's value.
  31092. *
  31093. * @type {any}
  31094. */
  31095. this.value = value;
  31096. /**
  31097. * Used to build the uniform buffer according to the STD140 layout.
  31098. * Derived uniforms will set this property to a data type specific
  31099. * value.
  31100. *
  31101. * @type {number}
  31102. */
  31103. this.boundary = 0;
  31104. /**
  31105. * The item size. Derived uniforms will set this property to a data
  31106. * type specific value.
  31107. *
  31108. * @type {number}
  31109. */
  31110. this.itemSize = 0;
  31111. /**
  31112. * This property is set by {@link UniformsGroup} and marks
  31113. * the start position in the uniform buffer.
  31114. *
  31115. * @type {number}
  31116. */
  31117. this.offset = 0;
  31118. }
  31119. /**
  31120. * Sets the uniform's value.
  31121. *
  31122. * @param {any} value - The value to set.
  31123. */
  31124. setValue( value ) {
  31125. this.value = value;
  31126. }
  31127. /**
  31128. * Returns the uniform's value.
  31129. *
  31130. * @return {any} The value.
  31131. */
  31132. getValue() {
  31133. return this.value;
  31134. }
  31135. }
  31136. /**
  31137. * Represents a Number uniform.
  31138. *
  31139. * @private
  31140. * @augments Uniform
  31141. */
  31142. class NumberUniform extends Uniform {
  31143. /**
  31144. * Constructs a new Number uniform.
  31145. *
  31146. * @param {string} name - The uniform's name.
  31147. * @param {number} value - The uniform's value.
  31148. */
  31149. constructor( name, value = 0 ) {
  31150. super( name, value );
  31151. /**
  31152. * This flag can be used for type testing.
  31153. *
  31154. * @type {boolean}
  31155. * @readonly
  31156. * @default true
  31157. */
  31158. this.isNumberUniform = true;
  31159. this.boundary = 4;
  31160. this.itemSize = 1;
  31161. }
  31162. }
  31163. /**
  31164. * Represents a Vector2 uniform.
  31165. *
  31166. * @private
  31167. * @augments Uniform
  31168. */
  31169. class Vector2Uniform extends Uniform {
  31170. /**
  31171. * Constructs a new Number uniform.
  31172. *
  31173. * @param {string} name - The uniform's name.
  31174. * @param {Vector2} value - The uniform's value.
  31175. */
  31176. constructor( name, value = new Vector2() ) {
  31177. super( name, value );
  31178. /**
  31179. * This flag can be used for type testing.
  31180. *
  31181. * @type {boolean}
  31182. * @readonly
  31183. * @default true
  31184. */
  31185. this.isVector2Uniform = true;
  31186. this.boundary = 8;
  31187. this.itemSize = 2;
  31188. }
  31189. }
  31190. /**
  31191. * Represents a Vector3 uniform.
  31192. *
  31193. * @private
  31194. * @augments Uniform
  31195. */
  31196. class Vector3Uniform extends Uniform {
  31197. /**
  31198. * Constructs a new Number uniform.
  31199. *
  31200. * @param {string} name - The uniform's name.
  31201. * @param {Vector3} value - The uniform's value.
  31202. */
  31203. constructor( name, value = new Vector3() ) {
  31204. super( name, value );
  31205. /**
  31206. * This flag can be used for type testing.
  31207. *
  31208. * @type {boolean}
  31209. * @readonly
  31210. * @default true
  31211. */
  31212. this.isVector3Uniform = true;
  31213. this.boundary = 16;
  31214. this.itemSize = 3;
  31215. }
  31216. }
  31217. /**
  31218. * Represents a Vector4 uniform.
  31219. *
  31220. * @private
  31221. * @augments Uniform
  31222. */
  31223. class Vector4Uniform extends Uniform {
  31224. /**
  31225. * Constructs a new Number uniform.
  31226. *
  31227. * @param {string} name - The uniform's name.
  31228. * @param {Vector4} value - The uniform's value.
  31229. */
  31230. constructor( name, value = new Vector4() ) {
  31231. super( name, value );
  31232. /**
  31233. * This flag can be used for type testing.
  31234. *
  31235. * @type {boolean}
  31236. * @readonly
  31237. * @default true
  31238. */
  31239. this.isVector4Uniform = true;
  31240. this.boundary = 16;
  31241. this.itemSize = 4;
  31242. }
  31243. }
  31244. /**
  31245. * Represents a Color uniform.
  31246. *
  31247. * @private
  31248. * @augments Uniform
  31249. */
  31250. class ColorUniform extends Uniform {
  31251. /**
  31252. * Constructs a new Number uniform.
  31253. *
  31254. * @param {string} name - The uniform's name.
  31255. * @param {Color} value - The uniform's value.
  31256. */
  31257. constructor( name, value = new Color() ) {
  31258. super( name, value );
  31259. /**
  31260. * This flag can be used for type testing.
  31261. *
  31262. * @type {boolean}
  31263. * @readonly
  31264. * @default true
  31265. */
  31266. this.isColorUniform = true;
  31267. this.boundary = 16;
  31268. this.itemSize = 3;
  31269. }
  31270. }
  31271. /**
  31272. * Represents a Matrix2 uniform.
  31273. *
  31274. * @private
  31275. * @augments Uniform
  31276. */
  31277. class Matrix2Uniform extends Uniform {
  31278. /**
  31279. * Constructs a new Number uniform.
  31280. *
  31281. * @param {string} name - The uniform's name.
  31282. * @param {Matrix2} value - The uniform's value.
  31283. */
  31284. constructor( name, value = new Matrix2() ) {
  31285. super( name, value );
  31286. /**
  31287. * This flag can be used for type testing.
  31288. *
  31289. * @type {boolean}
  31290. * @readonly
  31291. * @default true
  31292. */
  31293. this.isMatrix2Uniform = true;
  31294. this.boundary = 8;
  31295. this.itemSize = 4;
  31296. }
  31297. }
  31298. /**
  31299. * Represents a Matrix3 uniform.
  31300. *
  31301. * @private
  31302. * @augments Uniform
  31303. */
  31304. class Matrix3Uniform extends Uniform {
  31305. /**
  31306. * Constructs a new Number uniform.
  31307. *
  31308. * @param {string} name - The uniform's name.
  31309. * @param {Matrix3} value - The uniform's value.
  31310. */
  31311. constructor( name, value = new Matrix3() ) {
  31312. super( name, value );
  31313. /**
  31314. * This flag can be used for type testing.
  31315. *
  31316. * @type {boolean}
  31317. * @readonly
  31318. * @default true
  31319. */
  31320. this.isMatrix3Uniform = true;
  31321. this.boundary = 48;
  31322. this.itemSize = 12;
  31323. }
  31324. }
  31325. /**
  31326. * Represents a Matrix4 uniform.
  31327. *
  31328. * @private
  31329. * @augments Uniform
  31330. */
  31331. class Matrix4Uniform extends Uniform {
  31332. /**
  31333. * Constructs a new Number uniform.
  31334. *
  31335. * @param {string} name - The uniform's name.
  31336. * @param {Matrix4} value - The uniform's value.
  31337. */
  31338. constructor( name, value = new Matrix4() ) {
  31339. super( name, value );
  31340. /**
  31341. * This flag can be used for type testing.
  31342. *
  31343. * @type {boolean}
  31344. * @readonly
  31345. * @default true
  31346. */
  31347. this.isMatrix4Uniform = true;
  31348. this.boundary = 64;
  31349. this.itemSize = 16;
  31350. }
  31351. }
  31352. /**
  31353. * A special form of Number uniform binding type.
  31354. * It's value is managed by a node object.
  31355. *
  31356. * @private
  31357. * @augments NumberUniform
  31358. */
  31359. class NumberNodeUniform extends NumberUniform {
  31360. /**
  31361. * Constructs a new node-based Number uniform.
  31362. *
  31363. * @param {NodeUniform} nodeUniform - The node uniform.
  31364. */
  31365. constructor( nodeUniform ) {
  31366. super( nodeUniform.name, nodeUniform.value );
  31367. /**
  31368. * The node uniform.
  31369. *
  31370. * @type {NodeUniform}
  31371. */
  31372. this.nodeUniform = nodeUniform;
  31373. }
  31374. /**
  31375. * Overwritten to return the value of the node uniform.
  31376. *
  31377. * @return {number} The value.
  31378. */
  31379. getValue() {
  31380. return this.nodeUniform.value;
  31381. }
  31382. /**
  31383. * Returns the node uniform data type.
  31384. *
  31385. * @return {string} The data type.
  31386. */
  31387. getType() {
  31388. return this.nodeUniform.type;
  31389. }
  31390. }
  31391. /**
  31392. * A special form of Vector2 uniform binding type.
  31393. * It's value is managed by a node object.
  31394. *
  31395. * @private
  31396. * @augments Vector2Uniform
  31397. */
  31398. class Vector2NodeUniform extends Vector2Uniform {
  31399. /**
  31400. * Constructs a new node-based Vector2 uniform.
  31401. *
  31402. * @param {NodeUniform} nodeUniform - The node uniform.
  31403. */
  31404. constructor( nodeUniform ) {
  31405. super( nodeUniform.name, nodeUniform.value );
  31406. /**
  31407. * The node uniform.
  31408. *
  31409. * @type {NodeUniform}
  31410. */
  31411. this.nodeUniform = nodeUniform;
  31412. }
  31413. /**
  31414. * Overwritten to return the value of the node uniform.
  31415. *
  31416. * @return {Vector2} The value.
  31417. */
  31418. getValue() {
  31419. return this.nodeUniform.value;
  31420. }
  31421. /**
  31422. * Returns the node uniform data type.
  31423. *
  31424. * @return {string} The data type.
  31425. */
  31426. getType() {
  31427. return this.nodeUniform.type;
  31428. }
  31429. }
  31430. /**
  31431. * A special form of Vector3 uniform binding type.
  31432. * It's value is managed by a node object.
  31433. *
  31434. * @private
  31435. * @augments Vector3Uniform
  31436. */
  31437. class Vector3NodeUniform extends Vector3Uniform {
  31438. /**
  31439. * Constructs a new node-based Vector3 uniform.
  31440. *
  31441. * @param {NodeUniform} nodeUniform - The node uniform.
  31442. */
  31443. constructor( nodeUniform ) {
  31444. super( nodeUniform.name, nodeUniform.value );
  31445. /**
  31446. * The node uniform.
  31447. *
  31448. * @type {NodeUniform}
  31449. */
  31450. this.nodeUniform = nodeUniform;
  31451. }
  31452. /**
  31453. * Overwritten to return the value of the node uniform.
  31454. *
  31455. * @return {Vector3} The value.
  31456. */
  31457. getValue() {
  31458. return this.nodeUniform.value;
  31459. }
  31460. /**
  31461. * Returns the node uniform data type.
  31462. *
  31463. * @return {string} The data type.
  31464. */
  31465. getType() {
  31466. return this.nodeUniform.type;
  31467. }
  31468. }
  31469. /**
  31470. * A special form of Vector4 uniform binding type.
  31471. * It's value is managed by a node object.
  31472. *
  31473. * @private
  31474. * @augments Vector4Uniform
  31475. */
  31476. class Vector4NodeUniform extends Vector4Uniform {
  31477. /**
  31478. * Constructs a new node-based Vector4 uniform.
  31479. *
  31480. * @param {NodeUniform} nodeUniform - The node uniform.
  31481. */
  31482. constructor( nodeUniform ) {
  31483. super( nodeUniform.name, nodeUniform.value );
  31484. /**
  31485. * The node uniform.
  31486. *
  31487. * @type {NodeUniform}
  31488. */
  31489. this.nodeUniform = nodeUniform;
  31490. }
  31491. /**
  31492. * Overwritten to return the value of the node uniform.
  31493. *
  31494. * @return {Vector4} The value.
  31495. */
  31496. getValue() {
  31497. return this.nodeUniform.value;
  31498. }
  31499. /**
  31500. * Returns the node uniform data type.
  31501. *
  31502. * @return {string} The data type.
  31503. */
  31504. getType() {
  31505. return this.nodeUniform.type;
  31506. }
  31507. }
  31508. /**
  31509. * A special form of Color uniform binding type.
  31510. * It's value is managed by a node object.
  31511. *
  31512. * @private
  31513. * @augments ColorUniform
  31514. */
  31515. class ColorNodeUniform extends ColorUniform {
  31516. /**
  31517. * Constructs a new node-based Color uniform.
  31518. *
  31519. * @param {NodeUniform} nodeUniform - The node uniform.
  31520. */
  31521. constructor( nodeUniform ) {
  31522. super( nodeUniform.name, nodeUniform.value );
  31523. /**
  31524. * The node uniform.
  31525. *
  31526. * @type {NodeUniform}
  31527. */
  31528. this.nodeUniform = nodeUniform;
  31529. }
  31530. /**
  31531. * Overwritten to return the value of the node uniform.
  31532. *
  31533. * @return {Color} The value.
  31534. */
  31535. getValue() {
  31536. return this.nodeUniform.value;
  31537. }
  31538. /**
  31539. * Returns the node uniform data type.
  31540. *
  31541. * @return {string} The data type.
  31542. */
  31543. getType() {
  31544. return this.nodeUniform.type;
  31545. }
  31546. }
  31547. /**
  31548. * A special form of Matrix2 uniform binding type.
  31549. * It's value is managed by a node object.
  31550. *
  31551. * @private
  31552. * @augments Matrix2Uniform
  31553. */
  31554. class Matrix2NodeUniform extends Matrix2Uniform {
  31555. /**
  31556. * Constructs a new node-based Matrix2 uniform.
  31557. *
  31558. * @param {NodeUniform} nodeUniform - The node uniform.
  31559. */
  31560. constructor( nodeUniform ) {
  31561. super( nodeUniform.name, nodeUniform.value );
  31562. /**
  31563. * The node uniform.
  31564. *
  31565. * @type {NodeUniform}
  31566. */
  31567. this.nodeUniform = nodeUniform;
  31568. }
  31569. /**
  31570. * Overwritten to return the value of the node uniform.
  31571. *
  31572. * @return {Matrix2} The value.
  31573. */
  31574. getValue() {
  31575. return this.nodeUniform.value;
  31576. }
  31577. /**
  31578. * Returns the node uniform data type.
  31579. *
  31580. * @return {string} The data type.
  31581. */
  31582. getType() {
  31583. return this.nodeUniform.type;
  31584. }
  31585. }
  31586. /**
  31587. * A special form of Matrix3 uniform binding type.
  31588. * It's value is managed by a node object.
  31589. *
  31590. * @private
  31591. * @augments Matrix3Uniform
  31592. */
  31593. class Matrix3NodeUniform extends Matrix3Uniform {
  31594. /**
  31595. * Constructs a new node-based Matrix3 uniform.
  31596. *
  31597. * @param {NodeUniform} nodeUniform - The node uniform.
  31598. */
  31599. constructor( nodeUniform ) {
  31600. super( nodeUniform.name, nodeUniform.value );
  31601. /**
  31602. * The node uniform.
  31603. *
  31604. * @type {NodeUniform}
  31605. */
  31606. this.nodeUniform = nodeUniform;
  31607. }
  31608. /**
  31609. * Overwritten to return the value of the node uniform.
  31610. *
  31611. * @return {Matrix3} The value.
  31612. */
  31613. getValue() {
  31614. return this.nodeUniform.value;
  31615. }
  31616. /**
  31617. * Returns the node uniform data type.
  31618. *
  31619. * @return {string} The data type.
  31620. */
  31621. getType() {
  31622. return this.nodeUniform.type;
  31623. }
  31624. }
  31625. /**
  31626. * A special form of Matrix4 uniform binding type.
  31627. * It's value is managed by a node object.
  31628. *
  31629. * @private
  31630. * @augments Matrix4Uniform
  31631. */
  31632. class Matrix4NodeUniform extends Matrix4Uniform {
  31633. /**
  31634. * Constructs a new node-based Matrix4 uniform.
  31635. *
  31636. * @param {NodeUniform} nodeUniform - The node uniform.
  31637. */
  31638. constructor( nodeUniform ) {
  31639. super( nodeUniform.name, nodeUniform.value );
  31640. /**
  31641. * The node uniform.
  31642. *
  31643. * @type {NodeUniform}
  31644. */
  31645. this.nodeUniform = nodeUniform;
  31646. }
  31647. /**
  31648. * Overwritten to return the value of the node uniform.
  31649. *
  31650. * @return {Matrix4} The value.
  31651. */
  31652. getValue() {
  31653. return this.nodeUniform.value;
  31654. }
  31655. /**
  31656. * Returns the node uniform data type.
  31657. *
  31658. * @return {string} The data type.
  31659. */
  31660. getType() {
  31661. return this.nodeUniform.type;
  31662. }
  31663. }
  31664. const rendererCache = new WeakMap();
  31665. const typeFromArray = new Map( [
  31666. [ Int8Array, 'int' ],
  31667. [ Int16Array, 'int' ],
  31668. [ Int32Array, 'int' ],
  31669. [ Uint8Array, 'uint' ],
  31670. [ Uint16Array, 'uint' ],
  31671. [ Uint32Array, 'uint' ],
  31672. [ Float32Array, 'float' ]
  31673. ] );
  31674. const toFloat = ( value ) => {
  31675. if ( /e/g.test( value ) ) {
  31676. return String( value ).replace( /\+/g, '' );
  31677. } else {
  31678. value = Number( value );
  31679. return value + ( value % 1 ? '' : '.0' );
  31680. }
  31681. };
  31682. /**
  31683. * Base class for builders which generate a shader program based
  31684. * on a 3D object and its node material definition.
  31685. */
  31686. class NodeBuilder {
  31687. /**
  31688. * Constructs a new node builder.
  31689. *
  31690. * @param {Object3D} object - The 3D object.
  31691. * @param {Renderer} renderer - The current renderer.
  31692. * @param {NodeParser} parser - A reference to a node parser.
  31693. */
  31694. constructor( object, renderer, parser ) {
  31695. /**
  31696. * The 3D object.
  31697. *
  31698. * @type {Object3D}
  31699. */
  31700. this.object = object;
  31701. /**
  31702. * The material of the 3D object.
  31703. *
  31704. * @type {?Material}
  31705. */
  31706. this.material = ( object && object.material ) || null;
  31707. /**
  31708. * The geometry of the 3D object.
  31709. *
  31710. * @type {?BufferGeometry}
  31711. */
  31712. this.geometry = ( object && object.geometry ) || null;
  31713. /**
  31714. * The current renderer.
  31715. *
  31716. * @type {Renderer}
  31717. */
  31718. this.renderer = renderer;
  31719. /**
  31720. * A reference to a node parser.
  31721. *
  31722. * @type {NodeParser}
  31723. */
  31724. this.parser = parser;
  31725. /**
  31726. * The scene the 3D object belongs to.
  31727. *
  31728. * @type {?Scene}
  31729. * @default null
  31730. */
  31731. this.scene = null;
  31732. /**
  31733. * The camera the 3D object is rendered with.
  31734. *
  31735. * @type {?Camera}
  31736. * @default null
  31737. */
  31738. this.camera = null;
  31739. /**
  31740. * A list of all nodes the builder is processing
  31741. * for this 3D object.
  31742. *
  31743. * @type {Array<Node>}
  31744. */
  31745. this.nodes = [];
  31746. /**
  31747. * A list of all sequential nodes.
  31748. *
  31749. * @type {Array<Node>}
  31750. */
  31751. this.sequentialNodes = [];
  31752. /**
  31753. * A list of all nodes which {@link Node#update} method should be executed.
  31754. *
  31755. * @type {Array<Node>}
  31756. */
  31757. this.updateNodes = [];
  31758. /**
  31759. * A list of all nodes which {@link Node#updateBefore} method should be executed.
  31760. *
  31761. * @type {Array<Node>}
  31762. */
  31763. this.updateBeforeNodes = [];
  31764. /**
  31765. * A list of all nodes which {@link Node#updateAfter} method should be executed.
  31766. *
  31767. * @type {Array<Node>}
  31768. */
  31769. this.updateAfterNodes = [];
  31770. /**
  31771. * A dictionary that assigns each node to a unique hash.
  31772. *
  31773. * @type {Object<number,Node>}
  31774. */
  31775. this.hashNodes = {};
  31776. /**
  31777. * A reference to a node material observer.
  31778. *
  31779. * @type {?NodeMaterialObserver}
  31780. * @default null
  31781. */
  31782. this.observer = null;
  31783. /**
  31784. * A reference to the current lights node.
  31785. *
  31786. * @type {?LightsNode}
  31787. * @default null
  31788. */
  31789. this.lightsNode = null;
  31790. /**
  31791. * A reference to the current environment node.
  31792. *
  31793. * @type {?Node}
  31794. * @default null
  31795. */
  31796. this.environmentNode = null;
  31797. /**
  31798. * A reference to the current fog node.
  31799. *
  31800. * @type {?FogNode}
  31801. * @default null
  31802. */
  31803. this.fogNode = null;
  31804. /**
  31805. * The current clipping context.
  31806. *
  31807. * @type {?ClippingContext}
  31808. */
  31809. this.clippingContext = null;
  31810. /**
  31811. * The generated vertex shader.
  31812. *
  31813. * @type {?string}
  31814. */
  31815. this.vertexShader = null;
  31816. /**
  31817. * The generated fragment shader.
  31818. *
  31819. * @type {?string}
  31820. */
  31821. this.fragmentShader = null;
  31822. /**
  31823. * The generated compute shader.
  31824. *
  31825. * @type {?string}
  31826. */
  31827. this.computeShader = null;
  31828. /**
  31829. * Nodes used in the primary flow of code generation.
  31830. *
  31831. * @type {Object<string,Array<Node>>}
  31832. */
  31833. this.flowNodes = { vertex: [], fragment: [], compute: [] };
  31834. /**
  31835. * Nodes code from `.flowNodes`.
  31836. *
  31837. * @type {Object<string,string>}
  31838. */
  31839. this.flowCode = { vertex: '', fragment: '', compute: '' };
  31840. /**
  31841. * This dictionary holds the node uniforms of the builder.
  31842. * The uniforms are maintained in an array for each shader stage.
  31843. *
  31844. * @type {Object}
  31845. */
  31846. this.uniforms = { vertex: [], fragment: [], compute: [], index: 0 };
  31847. /**
  31848. * This dictionary holds the output structs of the builder.
  31849. * The structs are maintained in an array for each shader stage.
  31850. *
  31851. * @type {Object}
  31852. */
  31853. this.structs = { vertex: [], fragment: [], compute: [], index: 0 };
  31854. /**
  31855. * This dictionary holds the bindings for each shader stage.
  31856. *
  31857. * @type {Object}
  31858. */
  31859. this.bindings = { vertex: {}, fragment: {}, compute: {} };
  31860. /**
  31861. * This dictionary maintains the binding indices per bind group.
  31862. *
  31863. * @type {Object}
  31864. */
  31865. this.bindingsIndexes = {};
  31866. /**
  31867. * Reference to the array of bind groups.
  31868. *
  31869. * @type {?Array<BindGroup>}
  31870. */
  31871. this.bindGroups = null;
  31872. /**
  31873. * This array holds the node attributes of this builder
  31874. * created via {@link AttributeNode}.
  31875. *
  31876. * @type {Array<NodeAttribute>}
  31877. */
  31878. this.attributes = [];
  31879. /**
  31880. * This array holds the node attributes of this builder
  31881. * created via {@link BufferAttributeNode}.
  31882. *
  31883. * @type {Array<NodeAttribute>}
  31884. */
  31885. this.bufferAttributes = [];
  31886. /**
  31887. * This array holds the node varyings of this builder.
  31888. *
  31889. * @type {Array<NodeVarying>}
  31890. */
  31891. this.varyings = [];
  31892. /**
  31893. * This dictionary holds the (native) node codes of this builder.
  31894. * The codes are maintained in an array for each shader stage.
  31895. *
  31896. * @type {Object<string,Array<NodeCode>>}
  31897. */
  31898. this.codes = {};
  31899. /**
  31900. * This dictionary holds the node variables of this builder.
  31901. * The variables are maintained in an array for each shader stage.
  31902. * This dictionary is also used to count the number of variables
  31903. * according to their type (const, vars).
  31904. *
  31905. * @type {Object<string,Array<NodeVar>|number>}
  31906. */
  31907. this.vars = {};
  31908. /**
  31909. * This dictionary holds the declarations for each shader stage.
  31910. *
  31911. * @type {Object}
  31912. */
  31913. this.declarations = {};
  31914. /**
  31915. * Current code flow.
  31916. * All code generated in this stack will be stored in `.flow`.
  31917. *
  31918. * @type {{code: string}}
  31919. */
  31920. this.flow = { code: '' };
  31921. /**
  31922. * A chain of nodes.
  31923. * Used to check recursive calls in node-graph.
  31924. *
  31925. * @type {Array<Node>}
  31926. */
  31927. this.chaining = [];
  31928. /**
  31929. * The current stack.
  31930. * This reflects the current process in the code block hierarchy,
  31931. * it is useful to know if the current process is inside a conditional for example.
  31932. *
  31933. * @type {StackNode}
  31934. */
  31935. this.stack = stack();
  31936. /**
  31937. * List of stack nodes.
  31938. * The current stack hierarchy is stored in an array.
  31939. *
  31940. * @type {Array<StackNode>}
  31941. */
  31942. this.stacks = [];
  31943. /**
  31944. * A tab value. Used for shader string generation.
  31945. *
  31946. * @type {string}
  31947. * @default '\t'
  31948. */
  31949. this.tab = '\t';
  31950. /**
  31951. * Reference to the current function node.
  31952. *
  31953. * @type {?FunctionNode}
  31954. * @default null
  31955. */
  31956. this.currentFunctionNode = null;
  31957. /**
  31958. * The builder's context.
  31959. *
  31960. * @type {Object}
  31961. */
  31962. this.context = {
  31963. material: this.material
  31964. };
  31965. /**
  31966. * The builder's cache.
  31967. *
  31968. * @type {NodeCache}
  31969. */
  31970. this.cache = new NodeCache();
  31971. /**
  31972. * Since the {@link NodeBuilder#cache} might be temporarily
  31973. * overwritten by other caches, this member retains the reference
  31974. * to the builder's own cache.
  31975. *
  31976. * @type {NodeCache}
  31977. * @default this.cache
  31978. */
  31979. this.globalCache = this.cache;
  31980. this.flowsData = new WeakMap();
  31981. /**
  31982. * The current shader stage.
  31983. *
  31984. * @type {?('vertex'|'fragment'|'compute'|'any')}
  31985. */
  31986. this.shaderStage = null;
  31987. /**
  31988. * The current build stage.
  31989. *
  31990. * @type {?('setup'|'analyze'|'generate')}
  31991. */
  31992. this.buildStage = null;
  31993. }
  31994. /**
  31995. * Returns the bind groups of the current renderer.
  31996. *
  31997. * @return {ChainMap} The cache.
  31998. */
  31999. getBindGroupsCache() {
  32000. let bindGroupsCache = rendererCache.get( this.renderer );
  32001. if ( bindGroupsCache === undefined ) {
  32002. bindGroupsCache = new ChainMap();
  32003. rendererCache.set( this.renderer, bindGroupsCache );
  32004. }
  32005. return bindGroupsCache;
  32006. }
  32007. /**
  32008. * Factory method for creating an instance of {@link RenderTarget} with the given
  32009. * dimensions and options.
  32010. *
  32011. * @param {number} width - The width of the render target.
  32012. * @param {number} height - The height of the render target.
  32013. * @param {Object} options - The options of the render target.
  32014. * @return {RenderTarget} The render target.
  32015. */
  32016. createRenderTarget( width, height, options ) {
  32017. return new RenderTarget( width, height, options );
  32018. }
  32019. /**
  32020. * Factory method for creating an instance of {@link CubeRenderTarget} with the given
  32021. * dimensions and options.
  32022. *
  32023. * @param {number} size - The size of the cube render target.
  32024. * @param {Object} options - The options of the cube render target.
  32025. * @return {CubeRenderTarget} The cube render target.
  32026. */
  32027. createCubeRenderTarget( size, options ) {
  32028. return new CubeRenderTarget( size, options );
  32029. }
  32030. /**
  32031. * Whether the given node is included in the internal array of nodes or not.
  32032. *
  32033. * @param {Node} node - The node to test.
  32034. * @return {boolean} Whether the given node is included in the internal array of nodes or not.
  32035. */
  32036. includes( node ) {
  32037. return this.nodes.includes( node );
  32038. }
  32039. /**
  32040. * Returns the output struct name which is required by
  32041. * {@link OutputStructNode}.
  32042. *
  32043. * @abstract
  32044. * @return {string} The name of the output struct.
  32045. */
  32046. getOutputStructName() {}
  32047. /**
  32048. * Returns a bind group for the given group name and binding.
  32049. *
  32050. * @private
  32051. * @param {string} groupName - The group name.
  32052. * @param {Array<NodeUniformsGroup>} bindings - List of bindings.
  32053. * @return {BindGroup} The bind group
  32054. */
  32055. _getBindGroup( groupName, bindings ) {
  32056. const bindGroupsCache = this.getBindGroupsCache();
  32057. //
  32058. const bindingsArray = [];
  32059. let sharedGroup = true;
  32060. for ( const binding of bindings ) {
  32061. bindingsArray.push( binding );
  32062. sharedGroup = sharedGroup && binding.groupNode.shared !== true;
  32063. }
  32064. //
  32065. let bindGroup;
  32066. if ( sharedGroup ) {
  32067. bindGroup = bindGroupsCache.get( bindingsArray );
  32068. if ( bindGroup === undefined ) {
  32069. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  32070. bindGroupsCache.set( bindingsArray, bindGroup );
  32071. }
  32072. } else {
  32073. bindGroup = new BindGroup( groupName, bindingsArray, this.bindingsIndexes[ groupName ].group, bindingsArray );
  32074. }
  32075. return bindGroup;
  32076. }
  32077. /**
  32078. * Returns an array of node uniform groups for the given group name and shader stage.
  32079. *
  32080. * @param {string} groupName - The group name.
  32081. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32082. * @return {Array<NodeUniformsGroup>} The array of node uniform groups.
  32083. */
  32084. getBindGroupArray( groupName, shaderStage ) {
  32085. const bindings = this.bindings[ shaderStage ];
  32086. let bindGroup = bindings[ groupName ];
  32087. if ( bindGroup === undefined ) {
  32088. if ( this.bindingsIndexes[ groupName ] === undefined ) {
  32089. this.bindingsIndexes[ groupName ] = { binding: 0, group: Object.keys( this.bindingsIndexes ).length };
  32090. }
  32091. bindings[ groupName ] = bindGroup = [];
  32092. }
  32093. return bindGroup;
  32094. }
  32095. /**
  32096. * Returns a list bindings of all shader stages separated by groups.
  32097. *
  32098. * @return {Array<BindGroup>} The list of bindings.
  32099. */
  32100. getBindings() {
  32101. let bindingsGroups = this.bindGroups;
  32102. if ( bindingsGroups === null ) {
  32103. const groups = {};
  32104. const bindings = this.bindings;
  32105. for ( const shaderStage of shaderStages ) {
  32106. for ( const groupName in bindings[ shaderStage ] ) {
  32107. const uniforms = bindings[ shaderStage ][ groupName ];
  32108. const groupUniforms = groups[ groupName ] || ( groups[ groupName ] = [] );
  32109. groupUniforms.push( ...uniforms );
  32110. }
  32111. }
  32112. bindingsGroups = [];
  32113. for ( const groupName in groups ) {
  32114. const group = groups[ groupName ];
  32115. const bindingsGroup = this._getBindGroup( groupName, group );
  32116. bindingsGroups.push( bindingsGroup );
  32117. }
  32118. this.bindGroups = bindingsGroups;
  32119. }
  32120. return bindingsGroups;
  32121. }
  32122. /**
  32123. * Sorts the bind groups and updates {@link NodeBuilder#bindingsIndexes}.
  32124. */
  32125. sortBindingGroups() {
  32126. const bindingsGroups = this.getBindings();
  32127. bindingsGroups.sort( ( a, b ) => ( a.bindings[ 0 ].groupNode.order - b.bindings[ 0 ].groupNode.order ) );
  32128. for ( let i = 0; i < bindingsGroups.length; i ++ ) {
  32129. const bindingGroup = bindingsGroups[ i ];
  32130. this.bindingsIndexes[ bindingGroup.name ].group = i;
  32131. bindingGroup.index = i;
  32132. }
  32133. }
  32134. /**
  32135. * The builder maintains each node in a hash-based dictionary.
  32136. * This method sets the given node (value) with the given hash (key) into this dictionary.
  32137. *
  32138. * @param {Node} node - The node to add.
  32139. * @param {number} hash - The hash of the node.
  32140. */
  32141. setHashNode( node, hash ) {
  32142. this.hashNodes[ hash ] = node;
  32143. }
  32144. /**
  32145. * Adds a node to this builder.
  32146. *
  32147. * @param {Node} node - The node to add.
  32148. */
  32149. addNode( node ) {
  32150. if ( this.nodes.includes( node ) === false ) {
  32151. this.nodes.push( node );
  32152. this.setHashNode( node, node.getHash( this ) );
  32153. }
  32154. }
  32155. /**
  32156. * It is used to add Nodes that will be used as FRAME and RENDER events,
  32157. * and need to follow a certain sequence in the calls to work correctly.
  32158. * This function should be called after 'setup()' in the 'build()' process to ensure that the child nodes are processed first.
  32159. *
  32160. * @param {Node} node - The node to add.
  32161. */
  32162. addSequentialNode( node ) {
  32163. if ( this.sequentialNodes.includes( node ) === false ) {
  32164. this.sequentialNodes.push( node );
  32165. }
  32166. }
  32167. /**
  32168. * Checks the update types of nodes
  32169. */
  32170. buildUpdateNodes() {
  32171. for ( const node of this.nodes ) {
  32172. const updateType = node.getUpdateType();
  32173. if ( updateType !== NodeUpdateType.NONE ) {
  32174. this.updateNodes.push( node.getSelf() );
  32175. }
  32176. }
  32177. for ( const node of this.sequentialNodes ) {
  32178. const updateBeforeType = node.getUpdateBeforeType();
  32179. const updateAfterType = node.getUpdateAfterType();
  32180. if ( updateBeforeType !== NodeUpdateType.NONE ) {
  32181. this.updateBeforeNodes.push( node.getSelf() );
  32182. }
  32183. if ( updateAfterType !== NodeUpdateType.NONE ) {
  32184. this.updateAfterNodes.push( node.getSelf() );
  32185. }
  32186. }
  32187. }
  32188. /**
  32189. * A reference the current node which is the
  32190. * last node in the chain of nodes.
  32191. *
  32192. * @type {Node}
  32193. */
  32194. get currentNode() {
  32195. return this.chaining[ this.chaining.length - 1 ];
  32196. }
  32197. /**
  32198. * Whether the given texture is filtered or not.
  32199. *
  32200. * @param {Texture} texture - The texture to check.
  32201. * @return {boolean} Whether the given texture is filtered or not.
  32202. */
  32203. isFilteredTexture( texture ) {
  32204. return ( texture.magFilter === LinearFilter || texture.magFilter === LinearMipmapNearestFilter || texture.magFilter === NearestMipmapLinearFilter || texture.magFilter === LinearMipmapLinearFilter ||
  32205. texture.minFilter === LinearFilter || texture.minFilter === LinearMipmapNearestFilter || texture.minFilter === NearestMipmapLinearFilter || texture.minFilter === LinearMipmapLinearFilter );
  32206. }
  32207. /**
  32208. * Adds the given node to the internal node chain.
  32209. * This is used to check recursive calls in node-graph.
  32210. *
  32211. * @param {Node} node - The node to add.
  32212. */
  32213. addChain( node ) {
  32214. /*
  32215. if ( this.chaining.indexOf( node ) !== - 1 ) {
  32216. console.warn( 'Recursive node: ', node );
  32217. }
  32218. */
  32219. this.chaining.push( node );
  32220. }
  32221. /**
  32222. * Removes the given node from the internal node chain.
  32223. *
  32224. * @param {Node} node - The node to remove.
  32225. */
  32226. removeChain( node ) {
  32227. const lastChain = this.chaining.pop();
  32228. if ( lastChain !== node ) {
  32229. throw new Error( 'NodeBuilder: Invalid node chaining!' );
  32230. }
  32231. }
  32232. /**
  32233. * Returns the native shader method name for a given generic name. E.g.
  32234. * the method name `textureDimensions` matches the WGSL name but must be
  32235. * resolved to `textureSize` in GLSL.
  32236. *
  32237. * @abstract
  32238. * @param {string} method - The method name to resolve.
  32239. * @return {string} The resolved method name.
  32240. */
  32241. getMethod( method ) {
  32242. return method;
  32243. }
  32244. /**
  32245. * Returns a node for the given hash, see {@link NodeBuilder#setHashNode}.
  32246. *
  32247. * @param {number} hash - The hash of the node.
  32248. * @return {Node} The found node.
  32249. */
  32250. getNodeFromHash( hash ) {
  32251. return this.hashNodes[ hash ];
  32252. }
  32253. /**
  32254. * Adds the Node to a target flow so that it can generate code in the 'generate' process.
  32255. *
  32256. * @param {('vertex'|'fragment'|'compute')} shaderStage - The shader stage.
  32257. * @param {Node} node - The node to add.
  32258. * @return {Node} The node.
  32259. */
  32260. addFlow( shaderStage, node ) {
  32261. this.flowNodes[ shaderStage ].push( node );
  32262. return node;
  32263. }
  32264. /**
  32265. * Sets builder's context.
  32266. *
  32267. * @param {Object} context - The context to set.
  32268. */
  32269. setContext( context ) {
  32270. this.context = context;
  32271. }
  32272. /**
  32273. * Returns the builder's current context.
  32274. *
  32275. * @return {Object} The builder's current context.
  32276. */
  32277. getContext() {
  32278. return this.context;
  32279. }
  32280. /**
  32281. * Gets a context used in shader construction that can be shared across different materials.
  32282. * This is necessary since the renderer cache can reuse shaders generated in one material and use them in another.
  32283. *
  32284. * @return {Object} The builder's current context without material.
  32285. */
  32286. getSharedContext() {
  32287. ({ ...this.context });
  32288. return this.context;
  32289. }
  32290. /**
  32291. * Sets builder's cache.
  32292. *
  32293. * @param {NodeCache} cache - The cache to set.
  32294. */
  32295. setCache( cache ) {
  32296. this.cache = cache;
  32297. }
  32298. /**
  32299. * Returns the builder's current cache.
  32300. *
  32301. * @return {NodeCache} The builder's current cache.
  32302. */
  32303. getCache() {
  32304. return this.cache;
  32305. }
  32306. /**
  32307. * Returns a cache for the given node.
  32308. *
  32309. * @param {Node} node - The node.
  32310. * @param {boolean} [parent=true] - Whether this node refers to a shared parent cache or not.
  32311. * @return {NodeCache} The cache.
  32312. */
  32313. getCacheFromNode( node, parent = true ) {
  32314. const data = this.getDataFromNode( node );
  32315. if ( data.cache === undefined ) data.cache = new NodeCache( parent ? this.getCache() : null );
  32316. return data.cache;
  32317. }
  32318. /**
  32319. * Whether the requested feature is available or not.
  32320. *
  32321. * @abstract
  32322. * @param {string} name - The requested feature.
  32323. * @return {boolean} Whether the requested feature is supported or not.
  32324. */
  32325. isAvailable( /*name*/ ) {
  32326. return false;
  32327. }
  32328. /**
  32329. * Returns the vertexIndex input variable as a native shader string.
  32330. *
  32331. * @abstract
  32332. * @return {string} The instanceIndex shader string.
  32333. */
  32334. getVertexIndex() {
  32335. console.warn( 'Abstract function.' );
  32336. }
  32337. /**
  32338. * Returns the instanceIndex input variable as a native shader string.
  32339. *
  32340. * @abstract
  32341. * @return {string} The instanceIndex shader string.
  32342. */
  32343. getInstanceIndex() {
  32344. console.warn( 'Abstract function.' );
  32345. }
  32346. /**
  32347. * Returns the drawIndex input variable as a native shader string.
  32348. * Only relevant for WebGL and its `WEBGL_multi_draw` extension.
  32349. *
  32350. * @abstract
  32351. * @return {?string} The drawIndex shader string.
  32352. */
  32353. getDrawIndex() {
  32354. console.warn( 'Abstract function.' );
  32355. }
  32356. /**
  32357. * Returns the frontFacing input variable as a native shader string.
  32358. *
  32359. * @abstract
  32360. * @return {string} The frontFacing shader string.
  32361. */
  32362. getFrontFacing() {
  32363. console.warn( 'Abstract function.' );
  32364. }
  32365. /**
  32366. * Returns the fragCoord input variable as a native shader string.
  32367. *
  32368. * @abstract
  32369. * @return {string} The fragCoord shader string.
  32370. */
  32371. getFragCoord() {
  32372. console.warn( 'Abstract function.' );
  32373. }
  32374. /**
  32375. * Whether to flip texture data along its vertical axis or not. WebGL needs
  32376. * this method evaluate to `true`, WebGPU to `false`.
  32377. *
  32378. * @abstract
  32379. * @return {boolean} Whether to flip texture data along its vertical axis or not.
  32380. */
  32381. isFlipY() {
  32382. return false;
  32383. }
  32384. /**
  32385. * Calling this method increases the usage count for the given node by one.
  32386. *
  32387. * @param {Node} node - The node to increase the usage count for.
  32388. * @return {number} The updated usage count.
  32389. */
  32390. increaseUsage( node ) {
  32391. const nodeData = this.getDataFromNode( node );
  32392. nodeData.usageCount = nodeData.usageCount === undefined ? 1 : nodeData.usageCount + 1;
  32393. return nodeData.usageCount;
  32394. }
  32395. /**
  32396. * Generates a texture sample shader string for the given texture data.
  32397. *
  32398. * @abstract
  32399. * @param {Texture} texture - The texture.
  32400. * @param {string} textureProperty - The texture property name.
  32401. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  32402. * @return {string} The generated shader string.
  32403. */
  32404. generateTexture( /* texture, textureProperty, uvSnippet */ ) {
  32405. console.warn( 'Abstract function.' );
  32406. }
  32407. /**
  32408. * Generates a texture LOD shader string for the given texture data.
  32409. *
  32410. * @abstract
  32411. * @param {Texture} texture - The texture.
  32412. * @param {string} textureProperty - The texture property name.
  32413. * @param {string} uvSnippet - Snippet defining the texture coordinates.
  32414. * @param {?string} depthSnippet - Snippet defining the 0-based texture array index to sample.
  32415. * @param {string} levelSnippet - Snippet defining the mip level.
  32416. * @return {string} The generated shader string.
  32417. */
  32418. generateTextureLod( /* texture, textureProperty, uvSnippet, depthSnippet, levelSnippet */ ) {
  32419. console.warn( 'Abstract function.' );
  32420. }
  32421. /**
  32422. * Generates the array declaration string.
  32423. *
  32424. * @param {string} type - The type.
  32425. * @param {?number} [count] - The count.
  32426. * @return {string} The generated value as a shader string.
  32427. */
  32428. generateArrayDeclaration( type, count ) {
  32429. return this.getType( type ) + '[ ' + count + ' ]';
  32430. }
  32431. /**
  32432. * Generates the array shader string for the given type and value.
  32433. *
  32434. * @param {string} type - The type.
  32435. * @param {?number} [count] - The count.
  32436. * @param {?Array<Node>} [values=null] - The default values.
  32437. * @return {string} The generated value as a shader string.
  32438. */
  32439. generateArray( type, count, values = null ) {
  32440. let snippet = this.generateArrayDeclaration( type, count ) + '( ';
  32441. for ( let i = 0; i < count; i ++ ) {
  32442. const value = values ? values[ i ] : null;
  32443. if ( value !== null ) {
  32444. snippet += value.build( this, type );
  32445. } else {
  32446. snippet += this.generateConst( type );
  32447. }
  32448. if ( i < count - 1 ) snippet += ', ';
  32449. }
  32450. snippet += ' )';
  32451. return snippet;
  32452. }
  32453. /**
  32454. * Generates the struct shader string.
  32455. *
  32456. * @param {string} type - The type.
  32457. * @param {Array<Object>} [membersLayout] - The count.
  32458. * @param {?Array<Node>} [values=null] - The default values.
  32459. * @return {string} The generated value as a shader string.
  32460. */
  32461. generateStruct( type, membersLayout, values = null ) {
  32462. const snippets = [];
  32463. for ( const member of membersLayout ) {
  32464. const { name, type } = member;
  32465. if ( values && values[ name ] && values[ name ].isNode ) {
  32466. snippets.push( values[ name ].build( this, type ) );
  32467. } else {
  32468. snippets.push( this.generateConst( type ) );
  32469. }
  32470. }
  32471. return type + '( ' + snippets.join( ', ' ) + ' )';
  32472. }
  32473. /**
  32474. * Generates the shader string for the given type and value.
  32475. *
  32476. * @param {string} type - The type.
  32477. * @param {?any} [value=null] - The value.
  32478. * @return {string} The generated value as a shader string.
  32479. */
  32480. generateConst( type, value = null ) {
  32481. if ( value === null ) {
  32482. if ( type === 'float' || type === 'int' || type === 'uint' ) value = 0;
  32483. else if ( type === 'bool' ) value = false;
  32484. else if ( type === 'color' ) value = new Color();
  32485. else if ( type === 'vec2' ) value = new Vector2();
  32486. else if ( type === 'vec3' ) value = new Vector3();
  32487. else if ( type === 'vec4' ) value = new Vector4();
  32488. }
  32489. if ( type === 'float' ) return toFloat( value );
  32490. if ( type === 'int' ) return `${ Math.round( value ) }`;
  32491. if ( type === 'uint' ) return value >= 0 ? `${ Math.round( value ) }u` : '0u';
  32492. if ( type === 'bool' ) return value ? 'true' : 'false';
  32493. if ( type === 'color' ) return `${ this.getType( 'vec3' ) }( ${ toFloat( value.r ) }, ${ toFloat( value.g ) }, ${ toFloat( value.b ) } )`;
  32494. const typeLength = this.getTypeLength( type );
  32495. const componentType = this.getComponentType( type );
  32496. const generateConst = value => this.generateConst( componentType, value );
  32497. if ( typeLength === 2 ) {
  32498. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) } )`;
  32499. } else if ( typeLength === 3 ) {
  32500. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) } )`;
  32501. } else if ( typeLength === 4 && type !== 'mat2' ) {
  32502. return `${ this.getType( type ) }( ${ generateConst( value.x ) }, ${ generateConst( value.y ) }, ${ generateConst( value.z ) }, ${ generateConst( value.w ) } )`;
  32503. } else if ( typeLength >= 4 && value && ( value.isMatrix2 || value.isMatrix3 || value.isMatrix4 ) ) {
  32504. return `${ this.getType( type ) }( ${ value.elements.map( generateConst ).join( ', ' ) } )`;
  32505. } else if ( typeLength > 4 ) {
  32506. return `${ this.getType( type ) }()`;
  32507. }
  32508. throw new Error( `NodeBuilder: Type '${type}' not found in generate constant attempt.` );
  32509. }
  32510. /**
  32511. * It might be necessary to convert certain data types to different ones
  32512. * so this method can be used to hide the conversion.
  32513. *
  32514. * @param {string} type - The type.
  32515. * @return {string} The updated type.
  32516. */
  32517. getType( type ) {
  32518. if ( type === 'color' ) return 'vec3';
  32519. return type;
  32520. }
  32521. /**
  32522. * Whether the given attribute name is defined in the geometry or not.
  32523. *
  32524. * @param {string} name - The attribute name.
  32525. * @return {boolean} Whether the given attribute name is defined in the geometry.
  32526. */
  32527. hasGeometryAttribute( name ) {
  32528. return this.geometry && this.geometry.getAttribute( name ) !== undefined;
  32529. }
  32530. /**
  32531. * Returns a node attribute for the given name and type.
  32532. *
  32533. * @param {string} name - The attribute's name.
  32534. * @param {string} type - The attribute's type.
  32535. * @return {NodeAttribute} The node attribute.
  32536. */
  32537. getAttribute( name, type ) {
  32538. const attributes = this.attributes;
  32539. // find attribute
  32540. for ( const attribute of attributes ) {
  32541. if ( attribute.name === name ) {
  32542. return attribute;
  32543. }
  32544. }
  32545. // create a new if no exist
  32546. const attribute = new NodeAttribute( name, type );
  32547. this.registerDeclaration( attribute );
  32548. attributes.push( attribute );
  32549. return attribute;
  32550. }
  32551. /**
  32552. * Returns for the given node and shader stage the property name for the shader.
  32553. *
  32554. * @param {Node} node - The node.
  32555. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  32556. * @return {string} The property name.
  32557. */
  32558. getPropertyName( node/*, shaderStage*/ ) {
  32559. return node.name;
  32560. }
  32561. /**
  32562. * Whether the given type is a vector type or not.
  32563. *
  32564. * @param {string} type - The type to check.
  32565. * @return {boolean} Whether the given type is a vector type or not.
  32566. */
  32567. isVector( type ) {
  32568. return /vec\d/.test( type );
  32569. }
  32570. /**
  32571. * Whether the given type is a matrix type or not.
  32572. *
  32573. * @param {string} type - The type to check.
  32574. * @return {boolean} Whether the given type is a matrix type or not.
  32575. */
  32576. isMatrix( type ) {
  32577. return /mat\d/.test( type );
  32578. }
  32579. /**
  32580. * Whether the given type is a reference type or not.
  32581. *
  32582. * @param {string} type - The type to check.
  32583. * @return {boolean} Whether the given type is a reference type or not.
  32584. */
  32585. isReference( type ) {
  32586. return type === 'void' || type === 'property' || type === 'sampler' || type === 'samplerComparison' || type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'depthTexture' || type === 'texture3D';
  32587. }
  32588. /**
  32589. * Checks if the given texture requires a manual conversion to the working color space.
  32590. *
  32591. * @abstract
  32592. * @param {Texture} texture - The texture to check.
  32593. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  32594. */
  32595. needsToWorkingColorSpace( /*texture*/ ) {
  32596. return false;
  32597. }
  32598. /**
  32599. * Returns the component type of a given texture.
  32600. *
  32601. * @param {Texture} texture - The texture.
  32602. * @return {string} The component type.
  32603. */
  32604. getComponentTypeFromTexture( texture ) {
  32605. const type = texture.type;
  32606. if ( texture.isDataTexture ) {
  32607. if ( type === IntType ) return 'int';
  32608. if ( type === UnsignedIntType ) return 'uint';
  32609. }
  32610. return 'float';
  32611. }
  32612. /**
  32613. * Returns the element type for a given type.
  32614. *
  32615. * @param {string} type - The type.
  32616. * @return {string} The element type.
  32617. */
  32618. getElementType( type ) {
  32619. if ( type === 'mat2' ) return 'vec2';
  32620. if ( type === 'mat3' ) return 'vec3';
  32621. if ( type === 'mat4' ) return 'vec4';
  32622. return this.getComponentType( type );
  32623. }
  32624. /**
  32625. * Returns the component type for a given type.
  32626. *
  32627. * @param {string} type - The type.
  32628. * @return {string} The component type.
  32629. */
  32630. getComponentType( type ) {
  32631. type = this.getVectorType( type );
  32632. if ( type === 'float' || type === 'bool' || type === 'int' || type === 'uint' ) return type;
  32633. const componentType = /(b|i|u|)(vec|mat)([2-4])/.exec( type );
  32634. if ( componentType === null ) return null;
  32635. if ( componentType[ 1 ] === 'b' ) return 'bool';
  32636. if ( componentType[ 1 ] === 'i' ) return 'int';
  32637. if ( componentType[ 1 ] === 'u' ) return 'uint';
  32638. return 'float';
  32639. }
  32640. /**
  32641. * Returns the vector type for a given type.
  32642. *
  32643. * @param {string} type - The type.
  32644. * @return {string} The vector type.
  32645. */
  32646. getVectorType( type ) {
  32647. if ( type === 'color' ) return 'vec3';
  32648. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) return 'vec4';
  32649. return type;
  32650. }
  32651. /**
  32652. * Returns the data type for the given the length and component type.
  32653. *
  32654. * @param {number} length - The length.
  32655. * @param {string} [componentType='float'] - The component type.
  32656. * @return {string} The type.
  32657. */
  32658. getTypeFromLength( length, componentType = 'float' ) {
  32659. if ( length === 1 ) return componentType;
  32660. let baseType = getTypeFromLength( length );
  32661. const prefix = componentType === 'float' ? '' : componentType[ 0 ];
  32662. // fix edge case for mat2x2 being same size as vec4
  32663. if ( /mat2/.test( componentType ) === true ) {
  32664. baseType = baseType.replace( 'vec', 'mat' );
  32665. }
  32666. return prefix + baseType;
  32667. }
  32668. /**
  32669. * Returns the type for a given typed array.
  32670. *
  32671. * @param {TypedArray} array - The typed array.
  32672. * @return {string} The type.
  32673. */
  32674. getTypeFromArray( array ) {
  32675. return typeFromArray.get( array.constructor );
  32676. }
  32677. /**
  32678. * Returns the type is an integer type.
  32679. *
  32680. * @param {string} type - The type.
  32681. * @return {boolean} Whether the type is an integer type or not.
  32682. */
  32683. isInteger( type ) {
  32684. return /int|uint|(i|u)vec/.test( type );
  32685. }
  32686. /**
  32687. * Returns the type for a given buffer attribute.
  32688. *
  32689. * @param {BufferAttribute} attribute - The buffer attribute.
  32690. * @return {string} The type.
  32691. */
  32692. getTypeFromAttribute( attribute ) {
  32693. let dataAttribute = attribute;
  32694. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  32695. const array = dataAttribute.array;
  32696. const itemSize = attribute.itemSize;
  32697. const normalized = attribute.normalized;
  32698. let arrayType;
  32699. if ( ! ( attribute instanceof Float16BufferAttribute ) && normalized !== true ) {
  32700. arrayType = this.getTypeFromArray( array );
  32701. }
  32702. return this.getTypeFromLength( itemSize, arrayType );
  32703. }
  32704. /**
  32705. * Returns the length for the given data type.
  32706. *
  32707. * @param {string} type - The data type.
  32708. * @return {number} The length.
  32709. */
  32710. getTypeLength( type ) {
  32711. const vecType = this.getVectorType( type );
  32712. const vecNum = /vec([2-4])/.exec( vecType );
  32713. if ( vecNum !== null ) return Number( vecNum[ 1 ] );
  32714. if ( vecType === 'float' || vecType === 'bool' || vecType === 'int' || vecType === 'uint' ) return 1;
  32715. if ( /mat2/.test( type ) === true ) return 4;
  32716. if ( /mat3/.test( type ) === true ) return 9;
  32717. if ( /mat4/.test( type ) === true ) return 16;
  32718. return 0;
  32719. }
  32720. /**
  32721. * Returns the vector type for a given matrix type.
  32722. *
  32723. * @param {string} type - The matrix type.
  32724. * @return {string} The vector type.
  32725. */
  32726. getVectorFromMatrix( type ) {
  32727. return type.replace( 'mat', 'vec' );
  32728. }
  32729. /**
  32730. * For a given type this method changes the component type to the
  32731. * given value. E.g. `vec4` should be changed to the new component type
  32732. * `uint` which results in `uvec4`.
  32733. *
  32734. * @param {string} type - The type.
  32735. * @param {string} newComponentType - The new component type.
  32736. * @return {string} The new type.
  32737. */
  32738. changeComponentType( type, newComponentType ) {
  32739. return this.getTypeFromLength( this.getTypeLength( type ), newComponentType );
  32740. }
  32741. /**
  32742. * Returns the integer type pendant for the given type.
  32743. *
  32744. * @param {string} type - The type.
  32745. * @return {string} The integer type.
  32746. */
  32747. getIntegerType( type ) {
  32748. const componentType = this.getComponentType( type );
  32749. if ( componentType === 'int' || componentType === 'uint' ) return type;
  32750. return this.changeComponentType( type, 'int' );
  32751. }
  32752. /**
  32753. * Adds a stack node to the internal stack.
  32754. *
  32755. * @return {StackNode} The added stack node.
  32756. */
  32757. addStack() {
  32758. this.stack = stack( this.stack );
  32759. this.stacks.push( getCurrentStack() || this.stack );
  32760. setCurrentStack( this.stack );
  32761. return this.stack;
  32762. }
  32763. /**
  32764. * Removes the last stack node from the internal stack.
  32765. *
  32766. * @return {StackNode} The removed stack node.
  32767. */
  32768. removeStack() {
  32769. const lastStack = this.stack;
  32770. this.stack = lastStack.parent;
  32771. setCurrentStack( this.stacks.pop() );
  32772. return lastStack;
  32773. }
  32774. /**
  32775. * The builder maintains (cached) data for each node during the building process. This method
  32776. * can be used to get these data for a specific shader stage and cache.
  32777. *
  32778. * @param {Node} node - The node to get the data for.
  32779. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32780. * @param {?NodeCache} cache - An optional cache.
  32781. * @return {Object} The node data.
  32782. */
  32783. getDataFromNode( node, shaderStage = this.shaderStage, cache = null ) {
  32784. cache = cache === null ? ( node.isGlobal( this ) ? this.globalCache : this.cache ) : cache;
  32785. let nodeData = cache.getData( node );
  32786. if ( nodeData === undefined ) {
  32787. nodeData = {};
  32788. cache.setData( node, nodeData );
  32789. }
  32790. if ( nodeData[ shaderStage ] === undefined ) nodeData[ shaderStage ] = {};
  32791. return nodeData[ shaderStage ];
  32792. }
  32793. /**
  32794. * Returns the properties for the given node and shader stage.
  32795. *
  32796. * @param {Node} node - The node to get the properties for.
  32797. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage='any'] - The shader stage.
  32798. * @return {Object} The node properties.
  32799. */
  32800. getNodeProperties( node, shaderStage = 'any' ) {
  32801. const nodeData = this.getDataFromNode( node, shaderStage );
  32802. return nodeData.properties || ( nodeData.properties = { outputNode: null } );
  32803. }
  32804. /**
  32805. * Returns an instance of {@link NodeAttribute} for the given buffer attribute node.
  32806. *
  32807. * @param {BufferAttributeNode} node - The buffer attribute node.
  32808. * @param {string} type - The node type.
  32809. * @return {NodeAttribute} The node attribute.
  32810. */
  32811. getBufferAttributeFromNode( node, type ) {
  32812. const nodeData = this.getDataFromNode( node );
  32813. let bufferAttribute = nodeData.bufferAttribute;
  32814. if ( bufferAttribute === undefined ) {
  32815. const index = this.uniforms.index ++;
  32816. bufferAttribute = new NodeAttribute( 'nodeAttribute' + index, type, node );
  32817. this.bufferAttributes.push( bufferAttribute );
  32818. nodeData.bufferAttribute = bufferAttribute;
  32819. }
  32820. return bufferAttribute;
  32821. }
  32822. /**
  32823. * Returns an instance of {@link StructType} for the given output struct node.
  32824. *
  32825. * @param {OutputStructNode} node - The output struct node.
  32826. * @param {Array<Object>} membersLayout - The output struct types.
  32827. * @param {?string} [name=null] - The name of the struct.
  32828. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32829. * @return {StructType} The struct type attribute.
  32830. */
  32831. getStructTypeFromNode( node, membersLayout, name = null, shaderStage = this.shaderStage ) {
  32832. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  32833. let structType = nodeData.structType;
  32834. if ( structType === undefined ) {
  32835. const index = this.structs.index ++;
  32836. if ( name === null ) name = 'StructType' + index;
  32837. structType = new StructType( name, membersLayout );
  32838. this.structs[ shaderStage ].push( structType );
  32839. nodeData.structType = structType;
  32840. }
  32841. return structType;
  32842. }
  32843. /**
  32844. * Returns an instance of {@link StructType} for the given output struct node.
  32845. *
  32846. * @param {OutputStructNode} node - The output struct node.
  32847. * @param {Array<Object>} membersLayout - The output struct types.
  32848. * @return {StructType} The struct type attribute.
  32849. */
  32850. getOutputStructTypeFromNode( node, membersLayout ) {
  32851. const structType = this.getStructTypeFromNode( node, membersLayout, 'OutputType', 'fragment' );
  32852. structType.output = true;
  32853. return structType;
  32854. }
  32855. /**
  32856. * Returns an instance of {@link NodeUniform} for the given uniform node.
  32857. *
  32858. * @param {UniformNode} node - The uniform node.
  32859. * @param {string} type - The uniform type.
  32860. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32861. * @param {?string} name - The name of the uniform.
  32862. * @return {NodeUniform} The node uniform.
  32863. */
  32864. getUniformFromNode( node, type, shaderStage = this.shaderStage, name = null ) {
  32865. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  32866. let nodeUniform = nodeData.uniform;
  32867. if ( nodeUniform === undefined ) {
  32868. const index = this.uniforms.index ++;
  32869. nodeUniform = new NodeUniform( name || ( 'nodeUniform' + index ), type, node );
  32870. this.uniforms[ shaderStage ].push( nodeUniform );
  32871. this.registerDeclaration( nodeUniform );
  32872. nodeData.uniform = nodeUniform;
  32873. }
  32874. return nodeUniform;
  32875. }
  32876. /**
  32877. * Returns the array length.
  32878. *
  32879. * @param {Node} node - The node.
  32880. * @return {?number} The array length.
  32881. */
  32882. getArrayCount( node ) {
  32883. let count = null;
  32884. if ( node.isArrayNode ) count = node.count;
  32885. else if ( node.isVarNode && node.node.isArrayNode ) count = node.node.count;
  32886. return count;
  32887. }
  32888. /**
  32889. * Returns an instance of {@link NodeVar} for the given variable node.
  32890. *
  32891. * @param {VarNode} node - The variable node.
  32892. * @param {?string} name - The variable's name.
  32893. * @param {string} [type=node.getNodeType( this )] - The variable's type.
  32894. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  32895. * @param {boolean} [readOnly=false] - Whether the variable is read-only or not.
  32896. *
  32897. * @return {NodeVar} The node variable.
  32898. */
  32899. getVarFromNode( node, name = null, type = node.getNodeType( this ), shaderStage = this.shaderStage, readOnly = false ) {
  32900. const nodeData = this.getDataFromNode( node, shaderStage );
  32901. let nodeVar = nodeData.variable;
  32902. if ( nodeVar === undefined ) {
  32903. const idNS = readOnly ? '_const' : '_var';
  32904. const vars = this.vars[ shaderStage ] || ( this.vars[ shaderStage ] = [] );
  32905. const id = this.vars[ idNS ] || ( this.vars[ idNS ] = 0 );
  32906. if ( name === null ) {
  32907. name = ( readOnly ? 'nodeConst' : 'nodeVar' ) + id;
  32908. this.vars[ idNS ] ++;
  32909. }
  32910. //
  32911. const count = this.getArrayCount( node );
  32912. nodeVar = new NodeVar( name, type, readOnly, count );
  32913. if ( ! readOnly ) {
  32914. vars.push( nodeVar );
  32915. }
  32916. this.registerDeclaration( nodeVar );
  32917. nodeData.variable = nodeVar;
  32918. }
  32919. return nodeVar;
  32920. }
  32921. /**
  32922. * Returns whether a Node or its flow is deterministic, useful for use in `const`.
  32923. *
  32924. * @param {Node} node - The varying node.
  32925. * @return {boolean} Returns true if deterministic.
  32926. */
  32927. isDeterministic( node ) {
  32928. if ( node.isMathNode ) {
  32929. return this.isDeterministic( node.aNode ) &&
  32930. ( node.bNode ? this.isDeterministic( node.bNode ) : true ) &&
  32931. ( node.cNode ? this.isDeterministic( node.cNode ) : true );
  32932. } else if ( node.isOperatorNode ) {
  32933. return this.isDeterministic( node.aNode ) &&
  32934. ( node.bNode ? this.isDeterministic( node.bNode ) : true );
  32935. } else if ( node.isArrayNode ) {
  32936. if ( node.values !== null ) {
  32937. for ( const n of node.values ) {
  32938. if ( ! this.isDeterministic( n ) ) {
  32939. return false;
  32940. }
  32941. }
  32942. }
  32943. return true;
  32944. } else if ( node.isConstNode ) {
  32945. return true;
  32946. }
  32947. return false;
  32948. }
  32949. /**
  32950. * Returns an instance of {@link NodeVarying} for the given varying node.
  32951. *
  32952. * @param {(VaryingNode|PropertyNode)} node - The varying node.
  32953. * @param {?string} name - The varying's name.
  32954. * @param {string} [type=node.getNodeType( this )] - The varying's type.
  32955. * @param {?string} interpolationType - The interpolation type of the varying.
  32956. * @param {?string} interpolationSampling - The interpolation sampling type of the varying.
  32957. * @return {NodeVar} The node varying.
  32958. */
  32959. getVaryingFromNode( node, name = null, type = node.getNodeType( this ), interpolationType = null, interpolationSampling = null ) {
  32960. const nodeData = this.getDataFromNode( node, 'any' );
  32961. let nodeVarying = nodeData.varying;
  32962. if ( nodeVarying === undefined ) {
  32963. const varyings = this.varyings;
  32964. const index = varyings.length;
  32965. if ( name === null ) name = 'nodeVarying' + index;
  32966. nodeVarying = new NodeVarying( name, type, interpolationType, interpolationSampling );
  32967. varyings.push( nodeVarying );
  32968. this.registerDeclaration( nodeVarying );
  32969. nodeData.varying = nodeVarying;
  32970. }
  32971. return nodeVarying;
  32972. }
  32973. /**
  32974. * Returns the current namespace for the node builder.
  32975. *
  32976. * @return {string} The current namespace.
  32977. */
  32978. get namespace() {
  32979. return this.context.namespace;
  32980. }
  32981. /**
  32982. * Returns the output namespace for the node builder, which is used for the current output node.
  32983. *
  32984. * @return {string} The output namespace.
  32985. */
  32986. getOutputNamespace() {
  32987. return this.getNamespace( 'outputNode' );
  32988. }
  32989. /**
  32990. * Returns the namespace for the given property.
  32991. *
  32992. * If the property name is not set, it returns the namespace only.
  32993. * If the namespace is not set, it returns the property name.
  32994. * If the namespace is set, it returns the namespace concatenated with the property name.
  32995. *
  32996. * @param {string} [property=''] - The property name.
  32997. * @return {string} The namespace for the property.
  32998. */
  32999. getNamespace( property = '' ) {
  33000. const ns = this.namespace;
  33001. let nsName;
  33002. if ( ns ) {
  33003. nsName = property ? ( ns + '_' + property ) : ns;
  33004. } else {
  33005. nsName = property;
  33006. }
  33007. return nsName;
  33008. }
  33009. /**
  33010. * Registers a node declaration in the current shader stage.
  33011. *
  33012. * @param {Object} node - The node to be registered.
  33013. */
  33014. registerDeclaration( node ) {
  33015. const shaderStage = this.shaderStage;
  33016. const declarations = this.declarations[ shaderStage ] || ( this.declarations[ shaderStage ] = {} );
  33017. const property = this.getPropertyName( node );
  33018. let index = 1;
  33019. let name = property;
  33020. // Automatically renames the property if the name is already in use.
  33021. while ( declarations[ name ] !== undefined ) {
  33022. name = property + '_' + index ++;
  33023. }
  33024. if ( index > 1 ) {
  33025. node.name = name;
  33026. console.warn( `THREE.TSL: Declaration name '${ property }' of '${ node.type }' already in use. Renamed to '${ name }'.` );
  33027. }
  33028. declarations[ name ] = node;
  33029. }
  33030. /**
  33031. * Returns an instance of {@link NodeCode} for the given code node.
  33032. *
  33033. * @param {CodeNode} node - The code node.
  33034. * @param {string} type - The node type.
  33035. * @param {('vertex'|'fragment'|'compute'|'any')} [shaderStage=this.shaderStage] - The shader stage.
  33036. * @return {NodeCode} The node code.
  33037. */
  33038. getCodeFromNode( node, type, shaderStage = this.shaderStage ) {
  33039. const nodeData = this.getDataFromNode( node );
  33040. let nodeCode = nodeData.code;
  33041. if ( nodeCode === undefined ) {
  33042. const codes = this.codes[ shaderStage ] || ( this.codes[ shaderStage ] = [] );
  33043. const index = codes.length;
  33044. nodeCode = new NodeCode( 'nodeCode' + index, type );
  33045. codes.push( nodeCode );
  33046. nodeData.code = nodeCode;
  33047. }
  33048. return nodeCode;
  33049. }
  33050. /**
  33051. * Adds a code flow based on the code-block hierarchy.
  33052. * This is used so that code-blocks like If,Else create their variables locally if the Node
  33053. * is only used inside one of these conditionals in the current shader stage.
  33054. *
  33055. * @param {Node} node - The node to add.
  33056. * @param {Node} nodeBlock - Node-based code-block. Usually 'ConditionalNode'.
  33057. */
  33058. addFlowCodeHierarchy( node, nodeBlock ) {
  33059. const { flowCodes, flowCodeBlock } = this.getDataFromNode( node );
  33060. let needsFlowCode = true;
  33061. let nodeBlockHierarchy = nodeBlock;
  33062. while ( nodeBlockHierarchy ) {
  33063. if ( flowCodeBlock.get( nodeBlockHierarchy ) === true ) {
  33064. needsFlowCode = false;
  33065. break;
  33066. }
  33067. nodeBlockHierarchy = this.getDataFromNode( nodeBlockHierarchy ).parentNodeBlock;
  33068. }
  33069. if ( needsFlowCode ) {
  33070. for ( const flowCode of flowCodes ) {
  33071. this.addLineFlowCode( flowCode );
  33072. }
  33073. }
  33074. }
  33075. /**
  33076. * Add a inline-code to the current flow code-block.
  33077. *
  33078. * @param {Node} node - The node to add.
  33079. * @param {string} code - The code to add.
  33080. * @param {Node} nodeBlock - Current ConditionalNode
  33081. */
  33082. addLineFlowCodeBlock( node, code, nodeBlock ) {
  33083. const nodeData = this.getDataFromNode( node );
  33084. const flowCodes = nodeData.flowCodes || ( nodeData.flowCodes = [] );
  33085. const codeBlock = nodeData.flowCodeBlock || ( nodeData.flowCodeBlock = new WeakMap() );
  33086. flowCodes.push( code );
  33087. codeBlock.set( nodeBlock, true );
  33088. }
  33089. /**
  33090. * Add a inline-code to the current flow.
  33091. *
  33092. * @param {string} code - The code to add.
  33093. * @param {?Node} [node= null] - Optional Node, can help the system understand if the Node is part of a code-block.
  33094. * @return {NodeBuilder} A reference to this node builder.
  33095. */
  33096. addLineFlowCode( code, node = null ) {
  33097. if ( code === '' ) return this;
  33098. if ( node !== null && this.context.nodeBlock ) {
  33099. this.addLineFlowCodeBlock( node, code, this.context.nodeBlock );
  33100. }
  33101. code = this.tab + code;
  33102. if ( ! /;\s*$/.test( code ) ) {
  33103. code = code + ';\n';
  33104. }
  33105. this.flow.code += code;
  33106. return this;
  33107. }
  33108. /**
  33109. * Adds a code to the current code flow.
  33110. *
  33111. * @param {string} code - Shader code.
  33112. * @return {NodeBuilder} A reference to this node builder.
  33113. */
  33114. addFlowCode( code ) {
  33115. this.flow.code += code;
  33116. return this;
  33117. }
  33118. /**
  33119. * Add tab in the code that will be generated so that other snippets respect the current tabulation.
  33120. * Typically used in codes with If,Else.
  33121. *
  33122. * @return {NodeBuilder} A reference to this node builder.
  33123. */
  33124. addFlowTab() {
  33125. this.tab += '\t';
  33126. return this;
  33127. }
  33128. /**
  33129. * Removes a tab.
  33130. *
  33131. * @return {NodeBuilder} A reference to this node builder.
  33132. */
  33133. removeFlowTab() {
  33134. this.tab = this.tab.slice( 0, -1 );
  33135. return this;
  33136. }
  33137. /**
  33138. * Gets the current flow data based on a Node.
  33139. *
  33140. * @param {Node} node - Node that the flow was started.
  33141. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33142. * @return {Object} The flow data.
  33143. */
  33144. getFlowData( node/*, shaderStage*/ ) {
  33145. return this.flowsData.get( node );
  33146. }
  33147. /**
  33148. * Executes the node flow based on a root node to generate the final shader code.
  33149. *
  33150. * @param {Node} node - The node to execute.
  33151. * @return {Object} The code flow.
  33152. */
  33153. flowNode( node ) {
  33154. const output = node.getNodeType( this );
  33155. const flowData = this.flowChildNode( node, output );
  33156. this.flowsData.set( node, flowData );
  33157. return flowData;
  33158. }
  33159. /**
  33160. * Includes a node in the current function node.
  33161. *
  33162. * @param {Node} node - The node to include.
  33163. * @returns {void}
  33164. */
  33165. addInclude( node ) {
  33166. if ( this.currentFunctionNode !== null ) {
  33167. this.currentFunctionNode.includes.push( node );
  33168. }
  33169. }
  33170. /**
  33171. * Returns the native shader operator name for a given generic name.
  33172. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  33173. *
  33174. * @param {ShaderNodeInternal} shaderNode - The shader node to build the function node with.
  33175. * @return {FunctionNode} The build function node.
  33176. */
  33177. buildFunctionNode( shaderNode ) {
  33178. const fn = new FunctionNode();
  33179. const previous = this.currentFunctionNode;
  33180. this.currentFunctionNode = fn;
  33181. fn.code = this.buildFunctionCode( shaderNode );
  33182. this.currentFunctionNode = previous;
  33183. return fn;
  33184. }
  33185. /**
  33186. * Generates a code flow based on a TSL function: Fn().
  33187. *
  33188. * @param {ShaderNodeInternal} shaderNode - A function code will be generated based on the input.
  33189. * @return {Object}
  33190. */
  33191. flowShaderNode( shaderNode ) {
  33192. const layout = shaderNode.layout;
  33193. const inputs = {
  33194. [ Symbol.iterator ]() {
  33195. let index = 0;
  33196. const values = Object.values( this );
  33197. return {
  33198. next: () => ( {
  33199. value: values[ index ],
  33200. done: index ++ >= values.length
  33201. } )
  33202. };
  33203. }
  33204. };
  33205. for ( const input of layout.inputs ) {
  33206. inputs[ input.name ] = new ParameterNode( input.type, input.name );
  33207. }
  33208. //
  33209. shaderNode.layout = null;
  33210. const callNode = shaderNode.call( inputs );
  33211. const flowData = this.flowStagesNode( callNode, layout.type );
  33212. shaderNode.layout = layout;
  33213. return flowData;
  33214. }
  33215. /**
  33216. * Runs the node flow through all the steps of creation, 'setup', 'analyze', 'generate'.
  33217. *
  33218. * @param {Node} node - The node to execute.
  33219. * @param {?string} output - Expected output type. For example 'vec3'.
  33220. * @return {Object}
  33221. */
  33222. flowStagesNode( node, output = null ) {
  33223. const previousFlow = this.flow;
  33224. const previousVars = this.vars;
  33225. const previousDeclarations = this.declarations;
  33226. const previousCache = this.cache;
  33227. const previousBuildStage = this.buildStage;
  33228. const previousStack = this.stack;
  33229. const flow = {
  33230. code: ''
  33231. };
  33232. this.flow = flow;
  33233. this.vars = {};
  33234. this.declarations = {};
  33235. this.cache = new NodeCache();
  33236. this.stack = stack();
  33237. for ( const buildStage of defaultBuildStages ) {
  33238. this.setBuildStage( buildStage );
  33239. flow.result = node.build( this, output );
  33240. }
  33241. flow.vars = this.getVars( this.shaderStage );
  33242. this.flow = previousFlow;
  33243. this.vars = previousVars;
  33244. this.declarations = previousDeclarations;
  33245. this.cache = previousCache;
  33246. this.stack = previousStack;
  33247. this.setBuildStage( previousBuildStage );
  33248. return flow;
  33249. }
  33250. /**
  33251. * Returns the native shader operator name for a given generic name.
  33252. * It is a similar type of method like {@link NodeBuilder#getMethod}.
  33253. *
  33254. * @abstract
  33255. * @param {string} op - The operator name to resolve.
  33256. * @return {?string} The resolved operator name.
  33257. */
  33258. getFunctionOperator( /* op */ ) {
  33259. return null;
  33260. }
  33261. /**
  33262. * Builds the given shader node.
  33263. *
  33264. * @abstract
  33265. * @param {ShaderNodeInternal} shaderNode - The shader node.
  33266. * @return {string} The function code.
  33267. */
  33268. buildFunctionCode( /* shaderNode */ ) {
  33269. console.warn( 'Abstract function.' );
  33270. }
  33271. /**
  33272. * Generates a code flow based on a child Node.
  33273. *
  33274. * @param {Node} node - The node to execute.
  33275. * @param {?string} output - Expected output type. For example 'vec3'.
  33276. * @return {Object} The code flow.
  33277. */
  33278. flowChildNode( node, output = null ) {
  33279. const previousFlow = this.flow;
  33280. const flow = {
  33281. code: ''
  33282. };
  33283. this.flow = flow;
  33284. flow.result = node.build( this, output );
  33285. this.flow = previousFlow;
  33286. return flow;
  33287. }
  33288. /**
  33289. * Executes a flow of code in a different stage.
  33290. *
  33291. * Some nodes like `varying()` have the ability to compute code in vertex-stage and
  33292. * return the value in fragment-stage even if it is being executed in an input fragment.
  33293. *
  33294. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33295. * @param {Node} node - The node to execute.
  33296. * @param {?string} output - Expected output type. For example 'vec3'.
  33297. * @param {?string} propertyName - The property name to assign the result.
  33298. * @return {Object|Node|null} The code flow or node.build() result.
  33299. */
  33300. flowNodeFromShaderStage( shaderStage, node, output = null, propertyName = null ) {
  33301. const previousTab = this.tab;
  33302. const previousCache = this.cache;
  33303. const previousShaderStage = this.shaderStage;
  33304. const previousContext = this.context;
  33305. this.setShaderStage( shaderStage );
  33306. const context = { ...this.context };
  33307. delete context.nodeBlock;
  33308. this.cache = this.globalCache;
  33309. this.tab = '\t';
  33310. this.context = context;
  33311. let result = null;
  33312. if ( this.buildStage === 'generate' ) {
  33313. const flowData = this.flowChildNode( node, output );
  33314. if ( propertyName !== null ) {
  33315. flowData.code += `${ this.tab + propertyName } = ${ flowData.result };\n`;
  33316. }
  33317. this.flowCode[ shaderStage ] = this.flowCode[ shaderStage ] + flowData.code;
  33318. result = flowData;
  33319. } else {
  33320. result = node.build( this );
  33321. }
  33322. this.setShaderStage( previousShaderStage );
  33323. this.cache = previousCache;
  33324. this.tab = previousTab;
  33325. this.context = previousContext;
  33326. return result;
  33327. }
  33328. /**
  33329. * Returns an array holding all node attributes of this node builder.
  33330. *
  33331. * @return {Array<NodeAttribute>} The node attributes of this builder.
  33332. */
  33333. getAttributesArray() {
  33334. return this.attributes.concat( this.bufferAttributes );
  33335. }
  33336. /**
  33337. * Returns the attribute definitions as a shader string for the given shader stage.
  33338. *
  33339. * @abstract
  33340. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33341. * @return {string} The attribute code section.
  33342. */
  33343. getAttributes( /*shaderStage*/ ) {
  33344. console.warn( 'Abstract function.' );
  33345. }
  33346. /**
  33347. * Returns the varying definitions as a shader string for the given shader stage.
  33348. *
  33349. * @abstract
  33350. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33351. * @return {string} The varying code section.
  33352. */
  33353. getVaryings( /*shaderStage*/ ) {
  33354. console.warn( 'Abstract function.' );
  33355. }
  33356. /**
  33357. * Returns a single variable definition as a shader string for the given variable type and name.
  33358. *
  33359. * @param {string} type - The variable's type.
  33360. * @param {string} name - The variable's name.
  33361. * @param {?number} [count=null] - The array length.
  33362. * @return {string} The shader string.
  33363. */
  33364. getVar( type, name, count = null ) {
  33365. return `${ count !== null ? this.generateArrayDeclaration( type, count ) : this.getType( type ) } ${ name }`;
  33366. }
  33367. /**
  33368. * Returns the variable definitions as a shader string for the given shader stage.
  33369. *
  33370. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33371. * @return {string} The variable code section.
  33372. */
  33373. getVars( shaderStage ) {
  33374. let snippet = '';
  33375. const vars = this.vars[ shaderStage ];
  33376. if ( vars !== undefined ) {
  33377. for ( const variable of vars ) {
  33378. snippet += `${ this.getVar( variable.type, variable.name ) }; `;
  33379. }
  33380. }
  33381. return snippet;
  33382. }
  33383. /**
  33384. * Returns the uniform definitions as a shader string for the given shader stage.
  33385. *
  33386. * @abstract
  33387. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33388. * @return {string} The uniform code section.
  33389. */
  33390. getUniforms( /*shaderStage*/ ) {
  33391. console.warn( 'Abstract function.' );
  33392. }
  33393. /**
  33394. * Returns the native code definitions as a shader string for the given shader stage.
  33395. *
  33396. * @param {('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage.
  33397. * @return {string} The native code section.
  33398. */
  33399. getCodes( shaderStage ) {
  33400. const codes = this.codes[ shaderStage ];
  33401. let code = '';
  33402. if ( codes !== undefined ) {
  33403. for ( const nodeCode of codes ) {
  33404. code += nodeCode.code + '\n';
  33405. }
  33406. }
  33407. return code;
  33408. }
  33409. /**
  33410. * Returns the hash of this node builder.
  33411. *
  33412. * @return {string} The hash.
  33413. */
  33414. getHash() {
  33415. return this.vertexShader + this.fragmentShader + this.computeShader;
  33416. }
  33417. /**
  33418. * Sets the current shader stage.
  33419. *
  33420. * @param {?('vertex'|'fragment'|'compute'|'any')} shaderStage - The shader stage to set.
  33421. */
  33422. setShaderStage( shaderStage ) {
  33423. this.shaderStage = shaderStage;
  33424. }
  33425. /**
  33426. * Returns the current shader stage.
  33427. *
  33428. * @return {?('vertex'|'fragment'|'compute'|'any')} The current shader stage.
  33429. */
  33430. getShaderStage() {
  33431. return this.shaderStage;
  33432. }
  33433. /**
  33434. * Sets the current build stage.
  33435. *
  33436. * @param {?('setup'|'analyze'|'generate')} buildStage - The build stage to set.
  33437. */
  33438. setBuildStage( buildStage ) {
  33439. this.buildStage = buildStage;
  33440. }
  33441. /**
  33442. * Returns the current build stage.
  33443. *
  33444. * @return {?('setup'|'analyze'|'generate')} The current build stage.
  33445. */
  33446. getBuildStage() {
  33447. return this.buildStage;
  33448. }
  33449. /**
  33450. * Controls the code build of the shader stages.
  33451. *
  33452. * @abstract
  33453. */
  33454. buildCode() {
  33455. console.warn( 'Abstract function.' );
  33456. }
  33457. /**
  33458. * Central build method which controls the build for the given object.
  33459. *
  33460. * @return {NodeBuilder} A reference to this node builder.
  33461. */
  33462. build() {
  33463. const { object, material, renderer } = this;
  33464. if ( material !== null ) {
  33465. let nodeMaterial = renderer.library.fromMaterial( material );
  33466. if ( nodeMaterial === null ) {
  33467. console.error( `NodeMaterial: Material "${ material.type }" is not compatible.` );
  33468. nodeMaterial = new NodeMaterial();
  33469. }
  33470. nodeMaterial.build( this );
  33471. } else {
  33472. this.addFlow( 'compute', object );
  33473. }
  33474. // setup() -> stage 1: create possible new nodes and returns an output reference node
  33475. // analyze() -> stage 2: analyze nodes to possible optimization and validation
  33476. // generate() -> stage 3: generate shader
  33477. for ( const buildStage of defaultBuildStages ) {
  33478. this.setBuildStage( buildStage );
  33479. if ( this.context.vertex && this.context.vertex.isNode ) {
  33480. this.flowNodeFromShaderStage( 'vertex', this.context.vertex );
  33481. }
  33482. for ( const shaderStage of shaderStages ) {
  33483. this.setShaderStage( shaderStage );
  33484. const flowNodes = this.flowNodes[ shaderStage ];
  33485. for ( const node of flowNodes ) {
  33486. if ( buildStage === 'generate' ) {
  33487. this.flowNode( node );
  33488. } else {
  33489. node.build( this );
  33490. }
  33491. }
  33492. }
  33493. }
  33494. this.setBuildStage( null );
  33495. this.setShaderStage( null );
  33496. // stage 4: build code for a specific output
  33497. this.buildCode();
  33498. this.buildUpdateNodes();
  33499. return this;
  33500. }
  33501. /**
  33502. * Returns a uniform representation which is later used for UBO generation and rendering.
  33503. *
  33504. * @param {NodeUniform} uniformNode - The uniform node.
  33505. * @param {string} type - The requested type.
  33506. * @return {Uniform} The uniform.
  33507. */
  33508. getNodeUniform( uniformNode, type ) {
  33509. if ( type === 'float' || type === 'int' || type === 'uint' ) return new NumberNodeUniform( uniformNode );
  33510. if ( type === 'vec2' || type === 'ivec2' || type === 'uvec2' ) return new Vector2NodeUniform( uniformNode );
  33511. if ( type === 'vec3' || type === 'ivec3' || type === 'uvec3' ) return new Vector3NodeUniform( uniformNode );
  33512. if ( type === 'vec4' || type === 'ivec4' || type === 'uvec4' ) return new Vector4NodeUniform( uniformNode );
  33513. if ( type === 'color' ) return new ColorNodeUniform( uniformNode );
  33514. if ( type === 'mat2' ) return new Matrix2NodeUniform( uniformNode );
  33515. if ( type === 'mat3' ) return new Matrix3NodeUniform( uniformNode );
  33516. if ( type === 'mat4' ) return new Matrix4NodeUniform( uniformNode );
  33517. throw new Error( `Uniform "${type}" not declared.` );
  33518. }
  33519. /**
  33520. * Formats the given shader snippet from a given type into another one. E.g.
  33521. * this method might be used to convert a simple float string `"1.0"` into a
  33522. * `vec3` representation: `"vec3<f32>( 1.0 )"`.
  33523. *
  33524. * @param {string} snippet - The shader snippet.
  33525. * @param {string} fromType - The source type.
  33526. * @param {string} toType - The target type.
  33527. * @return {string} The updated shader string.
  33528. */
  33529. format( snippet, fromType, toType ) {
  33530. fromType = this.getVectorType( fromType );
  33531. toType = this.getVectorType( toType );
  33532. if ( fromType === toType || toType === null || this.isReference( toType ) ) {
  33533. return snippet;
  33534. }
  33535. const fromTypeLength = this.getTypeLength( fromType );
  33536. const toTypeLength = this.getTypeLength( toType );
  33537. if ( fromTypeLength === 16 && toTypeLength === 9 ) {
  33538. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xyz, ${ snippet }[ 1 ].xyz, ${ snippet }[ 2 ].xyz )`;
  33539. }
  33540. if ( fromTypeLength === 9 && toTypeLength === 4 ) {
  33541. return `${ this.getType( toType ) }( ${ snippet }[ 0 ].xy, ${ snippet }[ 1 ].xy )`;
  33542. }
  33543. if ( fromTypeLength > 4 ) { // fromType is matrix-like
  33544. // @TODO: ignore for now
  33545. return snippet;
  33546. }
  33547. if ( toTypeLength > 4 || toTypeLength === 0 ) { // toType is matrix-like or unknown
  33548. // @TODO: ignore for now
  33549. return snippet;
  33550. }
  33551. if ( fromTypeLength === toTypeLength ) {
  33552. return `${ this.getType( toType ) }( ${ snippet } )`;
  33553. }
  33554. if ( fromTypeLength > toTypeLength ) {
  33555. snippet = toType === 'bool' ? `all( ${ snippet } )` : `${ snippet }.${ 'xyz'.slice( 0, toTypeLength ) }`;
  33556. return this.format( snippet, this.getTypeFromLength( toTypeLength, this.getComponentType( fromType ) ), toType );
  33557. }
  33558. if ( toTypeLength === 4 && fromTypeLength > 1 ) { // toType is vec4-like
  33559. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec3' ) }, 1.0 )`;
  33560. }
  33561. if ( fromTypeLength === 2 ) { // fromType is vec2-like and toType is vec3-like
  33562. return `${ this.getType( toType ) }( ${ this.format( snippet, fromType, 'vec2' ) }, 0.0 )`;
  33563. }
  33564. if ( fromTypeLength === 1 && toTypeLength > 1 && fromType !== this.getComponentType( toType ) ) { // fromType is float-like
  33565. // convert a number value to vector type, e.g:
  33566. // vec3( 1u ) -> vec3( float( 1u ) )
  33567. snippet = `${ this.getType( this.getComponentType( toType ) ) }( ${ snippet } )`;
  33568. }
  33569. return `${ this.getType( toType ) }( ${ snippet } )`; // fromType is float-like
  33570. }
  33571. /**
  33572. * Returns a signature with the engine's current revision.
  33573. *
  33574. * @return {string} The signature.
  33575. */
  33576. getSignature() {
  33577. return `// Three.js r${ REVISION } - Node System\n`;
  33578. }
  33579. /**
  33580. * Prevents the node builder from being used as an iterable in TSL.Fn(), avoiding potential runtime errors.
  33581. */
  33582. *[ Symbol.iterator ]() { }
  33583. // Deprecated
  33584. /**
  33585. * @function
  33586. * @deprecated since r168. Use `new NodeMaterial()` instead, with targeted node material name.
  33587. *
  33588. * @param {string} [type='NodeMaterial'] - The node material type.
  33589. * @throws {Error}
  33590. */
  33591. createNodeMaterial( type = 'NodeMaterial' ) { // @deprecated, r168
  33592. throw new Error( `THREE.NodeBuilder: createNodeMaterial() was deprecated. Use new ${ type }() instead.` );
  33593. }
  33594. }
  33595. /**
  33596. * Management class for updating nodes. The module tracks metrics like
  33597. * the elapsed time, delta time, the render and frame ID to correctly
  33598. * call the node update methods {@link Node#updateBefore}, {@link Node#update}
  33599. * and {@link Node#updateAfter} depending on the node's configuration.
  33600. */
  33601. class NodeFrame {
  33602. /**
  33603. * Constructs a new node fame.
  33604. */
  33605. constructor() {
  33606. /**
  33607. * The elapsed time in seconds.
  33608. *
  33609. * @type {number}
  33610. * @default 0
  33611. */
  33612. this.time = 0;
  33613. /**
  33614. * The delta time in seconds.
  33615. *
  33616. * @type {number}
  33617. * @default 0
  33618. */
  33619. this.deltaTime = 0;
  33620. /**
  33621. * The frame ID.
  33622. *
  33623. * @type {number}
  33624. * @default 0
  33625. */
  33626. this.frameId = 0;
  33627. /**
  33628. * The render ID.
  33629. *
  33630. * @type {number}
  33631. * @default 0
  33632. */
  33633. this.renderId = 0;
  33634. /**
  33635. * Used to control the {@link Node#update} call.
  33636. *
  33637. * @type {WeakMap<Node, Object>}
  33638. */
  33639. this.updateMap = new WeakMap();
  33640. /**
  33641. * Used to control the {@link Node#updateBefore} call.
  33642. *
  33643. * @type {WeakMap<Node, Object>}
  33644. */
  33645. this.updateBeforeMap = new WeakMap();
  33646. /**
  33647. * Used to control the {@link Node#updateAfter} call.
  33648. *
  33649. * @type {WeakMap<Node, Object>}
  33650. */
  33651. this.updateAfterMap = new WeakMap();
  33652. /**
  33653. * A reference to the current renderer.
  33654. *
  33655. * @type {?Renderer}
  33656. * @default null
  33657. */
  33658. this.renderer = null;
  33659. /**
  33660. * A reference to the current material.
  33661. *
  33662. * @type {?Material}
  33663. * @default null
  33664. */
  33665. this.material = null;
  33666. /**
  33667. * A reference to the current camera.
  33668. *
  33669. * @type {?Camera}
  33670. * @default null
  33671. */
  33672. this.camera = null;
  33673. /**
  33674. * A reference to the current 3D object.
  33675. *
  33676. * @type {?Object3D}
  33677. * @default null
  33678. */
  33679. this.object = null;
  33680. /**
  33681. * A reference to the current scene.
  33682. *
  33683. * @type {?Scene}
  33684. * @default null
  33685. */
  33686. this.scene = null;
  33687. }
  33688. /**
  33689. * Returns a dictionary for a given node and update map which
  33690. * is used to correctly call node update methods per frame or render.
  33691. *
  33692. * @private
  33693. * @param {WeakMap<Node, Object>} referenceMap - The reference weak map.
  33694. * @param {Node} nodeRef - The reference to the current node.
  33695. * @return {Object<string,WeakMap>} The dictionary.
  33696. */
  33697. _getMaps( referenceMap, nodeRef ) {
  33698. let maps = referenceMap.get( nodeRef );
  33699. if ( maps === undefined ) {
  33700. maps = {
  33701. renderMap: new WeakMap(),
  33702. frameMap: new WeakMap()
  33703. };
  33704. referenceMap.set( nodeRef, maps );
  33705. }
  33706. return maps;
  33707. }
  33708. /**
  33709. * This method executes the {@link Node#updateBefore} for the given node.
  33710. * It makes sure {@link Node#updateBeforeType} is honored meaning the update
  33711. * is only executed once per frame, render or object depending on the update
  33712. * type.
  33713. *
  33714. * @param {Node} node - The node that should be updated.
  33715. */
  33716. updateBeforeNode( node ) {
  33717. const updateType = node.getUpdateBeforeType();
  33718. const reference = node.updateReference( this );
  33719. if ( updateType === NodeUpdateType.FRAME ) {
  33720. const { frameMap } = this._getMaps( this.updateBeforeMap, reference );
  33721. if ( frameMap.get( reference ) !== this.frameId ) {
  33722. if ( node.updateBefore( this ) !== false ) {
  33723. frameMap.set( reference, this.frameId );
  33724. }
  33725. }
  33726. } else if ( updateType === NodeUpdateType.RENDER ) {
  33727. const { renderMap } = this._getMaps( this.updateBeforeMap, reference );
  33728. if ( renderMap.get( reference ) !== this.renderId ) {
  33729. if ( node.updateBefore( this ) !== false ) {
  33730. renderMap.set( reference, this.renderId );
  33731. }
  33732. }
  33733. } else if ( updateType === NodeUpdateType.OBJECT ) {
  33734. node.updateBefore( this );
  33735. }
  33736. }
  33737. /**
  33738. * This method executes the {@link Node#updateAfter} for the given node.
  33739. * It makes sure {@link Node#updateAfterType} is honored meaning the update
  33740. * is only executed once per frame, render or object depending on the update
  33741. * type.
  33742. *
  33743. * @param {Node} node - The node that should be updated.
  33744. */
  33745. updateAfterNode( node ) {
  33746. const updateType = node.getUpdateAfterType();
  33747. const reference = node.updateReference( this );
  33748. if ( updateType === NodeUpdateType.FRAME ) {
  33749. const { frameMap } = this._getMaps( this.updateAfterMap, reference );
  33750. if ( frameMap.get( reference ) !== this.frameId ) {
  33751. if ( node.updateAfter( this ) !== false ) {
  33752. frameMap.set( reference, this.frameId );
  33753. }
  33754. }
  33755. } else if ( updateType === NodeUpdateType.RENDER ) {
  33756. const { renderMap } = this._getMaps( this.updateAfterMap, reference );
  33757. if ( renderMap.get( reference ) !== this.renderId ) {
  33758. if ( node.updateAfter( this ) !== false ) {
  33759. renderMap.set( reference, this.renderId );
  33760. }
  33761. }
  33762. } else if ( updateType === NodeUpdateType.OBJECT ) {
  33763. node.updateAfter( this );
  33764. }
  33765. }
  33766. /**
  33767. * This method executes the {@link Node#update} for the given node.
  33768. * It makes sure {@link Node#updateType} is honored meaning the update
  33769. * is only executed once per frame, render or object depending on the update
  33770. * type.
  33771. *
  33772. * @param {Node} node - The node that should be updated.
  33773. */
  33774. updateNode( node ) {
  33775. const updateType = node.getUpdateType();
  33776. const reference = node.updateReference( this );
  33777. if ( updateType === NodeUpdateType.FRAME ) {
  33778. const { frameMap } = this._getMaps( this.updateMap, reference );
  33779. if ( frameMap.get( reference ) !== this.frameId ) {
  33780. if ( node.update( this ) !== false ) {
  33781. frameMap.set( reference, this.frameId );
  33782. }
  33783. }
  33784. } else if ( updateType === NodeUpdateType.RENDER ) {
  33785. const { renderMap } = this._getMaps( this.updateMap, reference );
  33786. if ( renderMap.get( reference ) !== this.renderId ) {
  33787. if ( node.update( this ) !== false ) {
  33788. renderMap.set( reference, this.renderId );
  33789. }
  33790. }
  33791. } else if ( updateType === NodeUpdateType.OBJECT ) {
  33792. node.update( this );
  33793. }
  33794. }
  33795. /**
  33796. * Updates the internal state of the node frame. This method is
  33797. * called by the renderer in its internal animation loop.
  33798. */
  33799. update() {
  33800. this.frameId ++;
  33801. if ( this.lastTime === undefined ) this.lastTime = performance.now();
  33802. this.deltaTime = ( performance.now() - this.lastTime ) / 1000;
  33803. this.lastTime = performance.now();
  33804. this.time += this.deltaTime;
  33805. }
  33806. }
  33807. /**
  33808. * Describes the input of a {@link NodeFunction}.
  33809. */
  33810. class NodeFunctionInput {
  33811. /**
  33812. * Constructs a new node function input.
  33813. *
  33814. * @param {string} type - The input type.
  33815. * @param {string} name - The input name.
  33816. * @param {?number} [count=null] - If the input is an Array, count will be the length.
  33817. * @param {('in'|'out'|'inout')} [qualifier=''] - The parameter qualifier (only relevant for GLSL).
  33818. * @param {boolean} [isConst=false] - Whether the input uses a const qualifier or not (only relevant for GLSL).
  33819. */
  33820. constructor( type, name, count = null, qualifier = '', isConst = false ) {
  33821. /**
  33822. * The input type.
  33823. *
  33824. * @type {string}
  33825. */
  33826. this.type = type;
  33827. /**
  33828. * The input name.
  33829. *
  33830. * @type {string}
  33831. */
  33832. this.name = name;
  33833. /**
  33834. * If the input is an Array, count will be the length.
  33835. *
  33836. * @type {?number}
  33837. * @default null
  33838. */
  33839. this.count = count;
  33840. /**
  33841. *The parameter qualifier (only relevant for GLSL).
  33842. *
  33843. * @type {('in'|'out'|'inout')}
  33844. * @default ''
  33845. */
  33846. this.qualifier = qualifier;
  33847. /**
  33848. * Whether the input uses a const qualifier or not (only relevant for GLSL).
  33849. *
  33850. * @type {boolean}
  33851. * @default false
  33852. */
  33853. this.isConst = isConst;
  33854. }
  33855. }
  33856. NodeFunctionInput.isNodeFunctionInput = true;
  33857. /**
  33858. * Module for representing directional lights as nodes.
  33859. *
  33860. * @augments AnalyticLightNode
  33861. */
  33862. class DirectionalLightNode extends AnalyticLightNode {
  33863. static get type() {
  33864. return 'DirectionalLightNode';
  33865. }
  33866. /**
  33867. * Constructs a new directional light node.
  33868. *
  33869. * @param {?DirectionalLight} [light=null] - The directional light source.
  33870. */
  33871. constructor( light = null ) {
  33872. super( light );
  33873. }
  33874. setupDirect() {
  33875. const lightColor = this.colorNode;
  33876. const lightDirection = lightTargetDirection( this.light );
  33877. return { lightDirection, lightColor };
  33878. }
  33879. }
  33880. const _matrix41 = /*@__PURE__*/ new Matrix4();
  33881. const _matrix42 = /*@__PURE__*/ new Matrix4();
  33882. let _ltcLib = null;
  33883. /**
  33884. * Module for representing rect area lights as nodes.
  33885. *
  33886. * @augments AnalyticLightNode
  33887. */
  33888. class RectAreaLightNode extends AnalyticLightNode {
  33889. static get type() {
  33890. return 'RectAreaLightNode';
  33891. }
  33892. /**
  33893. * Constructs a new rect area light node.
  33894. *
  33895. * @param {?RectAreaLight} [light=null] - The rect area light source.
  33896. */
  33897. constructor( light = null ) {
  33898. super( light );
  33899. /**
  33900. * Uniform node representing the half height of the are light.
  33901. *
  33902. * @type {UniformNode<vec3>}
  33903. */
  33904. this.halfHeight = uniform( new Vector3() ).setGroup( renderGroup );
  33905. /**
  33906. * Uniform node representing the half width of the are light.
  33907. *
  33908. * @type {UniformNode<vec3>}
  33909. */
  33910. this.halfWidth = uniform( new Vector3() ).setGroup( renderGroup );
  33911. /**
  33912. * The `updateType` is set to `NodeUpdateType.RENDER` since the light
  33913. * relies on `viewMatrix` which might vary per render call.
  33914. *
  33915. * @type {string}
  33916. * @default 'render'
  33917. */
  33918. this.updateType = NodeUpdateType.RENDER;
  33919. }
  33920. /**
  33921. * Overwritten to updated rect area light specific uniforms.
  33922. *
  33923. * @param {NodeFrame} frame - A reference to the current node frame.
  33924. */
  33925. update( frame ) {
  33926. super.update( frame );
  33927. const { light } = this;
  33928. const viewMatrix = frame.camera.matrixWorldInverse;
  33929. _matrix42.identity();
  33930. _matrix41.copy( light.matrixWorld );
  33931. _matrix41.premultiply( viewMatrix );
  33932. _matrix42.extractRotation( _matrix41 );
  33933. this.halfWidth.value.set( light.width * 0.5, 0.0, 0.0 );
  33934. this.halfHeight.value.set( 0.0, light.height * 0.5, 0.0 );
  33935. this.halfWidth.value.applyMatrix4( _matrix42 );
  33936. this.halfHeight.value.applyMatrix4( _matrix42 );
  33937. }
  33938. setupDirectRectArea( builder ) {
  33939. let ltc_1, ltc_2;
  33940. if ( builder.isAvailable( 'float32Filterable' ) ) {
  33941. ltc_1 = texture( _ltcLib.LTC_FLOAT_1 );
  33942. ltc_2 = texture( _ltcLib.LTC_FLOAT_2 );
  33943. } else {
  33944. ltc_1 = texture( _ltcLib.LTC_HALF_1 );
  33945. ltc_2 = texture( _ltcLib.LTC_HALF_2 );
  33946. }
  33947. const { colorNode, light } = this;
  33948. const lightPosition = lightViewPosition( light );
  33949. return {
  33950. lightColor: colorNode,
  33951. lightPosition,
  33952. halfWidth: this.halfWidth,
  33953. halfHeight: this.halfHeight,
  33954. ltc_1,
  33955. ltc_2
  33956. };
  33957. }
  33958. /**
  33959. * Used to configure the internal BRDF approximation texture data.
  33960. *
  33961. * @param {RectAreaLightTexturesLib} ltc - The BRDF approximation texture data.
  33962. */
  33963. static setLTC( ltc ) {
  33964. _ltcLib = ltc;
  33965. }
  33966. }
  33967. /**
  33968. * Module for representing spot lights as nodes.
  33969. *
  33970. * @augments AnalyticLightNode
  33971. */
  33972. class SpotLightNode extends AnalyticLightNode {
  33973. static get type() {
  33974. return 'SpotLightNode';
  33975. }
  33976. /**
  33977. * Constructs a new spot light node.
  33978. *
  33979. * @param {?SpotLight} [light=null] - The spot light source.
  33980. */
  33981. constructor( light = null ) {
  33982. super( light );
  33983. /**
  33984. * Uniform node representing the cone cosine.
  33985. *
  33986. * @type {UniformNode<float>}
  33987. */
  33988. this.coneCosNode = uniform( 0 ).setGroup( renderGroup );
  33989. /**
  33990. * Uniform node representing the penumbra cosine.
  33991. *
  33992. * @type {UniformNode<float>}
  33993. */
  33994. this.penumbraCosNode = uniform( 0 ).setGroup( renderGroup );
  33995. /**
  33996. * Uniform node representing the cutoff distance.
  33997. *
  33998. * @type {UniformNode<float>}
  33999. */
  34000. this.cutoffDistanceNode = uniform( 0 ).setGroup( renderGroup );
  34001. /**
  34002. * Uniform node representing the decay exponent.
  34003. *
  34004. * @type {UniformNode<float>}
  34005. */
  34006. this.decayExponentNode = uniform( 0 ).setGroup( renderGroup );
  34007. /**
  34008. * Uniform node representing the light color.
  34009. *
  34010. * @type {UniformNode<Color>}
  34011. */
  34012. this.colorNode = uniform( this.color ).setGroup( renderGroup );
  34013. }
  34014. /**
  34015. * Overwritten to updated spot light specific uniforms.
  34016. *
  34017. * @param {NodeFrame} frame - A reference to the current node frame.
  34018. */
  34019. update( frame ) {
  34020. super.update( frame );
  34021. const { light } = this;
  34022. this.coneCosNode.value = Math.cos( light.angle );
  34023. this.penumbraCosNode.value = Math.cos( light.angle * ( 1 - light.penumbra ) );
  34024. this.cutoffDistanceNode.value = light.distance;
  34025. this.decayExponentNode.value = light.decay;
  34026. }
  34027. /**
  34028. * Computes the spot attenuation for the given angle.
  34029. *
  34030. * @param {NodeBuilder} builder - The node builder.
  34031. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  34032. * @return {Node<float>} The spot attenuation.
  34033. */
  34034. getSpotAttenuation( builder, angleCosine ) {
  34035. const { coneCosNode, penumbraCosNode } = this;
  34036. return smoothstep( coneCosNode, penumbraCosNode, angleCosine );
  34037. }
  34038. getLightCoord( builder ) {
  34039. const properties = builder.getNodeProperties( this );
  34040. let projectionUV = properties.projectionUV;
  34041. if ( projectionUV === undefined ) {
  34042. projectionUV = lightProjectionUV( this.light, builder.context.positionWorld );
  34043. properties.projectionUV = projectionUV;
  34044. }
  34045. return projectionUV;
  34046. }
  34047. setupDirect( builder ) {
  34048. const { colorNode, cutoffDistanceNode, decayExponentNode, light } = this;
  34049. const lightVector = this.getLightVector( builder );
  34050. const lightDirection = lightVector.normalize();
  34051. const angleCos = lightDirection.dot( lightTargetDirection( light ) );
  34052. const spotAttenuation = this.getSpotAttenuation( builder, angleCos );
  34053. const lightDistance = lightVector.length();
  34054. const lightAttenuation = getDistanceAttenuation( {
  34055. lightDistance,
  34056. cutoffDistance: cutoffDistanceNode,
  34057. decayExponent: decayExponentNode
  34058. } );
  34059. let lightColor = colorNode.mul( spotAttenuation ).mul( lightAttenuation );
  34060. let projected, lightCoord;
  34061. if ( light.colorNode ) {
  34062. lightCoord = this.getLightCoord( builder );
  34063. projected = light.colorNode( lightCoord );
  34064. } else if ( light.map ) {
  34065. lightCoord = this.getLightCoord( builder );
  34066. projected = texture( light.map, lightCoord.xy ).onRenderUpdate( () => light.map );
  34067. }
  34068. if ( projected ) {
  34069. const inSpotLightMap = lightCoord.mul( 2. ).sub( 1. ).abs().lessThan( 1. ).all();
  34070. lightColor = inSpotLightMap.select( lightColor.mul( projected ), lightColor );
  34071. }
  34072. return { lightColor, lightDirection };
  34073. }
  34074. }
  34075. /**
  34076. * An IES version of the default spot light node.
  34077. *
  34078. * @augments SpotLightNode
  34079. */
  34080. class IESSpotLightNode extends SpotLightNode {
  34081. static get type() {
  34082. return 'IESSpotLightNode';
  34083. }
  34084. /**
  34085. * Overwrites the default implementation to compute an IES conform spot attenuation.
  34086. *
  34087. * @param {NodeBuilder} builder - The node builder.
  34088. * @param {Node<float>} angleCosine - The angle to compute the spot attenuation for.
  34089. * @return {Node<float>} The spot attenuation.
  34090. */
  34091. getSpotAttenuation( builder, angleCosine ) {
  34092. const iesMap = this.light.iesMap;
  34093. let spotAttenuation = null;
  34094. if ( iesMap && iesMap.isTexture === true ) {
  34095. const angle = angleCosine.acos().mul( 1.0 / Math.PI );
  34096. spotAttenuation = texture( iesMap, vec2( angle, 0 ), 0 ).r;
  34097. } else {
  34098. spotAttenuation = super.getSpotAttenuation( angleCosine );
  34099. }
  34100. return spotAttenuation;
  34101. }
  34102. }
  34103. const sdBox = /*@__PURE__*/ Fn( ( [ p, b ] ) => {
  34104. const d = p.abs().sub( b );
  34105. return length( max$1( d, 0.0 ) ).add( min$1( max$1( d.x, d.y ), 0.0 ) );
  34106. } );
  34107. /**
  34108. * An implementation of a projector light node.
  34109. *
  34110. * @augments SpotLightNode
  34111. */
  34112. class ProjectorLightNode extends SpotLightNode {
  34113. static get type() {
  34114. return 'ProjectorLightNode';
  34115. }
  34116. update( frame ) {
  34117. super.update( frame );
  34118. const light = this.light;
  34119. this.penumbraCosNode.value = Math.min( Math.cos( light.angle * ( 1 - light.penumbra ) ), .99999 );
  34120. if ( light.aspect === null ) {
  34121. let aspect = 1;
  34122. if ( light.map !== null ) {
  34123. aspect = light.map.width / light.map.height;
  34124. }
  34125. light.shadow.aspect = aspect;
  34126. } else {
  34127. light.shadow.aspect = light.aspect;
  34128. }
  34129. }
  34130. /**
  34131. * Overwrites the default implementation to compute projection attenuation.
  34132. *
  34133. * @param {NodeBuilder} builder - The node builder.
  34134. * @return {Node<float>} The spot attenuation.
  34135. */
  34136. getSpotAttenuation( builder ) {
  34137. const penumbraCos = this.penumbraCosNode;
  34138. const spotLightCoord = this.getLightCoord( builder );
  34139. const coord = spotLightCoord.xyz.div( spotLightCoord.w );
  34140. const boxDist = sdBox( coord.xy.sub( vec2( 0.5 ) ), vec2( 0.5 ) );
  34141. const angleFactor = div( -1, sub( 1.0, acos( penumbraCos ) ).sub( 1.0 ) );
  34142. const attenuation = saturate( boxDist.mul( -2 ).mul( angleFactor ) );
  34143. return attenuation;
  34144. }
  34145. }
  34146. /**
  34147. * Module for representing ambient lights as nodes.
  34148. *
  34149. * @augments AnalyticLightNode
  34150. */
  34151. class AmbientLightNode extends AnalyticLightNode {
  34152. static get type() {
  34153. return 'AmbientLightNode';
  34154. }
  34155. /**
  34156. * Constructs a new ambient light node.
  34157. *
  34158. * @param {?AmbientLight} [light=null] - The ambient light source.
  34159. */
  34160. constructor( light = null ) {
  34161. super( light );
  34162. }
  34163. setup( { context } ) {
  34164. context.irradiance.addAssign( this.colorNode );
  34165. }
  34166. }
  34167. /**
  34168. * Module for representing hemisphere lights as nodes.
  34169. *
  34170. * @augments AnalyticLightNode
  34171. */
  34172. class HemisphereLightNode extends AnalyticLightNode {
  34173. static get type() {
  34174. return 'HemisphereLightNode';
  34175. }
  34176. /**
  34177. * Constructs a new hemisphere light node.
  34178. *
  34179. * @param {?HemisphereLight} [light=null] - The hemisphere light source.
  34180. */
  34181. constructor( light = null ) {
  34182. super( light );
  34183. /**
  34184. * Uniform node representing the light's position.
  34185. *
  34186. * @type {UniformNode<vec3>}
  34187. */
  34188. this.lightPositionNode = lightPosition( light );
  34189. /**
  34190. * A node representing the light's direction.
  34191. *
  34192. * @type {Node<vec3>}
  34193. */
  34194. this.lightDirectionNode = this.lightPositionNode.normalize();
  34195. /**
  34196. * Uniform node representing the light's ground color.
  34197. *
  34198. * @type {UniformNode<vec3>}
  34199. */
  34200. this.groundColorNode = uniform( new Color() ).setGroup( renderGroup );
  34201. }
  34202. /**
  34203. * Overwritten to updated hemisphere light specific uniforms.
  34204. *
  34205. * @param {NodeFrame} frame - A reference to the current node frame.
  34206. */
  34207. update( frame ) {
  34208. const { light } = this;
  34209. super.update( frame );
  34210. this.lightPositionNode.object3d = light;
  34211. this.groundColorNode.value.copy( light.groundColor ).multiplyScalar( light.intensity );
  34212. }
  34213. setup( builder ) {
  34214. const { colorNode, groundColorNode, lightDirectionNode } = this;
  34215. const dotNL = normalWorld.dot( lightDirectionNode );
  34216. const hemiDiffuseWeight = dotNL.mul( 0.5 ).add( 0.5 );
  34217. const irradiance = mix( groundColorNode, colorNode, hemiDiffuseWeight );
  34218. builder.context.irradiance.addAssign( irradiance );
  34219. }
  34220. }
  34221. /**
  34222. * Module for representing light probes as nodes.
  34223. *
  34224. * @augments AnalyticLightNode
  34225. */
  34226. class LightProbeNode extends AnalyticLightNode {
  34227. static get type() {
  34228. return 'LightProbeNode';
  34229. }
  34230. /**
  34231. * Constructs a new light probe node.
  34232. *
  34233. * @param {?LightProbe} [light=null] - The light probe.
  34234. */
  34235. constructor( light = null ) {
  34236. super( light );
  34237. const array = [];
  34238. for ( let i = 0; i < 9; i ++ ) array.push( new Vector3() );
  34239. /**
  34240. * Light probe represented as a uniform of spherical harmonics.
  34241. *
  34242. * @type {UniformArrayNode}
  34243. */
  34244. this.lightProbe = uniformArray( array );
  34245. }
  34246. /**
  34247. * Overwritten to updated light probe specific uniforms.
  34248. *
  34249. * @param {NodeFrame} frame - A reference to the current node frame.
  34250. */
  34251. update( frame ) {
  34252. const { light } = this;
  34253. super.update( frame );
  34254. //
  34255. for ( let i = 0; i < 9; i ++ ) {
  34256. this.lightProbe.array[ i ].copy( light.sh.coefficients[ i ] ).multiplyScalar( light.intensity );
  34257. }
  34258. }
  34259. setup( builder ) {
  34260. const irradiance = getShIrradianceAt( normalWorld, this.lightProbe );
  34261. builder.context.irradiance.addAssign( irradiance );
  34262. }
  34263. }
  34264. /**
  34265. * Base class for node parsers. A derived parser must be implemented
  34266. * for each supported native shader language.
  34267. */
  34268. class NodeParser {
  34269. /**
  34270. * The method parses the given native code an returns a node function.
  34271. *
  34272. * @abstract
  34273. * @param {string} source - The native shader code.
  34274. * @return {NodeFunction} A node function.
  34275. */
  34276. parseFunction( /*source*/ ) {
  34277. console.warn( 'Abstract function.' );
  34278. }
  34279. }
  34280. /**
  34281. * Base class for node functions. A derived module must be implemented
  34282. * for each supported native shader language. Similar to other `Node*` modules,
  34283. * this class is only relevant during the building process and not used
  34284. * in user-level code.
  34285. */
  34286. class NodeFunction {
  34287. /**
  34288. * Constructs a new node function.
  34289. *
  34290. * @param {string} type - The node type. This type is the return type of the node function.
  34291. * @param {Array<NodeFunctionInput>} inputs - The function's inputs.
  34292. * @param {string} [name=''] - The function's name.
  34293. * @param {string} [precision=''] - The precision qualifier.
  34294. */
  34295. constructor( type, inputs, name = '', precision = '' ) {
  34296. /**
  34297. * The node type. This type is the return type of the node function.
  34298. *
  34299. * @type {string}
  34300. */
  34301. this.type = type;
  34302. /**
  34303. * The function's inputs.
  34304. *
  34305. * @type {Array<NodeFunctionInput>}
  34306. */
  34307. this.inputs = inputs;
  34308. /**
  34309. * The name of the uniform.
  34310. *
  34311. * @type {string}
  34312. * @default ''
  34313. */
  34314. this.name = name;
  34315. /**
  34316. * The precision qualifier.
  34317. *
  34318. * @type {string}
  34319. * @default ''
  34320. */
  34321. this.precision = precision;
  34322. }
  34323. /**
  34324. * This method returns the native code of the node function.
  34325. *
  34326. * @abstract
  34327. * @param {string} name - The function's name.
  34328. * @return {string} A shader code.
  34329. */
  34330. getCode( /*name = this.name*/ ) {
  34331. console.warn( 'Abstract function.' );
  34332. }
  34333. }
  34334. NodeFunction.isNodeFunction = true;
  34335. const declarationRegexp$1 = /^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i;
  34336. const propertiesRegexp$1 = /[a-z_0-9]+/ig;
  34337. const pragmaMain = '#pragma main';
  34338. const parse$1 = ( source ) => {
  34339. source = source.trim();
  34340. const pragmaMainIndex = source.indexOf( pragmaMain );
  34341. const mainCode = pragmaMainIndex !== -1 ? source.slice( pragmaMainIndex + pragmaMain.length ) : source;
  34342. const declaration = mainCode.match( declarationRegexp$1 );
  34343. if ( declaration !== null && declaration.length === 5 ) {
  34344. // tokenizer
  34345. const inputsCode = declaration[ 4 ];
  34346. const propsMatches = [];
  34347. let nameMatch = null;
  34348. while ( ( nameMatch = propertiesRegexp$1.exec( inputsCode ) ) !== null ) {
  34349. propsMatches.push( nameMatch );
  34350. }
  34351. // parser
  34352. const inputs = [];
  34353. let i = 0;
  34354. while ( i < propsMatches.length ) {
  34355. const isConst = propsMatches[ i ][ 0 ] === 'const';
  34356. if ( isConst === true ) {
  34357. i ++;
  34358. }
  34359. let qualifier = propsMatches[ i ][ 0 ];
  34360. if ( qualifier === 'in' || qualifier === 'out' || qualifier === 'inout' ) {
  34361. i ++;
  34362. } else {
  34363. qualifier = '';
  34364. }
  34365. const type = propsMatches[ i ++ ][ 0 ];
  34366. let count = Number.parseInt( propsMatches[ i ][ 0 ] );
  34367. if ( Number.isNaN( count ) === false ) i ++;
  34368. else count = null;
  34369. const name = propsMatches[ i ++ ][ 0 ];
  34370. inputs.push( new NodeFunctionInput( type, name, count, qualifier, isConst ) );
  34371. }
  34372. //
  34373. const blockCode = mainCode.substring( declaration[ 0 ].length );
  34374. const name = declaration[ 3 ] !== undefined ? declaration[ 3 ] : '';
  34375. const type = declaration[ 2 ];
  34376. const precision = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  34377. const headerCode = pragmaMainIndex !== -1 ? source.slice( 0, pragmaMainIndex ) : '';
  34378. return {
  34379. type,
  34380. inputs,
  34381. name,
  34382. precision,
  34383. inputsCode,
  34384. blockCode,
  34385. headerCode
  34386. };
  34387. } else {
  34388. throw new Error( 'FunctionNode: Function is not a GLSL code.' );
  34389. }
  34390. };
  34391. /**
  34392. * This class represents a GLSL node function.
  34393. *
  34394. * @augments NodeFunction
  34395. */
  34396. class GLSLNodeFunction extends NodeFunction {
  34397. /**
  34398. * Constructs a new GLSL node function.
  34399. *
  34400. * @param {string} source - The GLSL source.
  34401. */
  34402. constructor( source ) {
  34403. const { type, inputs, name, precision, inputsCode, blockCode, headerCode } = parse$1( source );
  34404. super( type, inputs, name, precision );
  34405. this.inputsCode = inputsCode;
  34406. this.blockCode = blockCode;
  34407. this.headerCode = headerCode;
  34408. }
  34409. /**
  34410. * This method returns the GLSL code of the node function.
  34411. *
  34412. * @param {string} [name=this.name] - The function's name.
  34413. * @return {string} The shader code.
  34414. */
  34415. getCode( name = this.name ) {
  34416. let code;
  34417. const blockCode = this.blockCode;
  34418. if ( blockCode !== '' ) {
  34419. const { type, inputsCode, headerCode, precision } = this;
  34420. let declarationCode = `${ type } ${ name } ( ${ inputsCode.trim() } )`;
  34421. if ( precision !== '' ) {
  34422. declarationCode = `${ precision } ${ declarationCode }`;
  34423. }
  34424. code = headerCode + declarationCode + blockCode;
  34425. } else {
  34426. // interface function
  34427. code = '';
  34428. }
  34429. return code;
  34430. }
  34431. }
  34432. /**
  34433. * A GLSL node parser.
  34434. *
  34435. * @augments NodeParser
  34436. */
  34437. class GLSLNodeParser extends NodeParser {
  34438. /**
  34439. * The method parses the given GLSL code an returns a node function.
  34440. *
  34441. * @param {string} source - The GLSL code.
  34442. * @return {GLSLNodeFunction} A node function.
  34443. */
  34444. parseFunction( source ) {
  34445. return new GLSLNodeFunction( source );
  34446. }
  34447. }
  34448. const _outputNodeMap = new WeakMap();
  34449. const _chainKeys$2 = [];
  34450. const _cacheKeyValues = [];
  34451. /**
  34452. * This renderer module manages node-related objects and is the
  34453. * primary interface between the renderer and the node system.
  34454. *
  34455. * @private
  34456. * @augments DataMap
  34457. */
  34458. class Nodes extends DataMap {
  34459. /**
  34460. * Constructs a new nodes management component.
  34461. *
  34462. * @param {Renderer} renderer - The renderer.
  34463. * @param {Backend} backend - The renderer's backend.
  34464. */
  34465. constructor( renderer, backend ) {
  34466. super();
  34467. /**
  34468. * The renderer.
  34469. *
  34470. * @type {Renderer}
  34471. */
  34472. this.renderer = renderer;
  34473. /**
  34474. * The renderer's backend.
  34475. *
  34476. * @type {Backend}
  34477. */
  34478. this.backend = backend;
  34479. /**
  34480. * The node frame.
  34481. *
  34482. * @type {Renderer}
  34483. */
  34484. this.nodeFrame = new NodeFrame();
  34485. /**
  34486. * A cache for managing node builder states.
  34487. *
  34488. * @type {Map<number,NodeBuilderState>}
  34489. */
  34490. this.nodeBuilderCache = new Map();
  34491. /**
  34492. * A cache for managing data cache key data.
  34493. *
  34494. * @type {ChainMap}
  34495. */
  34496. this.callHashCache = new ChainMap();
  34497. /**
  34498. * A cache for managing node uniforms group data.
  34499. *
  34500. * @type {ChainMap}
  34501. */
  34502. this.groupsData = new ChainMap();
  34503. /**
  34504. * A cache for managing node objects of
  34505. * scene properties like fog or environments.
  34506. *
  34507. * @type {Object<string,WeakMap>}
  34508. */
  34509. this.cacheLib = {};
  34510. }
  34511. /**
  34512. * Returns `true` if the given node uniforms group must be updated or not.
  34513. *
  34514. * @param {NodeUniformsGroup} nodeUniformsGroup - The node uniforms group.
  34515. * @return {boolean} Whether the node uniforms group requires an update or not.
  34516. */
  34517. updateGroup( nodeUniformsGroup ) {
  34518. const groupNode = nodeUniformsGroup.groupNode;
  34519. const name = groupNode.name;
  34520. // objectGroup is always updated
  34521. if ( name === objectGroup.name ) return true;
  34522. // renderGroup is updated once per render/compute call
  34523. if ( name === renderGroup.name ) {
  34524. const uniformsGroupData = this.get( nodeUniformsGroup );
  34525. const renderId = this.nodeFrame.renderId;
  34526. if ( uniformsGroupData.renderId !== renderId ) {
  34527. uniformsGroupData.renderId = renderId;
  34528. return true;
  34529. }
  34530. return false;
  34531. }
  34532. // frameGroup is updated once per frame
  34533. if ( name === frameGroup.name ) {
  34534. const uniformsGroupData = this.get( nodeUniformsGroup );
  34535. const frameId = this.nodeFrame.frameId;
  34536. if ( uniformsGroupData.frameId !== frameId ) {
  34537. uniformsGroupData.frameId = frameId;
  34538. return true;
  34539. }
  34540. return false;
  34541. }
  34542. // other groups are updated just when groupNode.needsUpdate is true
  34543. _chainKeys$2[ 0 ] = groupNode;
  34544. _chainKeys$2[ 1 ] = nodeUniformsGroup;
  34545. let groupData = this.groupsData.get( _chainKeys$2 );
  34546. if ( groupData === undefined ) this.groupsData.set( _chainKeys$2, groupData = {} );
  34547. _chainKeys$2.length = 0;
  34548. if ( groupData.version !== groupNode.version ) {
  34549. groupData.version = groupNode.version;
  34550. return true;
  34551. }
  34552. return false;
  34553. }
  34554. /**
  34555. * Returns the cache key for the given render object.
  34556. *
  34557. * @param {RenderObject} renderObject - The render object.
  34558. * @return {number} The cache key.
  34559. */
  34560. getForRenderCacheKey( renderObject ) {
  34561. return renderObject.initialCacheKey;
  34562. }
  34563. /**
  34564. * Returns a node builder state for the given render object.
  34565. *
  34566. * @param {RenderObject} renderObject - The render object.
  34567. * @return {NodeBuilderState} The node builder state.
  34568. */
  34569. getForRender( renderObject ) {
  34570. const renderObjectData = this.get( renderObject );
  34571. let nodeBuilderState = renderObjectData.nodeBuilderState;
  34572. if ( nodeBuilderState === undefined ) {
  34573. const { nodeBuilderCache } = this;
  34574. const cacheKey = this.getForRenderCacheKey( renderObject );
  34575. nodeBuilderState = nodeBuilderCache.get( cacheKey );
  34576. if ( nodeBuilderState === undefined ) {
  34577. const nodeBuilder = this.backend.createNodeBuilder( renderObject.object, this.renderer );
  34578. nodeBuilder.scene = renderObject.scene;
  34579. nodeBuilder.material = renderObject.material;
  34580. nodeBuilder.camera = renderObject.camera;
  34581. nodeBuilder.context.material = renderObject.material;
  34582. nodeBuilder.lightsNode = renderObject.lightsNode;
  34583. nodeBuilder.environmentNode = this.getEnvironmentNode( renderObject.scene );
  34584. nodeBuilder.fogNode = this.getFogNode( renderObject.scene );
  34585. nodeBuilder.clippingContext = renderObject.clippingContext;
  34586. if ( this.renderer.getOutputRenderTarget() ? this.renderer.getOutputRenderTarget().multiview : false ) {
  34587. nodeBuilder.enableMultiview();
  34588. }
  34589. nodeBuilder.build();
  34590. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  34591. nodeBuilderCache.set( cacheKey, nodeBuilderState );
  34592. }
  34593. nodeBuilderState.usedTimes ++;
  34594. renderObjectData.nodeBuilderState = nodeBuilderState;
  34595. }
  34596. return nodeBuilderState;
  34597. }
  34598. /**
  34599. * Deletes the given object from the internal data map
  34600. *
  34601. * @param {any} object - The object to delete.
  34602. * @return {?Object} The deleted dictionary.
  34603. */
  34604. delete( object ) {
  34605. if ( object.isRenderObject ) {
  34606. const nodeBuilderState = this.get( object ).nodeBuilderState;
  34607. nodeBuilderState.usedTimes --;
  34608. if ( nodeBuilderState.usedTimes === 0 ) {
  34609. this.nodeBuilderCache.delete( this.getForRenderCacheKey( object ) );
  34610. }
  34611. }
  34612. return super.delete( object );
  34613. }
  34614. /**
  34615. * Returns a node builder state for the given compute node.
  34616. *
  34617. * @param {Node} computeNode - The compute node.
  34618. * @return {NodeBuilderState} The node builder state.
  34619. */
  34620. getForCompute( computeNode ) {
  34621. const computeData = this.get( computeNode );
  34622. let nodeBuilderState = computeData.nodeBuilderState;
  34623. if ( nodeBuilderState === undefined ) {
  34624. const nodeBuilder = this.backend.createNodeBuilder( computeNode, this.renderer );
  34625. nodeBuilder.build();
  34626. nodeBuilderState = this._createNodeBuilderState( nodeBuilder );
  34627. computeData.nodeBuilderState = nodeBuilderState;
  34628. }
  34629. return nodeBuilderState;
  34630. }
  34631. /**
  34632. * Creates a node builder state for the given node builder.
  34633. *
  34634. * @private
  34635. * @param {NodeBuilder} nodeBuilder - The node builder.
  34636. * @return {NodeBuilderState} The node builder state.
  34637. */
  34638. _createNodeBuilderState( nodeBuilder ) {
  34639. return new NodeBuilderState(
  34640. nodeBuilder.vertexShader,
  34641. nodeBuilder.fragmentShader,
  34642. nodeBuilder.computeShader,
  34643. nodeBuilder.getAttributesArray(),
  34644. nodeBuilder.getBindings(),
  34645. nodeBuilder.updateNodes,
  34646. nodeBuilder.updateBeforeNodes,
  34647. nodeBuilder.updateAfterNodes,
  34648. nodeBuilder.observer,
  34649. nodeBuilder.transforms
  34650. );
  34651. }
  34652. /**
  34653. * Returns an environment node for the current configured
  34654. * scene environment.
  34655. *
  34656. * @param {Scene} scene - The scene.
  34657. * @return {Node} A node representing the current scene environment.
  34658. */
  34659. getEnvironmentNode( scene ) {
  34660. this.updateEnvironment( scene );
  34661. let environmentNode = null;
  34662. if ( scene.environmentNode && scene.environmentNode.isNode ) {
  34663. environmentNode = scene.environmentNode;
  34664. } else {
  34665. const sceneData = this.get( scene );
  34666. if ( sceneData.environmentNode ) {
  34667. environmentNode = sceneData.environmentNode;
  34668. }
  34669. }
  34670. return environmentNode;
  34671. }
  34672. /**
  34673. * Returns a background node for the current configured
  34674. * scene background.
  34675. *
  34676. * @param {Scene} scene - The scene.
  34677. * @return {Node} A node representing the current scene background.
  34678. */
  34679. getBackgroundNode( scene ) {
  34680. this.updateBackground( scene );
  34681. let backgroundNode = null;
  34682. if ( scene.backgroundNode && scene.backgroundNode.isNode ) {
  34683. backgroundNode = scene.backgroundNode;
  34684. } else {
  34685. const sceneData = this.get( scene );
  34686. if ( sceneData.backgroundNode ) {
  34687. backgroundNode = sceneData.backgroundNode;
  34688. }
  34689. }
  34690. return backgroundNode;
  34691. }
  34692. /**
  34693. * Returns a fog node for the current configured scene fog.
  34694. *
  34695. * @param {Scene} scene - The scene.
  34696. * @return {Node} A node representing the current scene fog.
  34697. */
  34698. getFogNode( scene ) {
  34699. this.updateFog( scene );
  34700. return scene.fogNode || this.get( scene ).fogNode || null;
  34701. }
  34702. /**
  34703. * Returns a cache key for the given scene and lights node.
  34704. * This key is used by `RenderObject` as a part of the dynamic
  34705. * cache key (a key that must be checked every time the render
  34706. * objects is drawn).
  34707. *
  34708. * @param {Scene} scene - The scene.
  34709. * @param {LightsNode} lightsNode - The lights node.
  34710. * @return {number} The cache key.
  34711. */
  34712. getCacheKey( scene, lightsNode ) {
  34713. _chainKeys$2[ 0 ] = scene;
  34714. _chainKeys$2[ 1 ] = lightsNode;
  34715. const callId = this.renderer.info.calls;
  34716. const cacheKeyData = this.callHashCache.get( _chainKeys$2 ) || {};
  34717. if ( cacheKeyData.callId !== callId ) {
  34718. const environmentNode = this.getEnvironmentNode( scene );
  34719. const fogNode = this.getFogNode( scene );
  34720. if ( lightsNode ) _cacheKeyValues.push( lightsNode.getCacheKey( true ) );
  34721. if ( environmentNode ) _cacheKeyValues.push( environmentNode.getCacheKey() );
  34722. if ( fogNode ) _cacheKeyValues.push( fogNode.getCacheKey() );
  34723. _cacheKeyValues.push( this.renderer.getOutputRenderTarget() && this.renderer.getOutputRenderTarget().multiview ? 1 : 0 );
  34724. _cacheKeyValues.push( this.renderer.shadowMap.enabled ? 1 : 0 );
  34725. cacheKeyData.callId = callId;
  34726. cacheKeyData.cacheKey = hashArray( _cacheKeyValues );
  34727. this.callHashCache.set( _chainKeys$2, cacheKeyData );
  34728. _cacheKeyValues.length = 0;
  34729. }
  34730. _chainKeys$2.length = 0;
  34731. return cacheKeyData.cacheKey;
  34732. }
  34733. /**
  34734. * A boolean that indicates whether tone mapping should be enabled
  34735. * or not.
  34736. *
  34737. * @type {boolean}
  34738. */
  34739. get isToneMappingState() {
  34740. return this.renderer.getRenderTarget() ? false : true;
  34741. }
  34742. /**
  34743. * If a scene background is configured, this method makes sure to
  34744. * represent the background with a corresponding node-based implementation.
  34745. *
  34746. * @param {Scene} scene - The scene.
  34747. */
  34748. updateBackground( scene ) {
  34749. const sceneData = this.get( scene );
  34750. const background = scene.background;
  34751. if ( background ) {
  34752. const forceUpdate = ( scene.backgroundBlurriness === 0 && sceneData.backgroundBlurriness > 0 ) || ( scene.backgroundBlurriness > 0 && sceneData.backgroundBlurriness === 0 );
  34753. if ( sceneData.background !== background || forceUpdate ) {
  34754. const backgroundNode = this.getCacheNode( 'background', background, () => {
  34755. if ( background.isCubeTexture === true || ( background.mapping === EquirectangularReflectionMapping || background.mapping === EquirectangularRefractionMapping || background.mapping === CubeUVReflectionMapping ) ) {
  34756. if ( scene.backgroundBlurriness > 0 || background.mapping === CubeUVReflectionMapping ) {
  34757. return pmremTexture( background );
  34758. } else {
  34759. let envMap;
  34760. if ( background.isCubeTexture === true ) {
  34761. envMap = cubeTexture( background );
  34762. } else {
  34763. envMap = texture( background );
  34764. }
  34765. return cubeMapNode( envMap );
  34766. }
  34767. } else if ( background.isTexture === true ) {
  34768. return texture( background, screenUV.flipY() ).setUpdateMatrix( true );
  34769. } else if ( background.isColor !== true ) {
  34770. console.error( 'WebGPUNodes: Unsupported background configuration.', background );
  34771. }
  34772. }, forceUpdate );
  34773. sceneData.backgroundNode = backgroundNode;
  34774. sceneData.background = background;
  34775. sceneData.backgroundBlurriness = scene.backgroundBlurriness;
  34776. }
  34777. } else if ( sceneData.backgroundNode ) {
  34778. delete sceneData.backgroundNode;
  34779. delete sceneData.background;
  34780. }
  34781. }
  34782. /**
  34783. * This method is part of the caching of nodes which are used to represents the
  34784. * scene's background, fog or environment.
  34785. *
  34786. * @param {string} type - The type of object to cache.
  34787. * @param {Object} object - The object.
  34788. * @param {Function} callback - A callback that produces a node representation for the given object.
  34789. * @param {boolean} [forceUpdate=false] - Whether an update should be enforced or not.
  34790. * @return {Node} The node representation.
  34791. */
  34792. getCacheNode( type, object, callback, forceUpdate = false ) {
  34793. const nodeCache = this.cacheLib[ type ] || ( this.cacheLib[ type ] = new WeakMap() );
  34794. let node = nodeCache.get( object );
  34795. if ( node === undefined || forceUpdate ) {
  34796. node = callback();
  34797. nodeCache.set( object, node );
  34798. }
  34799. return node;
  34800. }
  34801. /**
  34802. * If a scene fog is configured, this method makes sure to
  34803. * represent the fog with a corresponding node-based implementation.
  34804. *
  34805. * @param {Scene} scene - The scene.
  34806. */
  34807. updateFog( scene ) {
  34808. const sceneData = this.get( scene );
  34809. const sceneFog = scene.fog;
  34810. if ( sceneFog ) {
  34811. if ( sceneData.fog !== sceneFog ) {
  34812. const fogNode = this.getCacheNode( 'fog', sceneFog, () => {
  34813. if ( sceneFog.isFogExp2 ) {
  34814. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  34815. const density = reference( 'density', 'float', sceneFog ).setGroup( renderGroup );
  34816. return fog( color, densityFogFactor( density ) );
  34817. } else if ( sceneFog.isFog ) {
  34818. const color = reference( 'color', 'color', sceneFog ).setGroup( renderGroup );
  34819. const near = reference( 'near', 'float', sceneFog ).setGroup( renderGroup );
  34820. const far = reference( 'far', 'float', sceneFog ).setGroup( renderGroup );
  34821. return fog( color, rangeFogFactor( near, far ) );
  34822. } else {
  34823. console.error( 'THREE.Renderer: Unsupported fog configuration.', sceneFog );
  34824. }
  34825. } );
  34826. sceneData.fogNode = fogNode;
  34827. sceneData.fog = sceneFog;
  34828. }
  34829. } else {
  34830. delete sceneData.fogNode;
  34831. delete sceneData.fog;
  34832. }
  34833. }
  34834. /**
  34835. * If a scene environment is configured, this method makes sure to
  34836. * represent the environment with a corresponding node-based implementation.
  34837. *
  34838. * @param {Scene} scene - The scene.
  34839. */
  34840. updateEnvironment( scene ) {
  34841. const sceneData = this.get( scene );
  34842. const environment = scene.environment;
  34843. if ( environment ) {
  34844. if ( sceneData.environment !== environment ) {
  34845. const environmentNode = this.getCacheNode( 'environment', environment, () => {
  34846. if ( environment.isCubeTexture === true ) {
  34847. return cubeTexture( environment );
  34848. } else if ( environment.isTexture === true ) {
  34849. return texture( environment );
  34850. } else {
  34851. console.error( 'Nodes: Unsupported environment configuration.', environment );
  34852. }
  34853. } );
  34854. sceneData.environmentNode = environmentNode;
  34855. sceneData.environment = environment;
  34856. }
  34857. } else if ( sceneData.environmentNode ) {
  34858. delete sceneData.environmentNode;
  34859. delete sceneData.environment;
  34860. }
  34861. }
  34862. getNodeFrame( renderer = this.renderer, scene = null, object = null, camera = null, material = null ) {
  34863. const nodeFrame = this.nodeFrame;
  34864. nodeFrame.renderer = renderer;
  34865. nodeFrame.scene = scene;
  34866. nodeFrame.object = object;
  34867. nodeFrame.camera = camera;
  34868. nodeFrame.material = material;
  34869. return nodeFrame;
  34870. }
  34871. getNodeFrameForRender( renderObject ) {
  34872. return this.getNodeFrame( renderObject.renderer, renderObject.scene, renderObject.object, renderObject.camera, renderObject.material );
  34873. }
  34874. /**
  34875. * Returns the current output cache key.
  34876. *
  34877. * @return {string} The output cache key.
  34878. */
  34879. getOutputCacheKey() {
  34880. const renderer = this.renderer;
  34881. return renderer.toneMapping + ',' + renderer.currentColorSpace + ',' + renderer.xr.isPresenting;
  34882. }
  34883. /**
  34884. * Checks if the output configuration (tone mapping and color space) for
  34885. * the given target has changed.
  34886. *
  34887. * @param {Texture} outputTarget - The output target.
  34888. * @return {boolean} Whether the output configuration has changed or not.
  34889. */
  34890. hasOutputChange( outputTarget ) {
  34891. const cacheKey = _outputNodeMap.get( outputTarget );
  34892. return cacheKey !== this.getOutputCacheKey();
  34893. }
  34894. /**
  34895. * Returns a node that represents the output configuration (tone mapping and
  34896. * color space) for the current target.
  34897. *
  34898. * @param {Texture} outputTarget - The output target.
  34899. * @return {Node} The output node.
  34900. */
  34901. getOutputNode( outputTarget ) {
  34902. const renderer = this.renderer;
  34903. const cacheKey = this.getOutputCacheKey();
  34904. const output = outputTarget.isArrayTexture ?
  34905. texture3D( outputTarget, vec3( screenUV, builtin( 'gl_ViewID_OVR' ) ) ).renderOutput( renderer.toneMapping, renderer.currentColorSpace ) :
  34906. texture( outputTarget, screenUV ).renderOutput( renderer.toneMapping, renderer.currentColorSpace );
  34907. _outputNodeMap.set( outputTarget, cacheKey );
  34908. return output;
  34909. }
  34910. /**
  34911. * Triggers the call of `updateBefore()` methods
  34912. * for all nodes of the given render object.
  34913. *
  34914. * @param {RenderObject} renderObject - The render object.
  34915. */
  34916. updateBefore( renderObject ) {
  34917. const nodeBuilder = renderObject.getNodeBuilderState();
  34918. for ( const node of nodeBuilder.updateBeforeNodes ) {
  34919. // update frame state for each node
  34920. this.getNodeFrameForRender( renderObject ).updateBeforeNode( node );
  34921. }
  34922. }
  34923. /**
  34924. * Triggers the call of `updateAfter()` methods
  34925. * for all nodes of the given render object.
  34926. *
  34927. * @param {RenderObject} renderObject - The render object.
  34928. */
  34929. updateAfter( renderObject ) {
  34930. const nodeBuilder = renderObject.getNodeBuilderState();
  34931. for ( const node of nodeBuilder.updateAfterNodes ) {
  34932. // update frame state for each node
  34933. this.getNodeFrameForRender( renderObject ).updateAfterNode( node );
  34934. }
  34935. }
  34936. /**
  34937. * Triggers the call of `update()` methods
  34938. * for all nodes of the given compute node.
  34939. *
  34940. * @param {Node} computeNode - The compute node.
  34941. */
  34942. updateForCompute( computeNode ) {
  34943. const nodeFrame = this.getNodeFrame();
  34944. const nodeBuilder = this.getForCompute( computeNode );
  34945. for ( const node of nodeBuilder.updateNodes ) {
  34946. nodeFrame.updateNode( node );
  34947. }
  34948. }
  34949. /**
  34950. * Triggers the call of `update()` methods
  34951. * for all nodes of the given compute node.
  34952. *
  34953. * @param {RenderObject} renderObject - The render object.
  34954. */
  34955. updateForRender( renderObject ) {
  34956. const nodeFrame = this.getNodeFrameForRender( renderObject );
  34957. const nodeBuilder = renderObject.getNodeBuilderState();
  34958. for ( const node of nodeBuilder.updateNodes ) {
  34959. nodeFrame.updateNode( node );
  34960. }
  34961. }
  34962. /**
  34963. * Returns `true` if the given render object requires a refresh.
  34964. *
  34965. * @param {RenderObject} renderObject - The render object.
  34966. * @return {boolean} Whether the given render object requires a refresh or not.
  34967. */
  34968. needsRefresh( renderObject ) {
  34969. const nodeFrame = this.getNodeFrameForRender( renderObject );
  34970. const monitor = renderObject.getMonitor();
  34971. return monitor.needsRefresh( renderObject, nodeFrame );
  34972. }
  34973. /**
  34974. * Frees the internal resources.
  34975. */
  34976. dispose() {
  34977. super.dispose();
  34978. this.nodeFrame = new NodeFrame();
  34979. this.nodeBuilderCache = new Map();
  34980. this.cacheLib = {};
  34981. }
  34982. }
  34983. const _plane = /*@__PURE__*/ new Plane();
  34984. /**
  34985. * Represents the state that is used to perform clipping via clipping planes.
  34986. * There is a default clipping context for each render context. When the
  34987. * scene holds instances of `ClippingGroup`, there will be a context for each
  34988. * group.
  34989. *
  34990. * @private
  34991. */
  34992. class ClippingContext {
  34993. /**
  34994. * Constructs a new clipping context.
  34995. *
  34996. * @param {?ClippingContext} [parentContext=null] - A reference to the parent clipping context.
  34997. */
  34998. constructor( parentContext = null ) {
  34999. /**
  35000. * The clipping context's version.
  35001. *
  35002. * @type {number}
  35003. * @readonly
  35004. */
  35005. this.version = 0;
  35006. /**
  35007. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  35008. *
  35009. * @type {?boolean}
  35010. * @default null
  35011. */
  35012. this.clipIntersection = null;
  35013. /**
  35014. * The clipping context's cache key.
  35015. *
  35016. * @type {string}
  35017. */
  35018. this.cacheKey = '';
  35019. /**
  35020. * Whether the shadow pass is active or not.
  35021. *
  35022. * @type {boolean}
  35023. * @default false
  35024. */
  35025. this.shadowPass = false;
  35026. /**
  35027. * The view normal matrix.
  35028. *
  35029. * @type {Matrix3}
  35030. */
  35031. this.viewNormalMatrix = new Matrix3();
  35032. /**
  35033. * Internal cache for maintaining clipping contexts.
  35034. *
  35035. * @type {WeakMap<ClippingGroup,ClippingContext>}
  35036. */
  35037. this.clippingGroupContexts = new WeakMap();
  35038. /**
  35039. * The intersection planes.
  35040. *
  35041. * @type {Array<Vector4>}
  35042. */
  35043. this.intersectionPlanes = [];
  35044. /**
  35045. * The intersection planes.
  35046. *
  35047. * @type {Array<Vector4>}
  35048. */
  35049. this.unionPlanes = [];
  35050. /**
  35051. * The version of the clipping context's parent context.
  35052. *
  35053. * @type {?number}
  35054. * @readonly
  35055. */
  35056. this.parentVersion = null;
  35057. if ( parentContext !== null ) {
  35058. this.viewNormalMatrix = parentContext.viewNormalMatrix;
  35059. this.clippingGroupContexts = parentContext.clippingGroupContexts;
  35060. this.shadowPass = parentContext.shadowPass;
  35061. this.viewMatrix = parentContext.viewMatrix;
  35062. }
  35063. }
  35064. /**
  35065. * Projects the given source clipping planes and writes the result into the
  35066. * destination array.
  35067. *
  35068. * @param {Array<Plane>} source - The source clipping planes.
  35069. * @param {Array<Vector4>} destination - The destination.
  35070. * @param {number} offset - The offset.
  35071. */
  35072. projectPlanes( source, destination, offset ) {
  35073. const l = source.length;
  35074. for ( let i = 0; i < l; i ++ ) {
  35075. _plane.copy( source[ i ] ).applyMatrix4( this.viewMatrix, this.viewNormalMatrix );
  35076. const v = destination[ offset + i ];
  35077. const normal = _plane.normal;
  35078. v.x = - normal.x;
  35079. v.y = - normal.y;
  35080. v.z = - normal.z;
  35081. v.w = _plane.constant;
  35082. }
  35083. }
  35084. /**
  35085. * Updates the root clipping context of a scene.
  35086. *
  35087. * @param {Scene} scene - The scene.
  35088. * @param {Camera} camera - The camera that is used to render the scene.
  35089. */
  35090. updateGlobal( scene, camera ) {
  35091. this.shadowPass = ( scene.overrideMaterial !== null && scene.overrideMaterial.isShadowPassMaterial );
  35092. this.viewMatrix = camera.matrixWorldInverse;
  35093. this.viewNormalMatrix.getNormalMatrix( this.viewMatrix );
  35094. }
  35095. /**
  35096. * Updates the clipping context.
  35097. *
  35098. * @param {ClippingContext} parentContext - The parent context.
  35099. * @param {ClippingGroup} clippingGroup - The clipping group this context belongs to.
  35100. */
  35101. update( parentContext, clippingGroup ) {
  35102. let update = false;
  35103. if ( parentContext.version !== this.parentVersion ) {
  35104. this.intersectionPlanes = Array.from( parentContext.intersectionPlanes );
  35105. this.unionPlanes = Array.from( parentContext.unionPlanes );
  35106. this.parentVersion = parentContext.version;
  35107. }
  35108. if ( this.clipIntersection !== clippingGroup.clipIntersection ) {
  35109. this.clipIntersection = clippingGroup.clipIntersection;
  35110. if ( this.clipIntersection ) {
  35111. this.unionPlanes.length = parentContext.unionPlanes.length;
  35112. } else {
  35113. this.intersectionPlanes.length = parentContext.intersectionPlanes.length;
  35114. }
  35115. }
  35116. const srcClippingPlanes = clippingGroup.clippingPlanes;
  35117. const l = srcClippingPlanes.length;
  35118. let dstClippingPlanes;
  35119. let offset;
  35120. if ( this.clipIntersection ) {
  35121. dstClippingPlanes = this.intersectionPlanes;
  35122. offset = parentContext.intersectionPlanes.length;
  35123. } else {
  35124. dstClippingPlanes = this.unionPlanes;
  35125. offset = parentContext.unionPlanes.length;
  35126. }
  35127. if ( dstClippingPlanes.length !== offset + l ) {
  35128. dstClippingPlanes.length = offset + l;
  35129. for ( let i = 0; i < l; i ++ ) {
  35130. dstClippingPlanes[ offset + i ] = new Vector4();
  35131. }
  35132. update = true;
  35133. }
  35134. this.projectPlanes( srcClippingPlanes, dstClippingPlanes, offset );
  35135. if ( update ) {
  35136. this.version ++;
  35137. this.cacheKey = `${ this.intersectionPlanes.length }:${ this.unionPlanes.length }`;
  35138. }
  35139. }
  35140. /**
  35141. * Returns a clipping context for the given clipping group.
  35142. *
  35143. * @param {ClippingGroup} clippingGroup - The clipping group.
  35144. * @return {ClippingContext} The clipping context.
  35145. */
  35146. getGroupContext( clippingGroup ) {
  35147. if ( this.shadowPass && ! clippingGroup.clipShadows ) return this;
  35148. let context = this.clippingGroupContexts.get( clippingGroup );
  35149. if ( context === undefined ) {
  35150. context = new ClippingContext( this );
  35151. this.clippingGroupContexts.set( clippingGroup, context );
  35152. }
  35153. context.update( this, clippingGroup );
  35154. return context;
  35155. }
  35156. /**
  35157. * The count of union clipping planes.
  35158. *
  35159. * @type {number}
  35160. * @readonly
  35161. */
  35162. get unionClippingCount() {
  35163. return this.unionPlanes.length;
  35164. }
  35165. }
  35166. /**
  35167. * This module is used to represent render bundles inside the renderer
  35168. * for further processing.
  35169. *
  35170. * @private
  35171. */
  35172. class RenderBundle {
  35173. /**
  35174. * Constructs a new bundle group.
  35175. *
  35176. * @param {BundleGroup} bundleGroup - The bundle group.
  35177. * @param {Camera} camera - The camera the bundle group is rendered with.
  35178. */
  35179. constructor( bundleGroup, camera ) {
  35180. this.bundleGroup = bundleGroup;
  35181. this.camera = camera;
  35182. }
  35183. }
  35184. const _chainKeys$1 = [];
  35185. /**
  35186. * This renderer module manages render bundles.
  35187. *
  35188. * @private
  35189. */
  35190. class RenderBundles {
  35191. /**
  35192. * Constructs a new render bundle management component.
  35193. */
  35194. constructor() {
  35195. /**
  35196. * A chain map for maintaining the render bundles.
  35197. *
  35198. * @type {ChainMap}
  35199. */
  35200. this.bundles = new ChainMap();
  35201. }
  35202. /**
  35203. * Returns a render bundle for the given bundle group and camera.
  35204. *
  35205. * @param {BundleGroup} bundleGroup - The bundle group.
  35206. * @param {Camera} camera - The camera the bundle group is rendered with.
  35207. * @return {RenderBundle} The render bundle.
  35208. */
  35209. get( bundleGroup, camera ) {
  35210. const bundles = this.bundles;
  35211. _chainKeys$1[ 0 ] = bundleGroup;
  35212. _chainKeys$1[ 1 ] = camera;
  35213. let bundle = bundles.get( _chainKeys$1 );
  35214. if ( bundle === undefined ) {
  35215. bundle = new RenderBundle( bundleGroup, camera );
  35216. bundles.set( _chainKeys$1, bundle );
  35217. }
  35218. _chainKeys$1.length = 0;
  35219. return bundle;
  35220. }
  35221. /**
  35222. * Frees all internal resources.
  35223. */
  35224. dispose() {
  35225. this.bundles = new ChainMap();
  35226. }
  35227. }
  35228. /**
  35229. * The purpose of a node library is to assign node implementations
  35230. * to existing library features. In `WebGPURenderer` lights, materials
  35231. * which are not based on `NodeMaterial` as well as tone mapping techniques
  35232. * are implemented with node-based modules.
  35233. *
  35234. * @private
  35235. */
  35236. class NodeLibrary {
  35237. /**
  35238. * Constructs a new node library.
  35239. */
  35240. constructor() {
  35241. /**
  35242. * A weak map that maps lights to light nodes.
  35243. *
  35244. * @type {WeakMap<Light.constructor,AnalyticLightNode.constructor>}
  35245. */
  35246. this.lightNodes = new WeakMap();
  35247. /**
  35248. * A map that maps materials to node materials.
  35249. *
  35250. * @type {Map<string,NodeMaterial.constructor>}
  35251. */
  35252. this.materialNodes = new Map();
  35253. /**
  35254. * A map that maps tone mapping techniques (constants)
  35255. * to tone mapping node functions.
  35256. *
  35257. * @type {Map<number,Function>}
  35258. */
  35259. this.toneMappingNodes = new Map();
  35260. }
  35261. /**
  35262. * Returns a matching node material instance for the given material object.
  35263. *
  35264. * This method also assigns/copies the properties of the given material object
  35265. * to the node material. This is done to make sure the current material
  35266. * configuration carries over to the node version.
  35267. *
  35268. * @param {Material} material - A material.
  35269. * @return {NodeMaterial} The corresponding node material.
  35270. */
  35271. fromMaterial( material ) {
  35272. if ( material.isNodeMaterial ) return material;
  35273. let nodeMaterial = null;
  35274. const nodeMaterialClass = this.getMaterialNodeClass( material.type );
  35275. if ( nodeMaterialClass !== null ) {
  35276. nodeMaterial = new nodeMaterialClass();
  35277. for ( const key in material ) {
  35278. nodeMaterial[ key ] = material[ key ];
  35279. }
  35280. }
  35281. return nodeMaterial;
  35282. }
  35283. /**
  35284. * Adds a tone mapping node function for a tone mapping technique (constant).
  35285. *
  35286. * @param {Function} toneMappingNode - The tone mapping node function.
  35287. * @param {number} toneMapping - The tone mapping.
  35288. */
  35289. addToneMapping( toneMappingNode, toneMapping ) {
  35290. this.addType( toneMappingNode, toneMapping, this.toneMappingNodes );
  35291. }
  35292. /**
  35293. * Returns a tone mapping node function for a tone mapping technique (constant).
  35294. *
  35295. * @param {number} toneMapping - The tone mapping.
  35296. * @return {?Function} The tone mapping node function. Returns `null` if no node function is found.
  35297. */
  35298. getToneMappingFunction( toneMapping ) {
  35299. return this.toneMappingNodes.get( toneMapping ) || null;
  35300. }
  35301. /**
  35302. * Returns a node material class definition for a material type.
  35303. *
  35304. * @param {string} materialType - The material type.
  35305. * @return {?NodeMaterial.constructor} The node material class definition. Returns `null` if no node material is found.
  35306. */
  35307. getMaterialNodeClass( materialType ) {
  35308. return this.materialNodes.get( materialType ) || null;
  35309. }
  35310. /**
  35311. * Adds a node material class definition for a given material type.
  35312. *
  35313. * @param {NodeMaterial.constructor} materialNodeClass - The node material class definition.
  35314. * @param {string} materialClassType - The material type.
  35315. */
  35316. addMaterial( materialNodeClass, materialClassType ) {
  35317. this.addType( materialNodeClass, materialClassType, this.materialNodes );
  35318. }
  35319. /**
  35320. * Returns a light node class definition for a light class definition.
  35321. *
  35322. * @param {Light.constructor} light - The light class definition.
  35323. * @return {?AnalyticLightNode.constructor} The light node class definition. Returns `null` if no light node is found.
  35324. */
  35325. getLightNodeClass( light ) {
  35326. return this.lightNodes.get( light ) || null;
  35327. }
  35328. /**
  35329. * Adds a light node class definition for a given light class definition.
  35330. *
  35331. * @param {AnalyticLightNode.constructor} lightNodeClass - The light node class definition.
  35332. * @param {Light.constructor} lightClass - The light class definition.
  35333. */
  35334. addLight( lightNodeClass, lightClass ) {
  35335. this.addClass( lightNodeClass, lightClass, this.lightNodes );
  35336. }
  35337. /**
  35338. * Adds a node class definition for the given type to the provided type library.
  35339. *
  35340. * @param {any} nodeClass - The node class definition.
  35341. * @param {number|string} type - The object type.
  35342. * @param {Map} library - The type library.
  35343. */
  35344. addType( nodeClass, type, library ) {
  35345. if ( library.has( type ) ) {
  35346. console.warn( `Redefinition of node ${ type }` );
  35347. return;
  35348. }
  35349. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  35350. if ( typeof type === 'function' || typeof type === 'object' ) throw new Error( `Base class ${ type } is not a class.` );
  35351. library.set( type, nodeClass );
  35352. }
  35353. /**
  35354. * Adds a node class definition for the given class definition to the provided type library.
  35355. *
  35356. * @param {any} nodeClass - The node class definition.
  35357. * @param {any} baseClass - The class definition.
  35358. * @param {WeakMap} library - The type library.
  35359. */
  35360. addClass( nodeClass, baseClass, library ) {
  35361. if ( library.has( baseClass ) ) {
  35362. console.warn( `Redefinition of node ${ baseClass.name }` );
  35363. return;
  35364. }
  35365. if ( typeof nodeClass !== 'function' ) throw new Error( `Node class ${ nodeClass.name } is not a class.` );
  35366. if ( typeof baseClass !== 'function' ) throw new Error( `Base class ${ baseClass.name } is not a class.` );
  35367. library.set( baseClass, nodeClass );
  35368. }
  35369. }
  35370. const _defaultLights = /*@__PURE__*/ new LightsNode();
  35371. const _chainKeys = [];
  35372. /**
  35373. * This renderer module manages the lights nodes which are unique
  35374. * per scene and camera combination.
  35375. *
  35376. * The lights node itself is later configured in the render list
  35377. * with the actual lights from the scene.
  35378. *
  35379. * @private
  35380. * @augments ChainMap
  35381. */
  35382. class Lighting extends ChainMap {
  35383. /**
  35384. * Constructs a lighting management component.
  35385. */
  35386. constructor() {
  35387. super();
  35388. }
  35389. /**
  35390. * Creates a new lights node for the given array of lights.
  35391. *
  35392. * @param {Array<Light>} lights - The render object.
  35393. * @return {LightsNode} The lights node.
  35394. */
  35395. createNode( lights = [] ) {
  35396. return new LightsNode().setLights( lights );
  35397. }
  35398. /**
  35399. * Returns a lights node for the given scene and camera.
  35400. *
  35401. * @param {Scene} scene - The scene.
  35402. * @param {Camera} camera - The camera.
  35403. * @return {LightsNode} The lights node.
  35404. */
  35405. getNode( scene, camera ) {
  35406. // ignore post-processing
  35407. if ( scene.isQuadMesh ) return _defaultLights;
  35408. _chainKeys[ 0 ] = scene;
  35409. _chainKeys[ 1 ] = camera;
  35410. let node = this.get( _chainKeys );
  35411. if ( node === undefined ) {
  35412. node = this.createNode();
  35413. this.set( _chainKeys, node );
  35414. }
  35415. _chainKeys.length = 0;
  35416. return node;
  35417. }
  35418. }
  35419. /**
  35420. * A special type of render target that is used when rendering
  35421. * with the WebXR Device API.
  35422. *
  35423. * @private
  35424. * @augments RenderTarget
  35425. */
  35426. class XRRenderTarget extends RenderTarget {
  35427. /**
  35428. * Constructs a new XR render target.
  35429. *
  35430. * @param {number} [width=1] - The width of the render target.
  35431. * @param {number} [height=1] - The height of the render target.
  35432. * @param {Object} [options={}] - The configuration options.
  35433. */
  35434. constructor( width = 1, height = 1, options = {} ) {
  35435. super( width, height, options );
  35436. /**
  35437. * This flag can be used for type testing.
  35438. *
  35439. * @type {boolean}
  35440. * @readonly
  35441. * @default true
  35442. */
  35443. this.isXRRenderTarget = true;
  35444. /**
  35445. * Whether the attachments of the render target
  35446. * are defined by external textures. This flag is
  35447. * set to `true` when using the WebXR Layers API.
  35448. *
  35449. * @private
  35450. * @type {boolean}
  35451. * @default false
  35452. */
  35453. this._hasExternalTextures = false;
  35454. /**
  35455. * Whether a depth buffer should automatically be allocated
  35456. * for this XR render target or not.
  35457. *
  35458. * Allocating a depth buffer is the default behavior of XR render
  35459. * targets. However, when using the WebXR Layers API, this flag
  35460. * must be set to `false` when the `ignoreDepthValues` property of
  35461. * the projection layers evaluates to `false`.
  35462. *
  35463. * Reference: {@link https://www.w3.org/TR/webxrlayers-1/#dom-xrprojectionlayer-ignoredepthvalues}.
  35464. *
  35465. * @private
  35466. * @type {boolean}
  35467. * @default true
  35468. */
  35469. this._autoAllocateDepthBuffer = true;
  35470. /**
  35471. * Whether this render target is associated with a XRWebGLLayer.
  35472. *
  35473. * A XRWebGLLayer points to an opaque framebuffer. Basically,
  35474. * this means that you don't have access to its bound color,
  35475. * stencil and depth buffers. We need to handle this framebuffer
  35476. * differently since its textures are always bound.
  35477. *
  35478. * @private
  35479. * @type {boolean}
  35480. * @default false
  35481. * */
  35482. this._isOpaqueFramebuffer = false;
  35483. }
  35484. copy( source ) {
  35485. super.copy( source );
  35486. this._hasExternalTextures = source._hasExternalTextures;
  35487. this._autoAllocateDepthBuffer = source._autoAllocateDepthBuffer;
  35488. this._isOpaqueFramebuffer = source._isOpaqueFramebuffer;
  35489. return this;
  35490. }
  35491. }
  35492. const _cameraLPos = /*@__PURE__*/ new Vector3();
  35493. const _cameraRPos = /*@__PURE__*/ new Vector3();
  35494. /**
  35495. * The XR manager is built on top of the WebXR Device API to
  35496. * manage XR sessions with `WebGPURenderer`.
  35497. *
  35498. * XR is currently only supported with a WebGL 2 backend.
  35499. *
  35500. * @augments EventDispatcher
  35501. */
  35502. class XRManager extends EventDispatcher {
  35503. /**
  35504. * Constructs a new XR manager.
  35505. *
  35506. * @param {Renderer} renderer - The renderer.
  35507. * @param {boolean} [multiview=false] - Enables multiview if the device supports it.
  35508. */
  35509. constructor( renderer, multiview = false ) {
  35510. super();
  35511. /**
  35512. * This flag globally enables XR rendering.
  35513. *
  35514. * @type {boolean}
  35515. * @default false
  35516. */
  35517. this.enabled = false;
  35518. /**
  35519. * Whether the XR device is currently presenting or not.
  35520. *
  35521. * @type {boolean}
  35522. * @default false
  35523. * @readonly
  35524. */
  35525. this.isPresenting = false;
  35526. /**
  35527. * Whether the XR camera should automatically be updated or not.
  35528. *
  35529. * @type {boolean}
  35530. * @default true
  35531. */
  35532. this.cameraAutoUpdate = true;
  35533. /**
  35534. * The renderer.
  35535. *
  35536. * @private
  35537. * @type {Renderer}
  35538. */
  35539. this._renderer = renderer;
  35540. // camera
  35541. /**
  35542. * Represents the camera for the left eye.
  35543. *
  35544. * @private
  35545. * @type {PerspectiveCamera}
  35546. */
  35547. this._cameraL = new PerspectiveCamera();
  35548. this._cameraL.viewport = new Vector4();
  35549. /**
  35550. * Represents the camera for the right eye.
  35551. *
  35552. * @private
  35553. * @type {PerspectiveCamera}
  35554. */
  35555. this._cameraR = new PerspectiveCamera();
  35556. this._cameraR.viewport = new Vector4();
  35557. /**
  35558. * A list of cameras used for rendering the XR views.
  35559. *
  35560. * @private
  35561. * @type {Array<Camera>}
  35562. */
  35563. this._cameras = [ this._cameraL, this._cameraR ];
  35564. /**
  35565. * The main XR camera.
  35566. *
  35567. * @private
  35568. * @type {ArrayCamera}
  35569. */
  35570. this._cameraXR = new ArrayCamera();
  35571. /**
  35572. * The current near value of the XR camera.
  35573. *
  35574. * @private
  35575. * @type {?number}
  35576. * @default null
  35577. */
  35578. this._currentDepthNear = null;
  35579. /**
  35580. * The current far value of the XR camera.
  35581. *
  35582. * @private
  35583. * @type {?number}
  35584. * @default null
  35585. */
  35586. this._currentDepthFar = null;
  35587. /**
  35588. * A list of WebXR controllers requested by the application.
  35589. *
  35590. * @private
  35591. * @type {Array<WebXRController>}
  35592. */
  35593. this._controllers = [];
  35594. /**
  35595. * A list of XR input source. Each input source belongs to
  35596. * an instance of WebXRController.
  35597. *
  35598. * @private
  35599. * @type {Array<XRInputSource?>}
  35600. */
  35601. this._controllerInputSources = [];
  35602. /**
  35603. * The XR render target that represents the rendering destination
  35604. * during an active XR session.
  35605. *
  35606. * @private
  35607. * @type {?RenderTarget}
  35608. * @default null
  35609. */
  35610. this._xrRenderTarget = null;
  35611. /**
  35612. * An array holding all the non-projection layers
  35613. *
  35614. * @private
  35615. * @type {Array<Object>}
  35616. * @default []
  35617. */
  35618. this._layers = [];
  35619. /**
  35620. * Whether the device has support for all layer types.
  35621. *
  35622. * @type {boolean}
  35623. * @default false
  35624. */
  35625. this._supportsLayers = false;
  35626. this._frameBufferTargets = null;
  35627. /**
  35628. * Helper function to create native WebXR Layer.
  35629. *
  35630. * @private
  35631. * @type {Function}
  35632. */
  35633. this._createXRLayer = createXRLayer.bind( this );
  35634. /**
  35635. * The current WebGL context.
  35636. *
  35637. * @private
  35638. * @type {?WebGL2RenderingContext}
  35639. * @default null
  35640. */
  35641. this._gl = null;
  35642. /**
  35643. * The current animation context.
  35644. *
  35645. * @private
  35646. * @type {?Window}
  35647. * @default null
  35648. */
  35649. this._currentAnimationContext = null;
  35650. /**
  35651. * The current animation loop.
  35652. *
  35653. * @private
  35654. * @type {?Function}
  35655. * @default null
  35656. */
  35657. this._currentAnimationLoop = null;
  35658. /**
  35659. * The current pixel ratio.
  35660. *
  35661. * @private
  35662. * @type {?number}
  35663. * @default null
  35664. */
  35665. this._currentPixelRatio = null;
  35666. /**
  35667. * The current size of the renderer's canvas
  35668. * in logical pixel unit.
  35669. *
  35670. * @private
  35671. * @type {Vector2}
  35672. */
  35673. this._currentSize = new Vector2();
  35674. /**
  35675. * The default event listener for handling events inside a XR session.
  35676. *
  35677. * @private
  35678. * @type {Function}
  35679. */
  35680. this._onSessionEvent = onSessionEvent.bind( this );
  35681. /**
  35682. * The event listener for handling the end of a XR session.
  35683. *
  35684. * @private
  35685. * @type {Function}
  35686. */
  35687. this._onSessionEnd = onSessionEnd.bind( this );
  35688. /**
  35689. * The event listener for handling the `inputsourceschange` event.
  35690. *
  35691. * @private
  35692. * @type {Function}
  35693. */
  35694. this._onInputSourcesChange = onInputSourcesChange.bind( this );
  35695. /**
  35696. * The animation loop which is used as a replacement for the default
  35697. * animation loop of the application. It is only used when a XR session
  35698. * is active.
  35699. *
  35700. * @private
  35701. * @type {Function}
  35702. */
  35703. this._onAnimationFrame = onAnimationFrame.bind( this );
  35704. /**
  35705. * The current XR reference space.
  35706. *
  35707. * @private
  35708. * @type {?XRReferenceSpace}
  35709. * @default null
  35710. */
  35711. this._referenceSpace = null;
  35712. /**
  35713. * The current XR reference space type.
  35714. *
  35715. * @private
  35716. * @type {XRReferenceSpaceType}
  35717. * @default 'local-floor'
  35718. */
  35719. this._referenceSpaceType = 'local-floor';
  35720. /**
  35721. * A custom reference space defined by the application.
  35722. *
  35723. * @private
  35724. * @type {?XRReferenceSpace}
  35725. * @default null
  35726. */
  35727. this._customReferenceSpace = null;
  35728. /**
  35729. * The framebuffer scale factor.
  35730. *
  35731. * @private
  35732. * @type {number}
  35733. * @default 1
  35734. */
  35735. this._framebufferScaleFactor = 1;
  35736. /**
  35737. * The foveation factor.
  35738. *
  35739. * @private
  35740. * @type {number}
  35741. * @default 1
  35742. */
  35743. this._foveation = 1.0;
  35744. /**
  35745. * A reference to the current XR session.
  35746. *
  35747. * @private
  35748. * @type {?XRSession}
  35749. * @default null
  35750. */
  35751. this._session = null;
  35752. /**
  35753. * A reference to the current XR base layer.
  35754. *
  35755. * @private
  35756. * @type {?XRWebGLLayer}
  35757. * @default null
  35758. */
  35759. this._glBaseLayer = null;
  35760. /**
  35761. * A reference to the current XR binding.
  35762. *
  35763. * @private
  35764. * @type {?XRWebGLBinding}
  35765. * @default null
  35766. */
  35767. this._glBinding = null;
  35768. /**
  35769. * A reference to the current XR projection layer.
  35770. *
  35771. * @private
  35772. * @type {?XRProjectionLayer}
  35773. * @default null
  35774. */
  35775. this._glProjLayer = null;
  35776. /**
  35777. * A reference to the current XR frame.
  35778. *
  35779. * @private
  35780. * @type {?XRFrame}
  35781. * @default null
  35782. */
  35783. this._xrFrame = null;
  35784. /**
  35785. * Whether to use the WebXR Layers API or not.
  35786. *
  35787. * @private
  35788. * @type {boolean}
  35789. * @readonly
  35790. */
  35791. this._useLayers = ( typeof XRWebGLBinding !== 'undefined' && 'createProjectionLayer' in XRWebGLBinding.prototype ); // eslint-disable-line compat/compat
  35792. /**
  35793. * Whether the usage of multiview has been requested by the application or not.
  35794. *
  35795. * @private
  35796. * @type {boolean}
  35797. * @default false
  35798. * @readonly
  35799. */
  35800. this._useMultiviewIfPossible = multiview;
  35801. /**
  35802. * Whether the usage of multiview is actually enabled. This flag only evaluates to `true`
  35803. * if multiview has been requested by the application and the `OVR_multiview2` is available.
  35804. *
  35805. * @private
  35806. * @type {boolean}
  35807. * @readonly
  35808. */
  35809. this._useMultiview = false;
  35810. }
  35811. /**
  35812. * Returns an instance of `THREE.Group` that represents the transformation
  35813. * of a XR controller in target ray space. The requested controller is defined
  35814. * by the given index.
  35815. *
  35816. * @param {number} index - The index of the XR controller.
  35817. * @return {Group} A group that represents the controller's transformation.
  35818. */
  35819. getController( index ) {
  35820. const controller = this._getController( index );
  35821. return controller.getTargetRaySpace();
  35822. }
  35823. /**
  35824. * Returns an instance of `THREE.Group` that represents the transformation
  35825. * of a XR controller in grip space. The requested controller is defined
  35826. * by the given index.
  35827. *
  35828. * @param {number} index - The index of the XR controller.
  35829. * @return {Group} A group that represents the controller's transformation.
  35830. */
  35831. getControllerGrip( index ) {
  35832. const controller = this._getController( index );
  35833. return controller.getGripSpace();
  35834. }
  35835. /**
  35836. * Returns an instance of `THREE.Group` that represents the transformation
  35837. * of a XR controller in hand space. The requested controller is defined
  35838. * by the given index.
  35839. *
  35840. * @param {number} index - The index of the XR controller.
  35841. * @return {Group} A group that represents the controller's transformation.
  35842. */
  35843. getHand( index ) {
  35844. const controller = this._getController( index );
  35845. return controller.getHandSpace();
  35846. }
  35847. /**
  35848. * Returns the foveation value.
  35849. *
  35850. * @return {number|undefined} The foveation value. Returns `undefined` if no base or projection layer is defined.
  35851. */
  35852. getFoveation() {
  35853. if ( this._glProjLayer === null && this._glBaseLayer === null ) {
  35854. return undefined;
  35855. }
  35856. return this._foveation;
  35857. }
  35858. /**
  35859. * Sets the foveation value.
  35860. *
  35861. * @param {number} foveation - A number in the range `[0,1]` where `0` means no foveation (full resolution)
  35862. * and `1` means maximum foveation (the edges render at lower resolution).
  35863. */
  35864. setFoveation( foveation ) {
  35865. this._foveation = foveation;
  35866. if ( this._glProjLayer !== null ) {
  35867. this._glProjLayer.fixedFoveation = foveation;
  35868. }
  35869. if ( this._glBaseLayer !== null && this._glBaseLayer.fixedFoveation !== undefined ) {
  35870. this._glBaseLayer.fixedFoveation = foveation;
  35871. }
  35872. }
  35873. /**
  35874. * Returns the framebuffer scale factor.
  35875. *
  35876. * @return {number} The framebuffer scale factor.
  35877. */
  35878. getFramebufferScaleFactor() {
  35879. return this._framebufferScaleFactor;
  35880. }
  35881. /**
  35882. * Sets the framebuffer scale factor.
  35883. *
  35884. * This method can not be used during a XR session.
  35885. *
  35886. * @param {number} factor - The framebuffer scale factor.
  35887. */
  35888. setFramebufferScaleFactor( factor ) {
  35889. this._framebufferScaleFactor = factor;
  35890. if ( this.isPresenting === true ) {
  35891. console.warn( 'THREE.XRManager: Cannot change framebuffer scale while presenting.' );
  35892. }
  35893. }
  35894. /**
  35895. * Returns the reference space type.
  35896. *
  35897. * @return {XRReferenceSpaceType} The reference space type.
  35898. */
  35899. getReferenceSpaceType() {
  35900. return this._referenceSpaceType;
  35901. }
  35902. /**
  35903. * Sets the reference space type.
  35904. *
  35905. * This method can not be used during a XR session.
  35906. *
  35907. * @param {XRReferenceSpaceType} type - The reference space type.
  35908. */
  35909. setReferenceSpaceType( type ) {
  35910. this._referenceSpaceType = type;
  35911. if ( this.isPresenting === true ) {
  35912. console.warn( 'THREE.XRManager: Cannot change reference space type while presenting.' );
  35913. }
  35914. }
  35915. /**
  35916. * Returns the XR reference space.
  35917. *
  35918. * @return {XRReferenceSpace} The XR reference space.
  35919. */
  35920. getReferenceSpace() {
  35921. return this._customReferenceSpace || this._referenceSpace;
  35922. }
  35923. /**
  35924. * Sets a custom XR reference space.
  35925. *
  35926. * @param {XRReferenceSpace} space - The XR reference space.
  35927. */
  35928. setReferenceSpace( space ) {
  35929. this._customReferenceSpace = space;
  35930. }
  35931. /**
  35932. * Returns the XR camera.
  35933. *
  35934. * @return {ArrayCamera} The XR camera.
  35935. */
  35936. getCamera() {
  35937. return this._cameraXR;
  35938. }
  35939. /**
  35940. * Returns the environment blend mode from the current XR session.
  35941. *
  35942. * @return {'opaque'|'additive'|'alpha-blend'|undefined} The environment blend mode. Returns `undefined` when used outside of a XR session.
  35943. */
  35944. getEnvironmentBlendMode() {
  35945. if ( this._session !== null ) {
  35946. return this._session.environmentBlendMode;
  35947. }
  35948. }
  35949. /**
  35950. * Returns the current XR frame.
  35951. *
  35952. * @return {?XRFrame} The XR frame. Returns `null` when used outside a XR session.
  35953. */
  35954. getFrame() {
  35955. return this._xrFrame;
  35956. }
  35957. /**
  35958. * Returns `true` if the engine renders to a multiview target.
  35959. *
  35960. * @return {boolean} Whether the engine renders to a multiview render target or not.
  35961. */
  35962. useMultiview() {
  35963. return this._useMultiview;
  35964. }
  35965. /**
  35966. * This method can be used in XR applications to create a quadratic layer that presents a separate
  35967. * rendered scene.
  35968. *
  35969. * @param {number} width - The width of the layer plane in world units.
  35970. * @param {number} height - The height of the layer plane in world units.
  35971. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  35972. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  35973. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  35974. * @param {number} pixelheight - The height of the layer's render target in pixels.
  35975. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  35976. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  35977. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  35978. * @return {Mesh} A mesh representing the quadratic XR layer. This mesh should be added to the XR scene.
  35979. */
  35980. createQuadLayer( width, height, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  35981. const geometry = new PlaneGeometry( width, height );
  35982. const renderTarget = new XRRenderTarget(
  35983. pixelwidth,
  35984. pixelheight,
  35985. {
  35986. format: RGBAFormat,
  35987. type: UnsignedByteType,
  35988. depthTexture: new DepthTexture(
  35989. pixelwidth,
  35990. pixelheight,
  35991. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  35992. undefined,
  35993. undefined,
  35994. undefined,
  35995. undefined,
  35996. undefined,
  35997. undefined,
  35998. attributes.stencil ? DepthStencilFormat : DepthFormat
  35999. ),
  36000. stencilBuffer: attributes.stencil,
  36001. resolveDepthBuffer: false,
  36002. resolveStencilBuffer: false
  36003. } );
  36004. renderTarget._autoAllocateDepthBuffer = true;
  36005. const material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  36006. material.map = renderTarget.texture;
  36007. material.map.offset.y = 1;
  36008. material.map.repeat.y = -1;
  36009. const plane = new Mesh( geometry, material );
  36010. plane.position.copy( translation );
  36011. plane.quaternion.copy( quaternion );
  36012. const layer = {
  36013. type: 'quad',
  36014. width: width,
  36015. height: height,
  36016. translation: translation,
  36017. quaternion: quaternion,
  36018. pixelwidth: pixelwidth,
  36019. pixelheight: pixelheight,
  36020. plane: plane,
  36021. material: material,
  36022. rendercall: rendercall,
  36023. renderTarget: renderTarget };
  36024. this._layers.push( layer );
  36025. if ( this._session !== null ) {
  36026. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: FrontSide } );
  36027. layer.plane.material.blending = CustomBlending;
  36028. layer.plane.material.blendEquation = AddEquation;
  36029. layer.plane.material.blendSrc = ZeroFactor;
  36030. layer.plane.material.blendDst = ZeroFactor;
  36031. layer.xrlayer = this._createXRLayer( layer );
  36032. const xrlayers = this._session.renderState.layers;
  36033. xrlayers.unshift( layer.xrlayer );
  36034. this._session.updateRenderState( { layers: xrlayers } );
  36035. } else {
  36036. renderTarget.isXRRenderTarget = false;
  36037. }
  36038. return plane;
  36039. }
  36040. /**
  36041. * This method can be used in XR applications to create a cylindrical layer that presents a separate
  36042. * rendered scene.
  36043. *
  36044. * @param {number} radius - The radius of the cylinder in world units.
  36045. * @param {number} centralAngle - The central angle of the cylinder in radians.
  36046. * @param {number} aspectratio - The aspect ratio.
  36047. * @param {Vector3} translation - The position/translation of the layer plane in world units.
  36048. * @param {Quaternion} quaternion - The orientation of the layer plane expressed as a quaternion.
  36049. * @param {number} pixelwidth - The width of the layer's render target in pixels.
  36050. * @param {number} pixelheight - The height of the layer's render target in pixels.
  36051. * @param {Function} rendercall - A callback function that renders the layer. Similar to code in
  36052. * the default animation loop, this method can be used to update/transform 3D object in the layer's scene.
  36053. * @param {Object} [attributes={}] - Allows to configure the layer's render target.
  36054. * @return {Mesh} A mesh representing the cylindrical XR layer. This mesh should be added to the XR scene.
  36055. */
  36056. createCylinderLayer( radius, centralAngle, aspectratio, translation, quaternion, pixelwidth, pixelheight, rendercall, attributes = {} ) {
  36057. const geometry = new CylinderGeometry( radius, radius, radius * centralAngle / aspectratio, 64, 64, true, Math.PI - centralAngle / 2, centralAngle );
  36058. const renderTarget = new XRRenderTarget(
  36059. pixelwidth,
  36060. pixelheight,
  36061. {
  36062. format: RGBAFormat,
  36063. type: UnsignedByteType,
  36064. depthTexture: new DepthTexture(
  36065. pixelwidth,
  36066. pixelheight,
  36067. attributes.stencil ? UnsignedInt248Type : UnsignedIntType,
  36068. undefined,
  36069. undefined,
  36070. undefined,
  36071. undefined,
  36072. undefined,
  36073. undefined,
  36074. attributes.stencil ? DepthStencilFormat : DepthFormat
  36075. ),
  36076. stencilBuffer: attributes.stencil,
  36077. resolveDepthBuffer: false,
  36078. resolveStencilBuffer: false
  36079. } );
  36080. renderTarget._autoAllocateDepthBuffer = true;
  36081. const material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  36082. material.map = renderTarget.texture;
  36083. material.map.offset.y = 1;
  36084. material.map.repeat.y = -1;
  36085. const plane = new Mesh( geometry, material );
  36086. plane.position.copy( translation );
  36087. plane.quaternion.copy( quaternion );
  36088. const layer = {
  36089. type: 'cylinder',
  36090. radius: radius,
  36091. centralAngle: centralAngle,
  36092. aspectratio: aspectratio,
  36093. translation: translation,
  36094. quaternion: quaternion,
  36095. pixelwidth: pixelwidth,
  36096. pixelheight: pixelheight,
  36097. plane: plane,
  36098. material: material,
  36099. rendercall: rendercall,
  36100. renderTarget: renderTarget };
  36101. this._layers.push( layer );
  36102. if ( this._session !== null ) {
  36103. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: BackSide } );
  36104. layer.plane.material.blending = CustomBlending;
  36105. layer.plane.material.blendEquation = AddEquation;
  36106. layer.plane.material.blendSrc = ZeroFactor;
  36107. layer.plane.material.blendDst = ZeroFactor;
  36108. layer.xrlayer = this._createXRLayer( layer );
  36109. const xrlayers = this._session.renderState.layers;
  36110. xrlayers.unshift( layer.xrlayer );
  36111. this._session.updateRenderState( { layers: xrlayers } );
  36112. } else {
  36113. renderTarget.isXRRenderTarget = false;
  36114. }
  36115. return plane;
  36116. }
  36117. /**
  36118. * Renders the XR layers that have been previously added to the scene.
  36119. *
  36120. * This method is usually called in your animation loop before rendering
  36121. * the actual scene via `renderer.render( scene, camera );`.
  36122. */
  36123. renderLayers( ) {
  36124. const translationObject = new Vector3();
  36125. const quaternionObject = new Quaternion();
  36126. const renderer = this._renderer;
  36127. const wasPresenting = this.isPresenting;
  36128. const rendererOutputTarget = renderer.getOutputRenderTarget();
  36129. const rendererFramebufferTarget = renderer._frameBufferTarget;
  36130. this.isPresenting = false;
  36131. const rendererSize = new Vector2();
  36132. renderer.getSize( rendererSize );
  36133. const rendererQuad = renderer._quad;
  36134. for ( const layer of this._layers ) {
  36135. layer.renderTarget.isXRRenderTarget = this._session !== null;
  36136. layer.renderTarget._hasExternalTextures = layer.renderTarget.isXRRenderTarget;
  36137. if ( layer.renderTarget.isXRRenderTarget && this._supportsLayers ) {
  36138. layer.xrlayer.transform = new XRRigidTransform( layer.plane.getWorldPosition( translationObject ), layer.plane.getWorldQuaternion( quaternionObject ) );
  36139. const glSubImage = this._glBinding.getSubImage( layer.xrlayer, this._xrFrame );
  36140. renderer.backend.setXRRenderTargetTextures(
  36141. layer.renderTarget,
  36142. glSubImage.colorTexture,
  36143. undefined );
  36144. renderer._setXRLayerSize( layer.renderTarget.width, layer.renderTarget.height );
  36145. renderer.setOutputRenderTarget( layer.renderTarget );
  36146. renderer.setRenderTarget( null );
  36147. renderer._frameBufferTarget = null;
  36148. this._frameBufferTargets || ( this._frameBufferTargets = new WeakMap() );
  36149. const { frameBufferTarget, quad } = this._frameBufferTargets.get( layer.renderTarget ) || { frameBufferTarget: null, quad: null };
  36150. if ( ! frameBufferTarget ) {
  36151. renderer._quad = new QuadMesh( new NodeMaterial() );
  36152. this._frameBufferTargets.set( layer.renderTarget, { frameBufferTarget: renderer._getFrameBufferTarget(), quad: renderer._quad } );
  36153. } else {
  36154. renderer._frameBufferTarget = frameBufferTarget;
  36155. renderer._quad = quad;
  36156. }
  36157. layer.rendercall();
  36158. renderer._frameBufferTarget = null;
  36159. } else {
  36160. renderer.setRenderTarget( layer.renderTarget );
  36161. layer.rendercall();
  36162. }
  36163. }
  36164. renderer.setRenderTarget( null );
  36165. renderer.setOutputRenderTarget( rendererOutputTarget );
  36166. renderer._frameBufferTarget = rendererFramebufferTarget;
  36167. renderer._setXRLayerSize( rendererSize.x, rendererSize.y );
  36168. renderer._quad = rendererQuad;
  36169. this.isPresenting = wasPresenting;
  36170. }
  36171. /**
  36172. * Returns the current XR session.
  36173. *
  36174. * @return {?XRSession} The XR session. Returns `null` when used outside a XR session.
  36175. */
  36176. getSession() {
  36177. return this._session;
  36178. }
  36179. /**
  36180. * After a XR session has been requested usually with one of the `*Button` modules, it
  36181. * is injected into the renderer with this method. This method triggers the start of
  36182. * the actual XR rendering.
  36183. *
  36184. * @async
  36185. * @param {XRSession} session - The XR session to set.
  36186. * @return {Promise} A Promise that resolves when the session has been set.
  36187. */
  36188. async setSession( session ) {
  36189. const renderer = this._renderer;
  36190. const backend = renderer.backend;
  36191. this._gl = renderer.getContext();
  36192. const gl = this._gl;
  36193. const attributes = gl.getContextAttributes();
  36194. this._session = session;
  36195. if ( session !== null ) {
  36196. 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.' );
  36197. session.addEventListener( 'select', this._onSessionEvent );
  36198. session.addEventListener( 'selectstart', this._onSessionEvent );
  36199. session.addEventListener( 'selectend', this._onSessionEvent );
  36200. session.addEventListener( 'squeeze', this._onSessionEvent );
  36201. session.addEventListener( 'squeezestart', this._onSessionEvent );
  36202. session.addEventListener( 'squeezeend', this._onSessionEvent );
  36203. session.addEventListener( 'end', this._onSessionEnd );
  36204. session.addEventListener( 'inputsourceschange', this._onInputSourcesChange );
  36205. await backend.makeXRCompatible();
  36206. this._currentPixelRatio = renderer.getPixelRatio();
  36207. renderer.getSize( this._currentSize );
  36208. this._currentAnimationContext = renderer._animation.getContext();
  36209. this._currentAnimationLoop = renderer._animation.getAnimationLoop();
  36210. renderer._animation.stop();
  36211. //
  36212. if ( this._useLayers === true ) {
  36213. // default path using XRWebGLBinding/XRProjectionLayer
  36214. let depthFormat = null;
  36215. let depthType = null;
  36216. let glDepthFormat = null;
  36217. if ( renderer.depth ) {
  36218. glDepthFormat = renderer.stencil ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  36219. depthFormat = renderer.stencil ? DepthStencilFormat : DepthFormat;
  36220. depthType = renderer.stencil ? UnsignedInt248Type : UnsignedIntType;
  36221. }
  36222. const projectionlayerInit = {
  36223. colorFormat: gl.RGBA8,
  36224. depthFormat: glDepthFormat,
  36225. scaleFactor: this._framebufferScaleFactor,
  36226. clearOnAccess: false
  36227. };
  36228. if ( this._useMultiviewIfPossible && renderer.hasFeature( 'OVR_multiview2' ) ) {
  36229. projectionlayerInit.textureType = 'texture-array';
  36230. this._useMultiview = true;
  36231. }
  36232. const glBinding = new XRWebGLBinding( session, gl );
  36233. const glProjLayer = glBinding.createProjectionLayer( projectionlayerInit );
  36234. const layersArray = [ glProjLayer ];
  36235. this._glBinding = glBinding;
  36236. this._glProjLayer = glProjLayer;
  36237. renderer.setPixelRatio( 1 );
  36238. renderer._setXRLayerSize( glProjLayer.textureWidth, glProjLayer.textureHeight );
  36239. const depth = this._useMultiview ? 2 : 1;
  36240. const depthTexture = new DepthTexture( glProjLayer.textureWidth, glProjLayer.textureHeight, depthType, undefined, undefined, undefined, undefined, undefined, undefined, depthFormat, depth );
  36241. this._xrRenderTarget = new XRRenderTarget(
  36242. glProjLayer.textureWidth,
  36243. glProjLayer.textureHeight,
  36244. {
  36245. format: RGBAFormat,
  36246. type: UnsignedByteType,
  36247. colorSpace: renderer.outputColorSpace,
  36248. depthTexture: depthTexture,
  36249. stencilBuffer: renderer.stencil,
  36250. samples: attributes.antialias ? 4 : 0,
  36251. resolveDepthBuffer: ( glProjLayer.ignoreDepthValues === false ),
  36252. resolveStencilBuffer: ( glProjLayer.ignoreDepthValues === false ),
  36253. depth: this._useMultiview ? 2 : 1,
  36254. multiview: this._useMultiview
  36255. } );
  36256. this._xrRenderTarget._hasExternalTextures = true;
  36257. this._xrRenderTarget.depth = this._useMultiview ? 2 : 1;
  36258. this._supportsLayers = session.enabledFeatures.includes( 'layers' );
  36259. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  36260. if ( this._supportsLayers ) {
  36261. // switch layers to native
  36262. for ( const layer of this._layers ) {
  36263. // change material so it "punches" out a hole to show the XR Layer.
  36264. layer.plane.material = new MeshBasicMaterial( { color: 0xffffff, side: layer.type === 'cylinder' ? BackSide : FrontSide } );
  36265. layer.plane.material.blending = CustomBlending;
  36266. layer.plane.material.blendEquation = AddEquation;
  36267. layer.plane.material.blendSrc = ZeroFactor;
  36268. layer.plane.material.blendDst = ZeroFactor;
  36269. layer.xrlayer = this._createXRLayer( layer );
  36270. layersArray.unshift( layer.xrlayer );
  36271. }
  36272. }
  36273. session.updateRenderState( { layers: layersArray } );
  36274. } else {
  36275. // fallback to XRWebGLLayer
  36276. const layerInit = {
  36277. antialias: renderer.samples > 0,
  36278. alpha: true,
  36279. depth: renderer.depth,
  36280. stencil: renderer.stencil,
  36281. framebufferScaleFactor: this.getFramebufferScaleFactor()
  36282. };
  36283. const glBaseLayer = new XRWebGLLayer( session, gl, layerInit );
  36284. this._glBaseLayer = glBaseLayer;
  36285. session.updateRenderState( { baseLayer: glBaseLayer } );
  36286. renderer.setPixelRatio( 1 );
  36287. renderer._setXRLayerSize( glBaseLayer.framebufferWidth, glBaseLayer.framebufferHeight );
  36288. this._xrRenderTarget = new XRRenderTarget(
  36289. glBaseLayer.framebufferWidth,
  36290. glBaseLayer.framebufferHeight,
  36291. {
  36292. format: RGBAFormat,
  36293. type: UnsignedByteType,
  36294. colorSpace: renderer.outputColorSpace,
  36295. stencilBuffer: renderer.stencil,
  36296. resolveDepthBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  36297. resolveStencilBuffer: ( glBaseLayer.ignoreDepthValues === false ),
  36298. }
  36299. );
  36300. this._xrRenderTarget._isOpaqueFramebuffer = true;
  36301. this._referenceSpace = await session.requestReferenceSpace( this.getReferenceSpaceType() );
  36302. }
  36303. //
  36304. this.setFoveation( this.getFoveation() );
  36305. renderer._animation.setAnimationLoop( this._onAnimationFrame );
  36306. renderer._animation.setContext( session );
  36307. renderer._animation.start();
  36308. this.isPresenting = true;
  36309. this.dispatchEvent( { type: 'sessionstart' } );
  36310. }
  36311. }
  36312. /**
  36313. * This method is called by the renderer per frame and updates the XR camera
  36314. * and it sub cameras based on the given camera. The given camera is the "user"
  36315. * camera created on application level and used for non-XR rendering.
  36316. *
  36317. * @param {PerspectiveCamera} camera - The camera.
  36318. */
  36319. updateCamera( camera ) {
  36320. const session = this._session;
  36321. if ( session === null ) return;
  36322. const depthNear = camera.near;
  36323. const depthFar = camera.far;
  36324. const cameraXR = this._cameraXR;
  36325. const cameraL = this._cameraL;
  36326. const cameraR = this._cameraR;
  36327. cameraXR.near = cameraR.near = cameraL.near = depthNear;
  36328. cameraXR.far = cameraR.far = cameraL.far = depthFar;
  36329. cameraXR.isMultiViewCamera = this._useMultiview;
  36330. if ( this._currentDepthNear !== cameraXR.near || this._currentDepthFar !== cameraXR.far ) {
  36331. // Note that the new renderState won't apply until the next frame. See #18320
  36332. session.updateRenderState( {
  36333. depthNear: cameraXR.near,
  36334. depthFar: cameraXR.far
  36335. } );
  36336. this._currentDepthNear = cameraXR.near;
  36337. this._currentDepthFar = cameraXR.far;
  36338. }
  36339. cameraL.layers.mask = camera.layers.mask | 0b010;
  36340. cameraR.layers.mask = camera.layers.mask | 0b100;
  36341. cameraXR.layers.mask = cameraL.layers.mask | cameraR.layers.mask;
  36342. const parent = camera.parent;
  36343. const cameras = cameraXR.cameras;
  36344. updateCamera( cameraXR, parent );
  36345. for ( let i = 0; i < cameras.length; i ++ ) {
  36346. updateCamera( cameras[ i ], parent );
  36347. }
  36348. // update projection matrix for proper view frustum culling
  36349. if ( cameras.length === 2 ) {
  36350. setProjectionFromUnion( cameraXR, cameraL, cameraR );
  36351. } else {
  36352. // assume single camera setup (AR)
  36353. cameraXR.projectionMatrix.copy( cameraL.projectionMatrix );
  36354. }
  36355. // update user camera and its children
  36356. updateUserCamera( camera, cameraXR, parent );
  36357. }
  36358. /**
  36359. * Returns a WebXR controller for the given controller index.
  36360. *
  36361. * @private
  36362. * @param {number} index - The controller index.
  36363. * @return {WebXRController} The XR controller.
  36364. */
  36365. _getController( index ) {
  36366. let controller = this._controllers[ index ];
  36367. if ( controller === undefined ) {
  36368. controller = new WebXRController();
  36369. this._controllers[ index ] = controller;
  36370. }
  36371. return controller;
  36372. }
  36373. }
  36374. /**
  36375. * Assumes 2 cameras that are parallel and share an X-axis, and that
  36376. * the cameras' projection and world matrices have already been set.
  36377. * And that near and far planes are identical for both cameras.
  36378. * Visualization of this technique: https://computergraphics.stackexchange.com/a/4765
  36379. *
  36380. * @param {ArrayCamera} camera - The camera to update.
  36381. * @param {PerspectiveCamera} cameraL - The left camera.
  36382. * @param {PerspectiveCamera} cameraR - The right camera.
  36383. */
  36384. function setProjectionFromUnion( camera, cameraL, cameraR ) {
  36385. _cameraLPos.setFromMatrixPosition( cameraL.matrixWorld );
  36386. _cameraRPos.setFromMatrixPosition( cameraR.matrixWorld );
  36387. const ipd = _cameraLPos.distanceTo( _cameraRPos );
  36388. const projL = cameraL.projectionMatrix.elements;
  36389. const projR = cameraR.projectionMatrix.elements;
  36390. // VR systems will have identical far and near planes, and
  36391. // most likely identical top and bottom frustum extents.
  36392. // Use the left camera for these values.
  36393. const near = projL[ 14 ] / ( projL[ 10 ] - 1 );
  36394. const far = projL[ 14 ] / ( projL[ 10 ] + 1 );
  36395. const topFov = ( projL[ 9 ] + 1 ) / projL[ 5 ];
  36396. const bottomFov = ( projL[ 9 ] - 1 ) / projL[ 5 ];
  36397. const leftFov = ( projL[ 8 ] - 1 ) / projL[ 0 ];
  36398. const rightFov = ( projR[ 8 ] + 1 ) / projR[ 0 ];
  36399. const left = near * leftFov;
  36400. const right = near * rightFov;
  36401. // Calculate the new camera's position offset from the
  36402. // left camera. xOffset should be roughly half `ipd`.
  36403. const zOffset = ipd / ( - leftFov + rightFov );
  36404. const xOffset = zOffset * - leftFov;
  36405. // TODO: Better way to apply this offset?
  36406. cameraL.matrixWorld.decompose( camera.position, camera.quaternion, camera.scale );
  36407. camera.translateX( xOffset );
  36408. camera.translateZ( zOffset );
  36409. camera.matrixWorld.compose( camera.position, camera.quaternion, camera.scale );
  36410. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  36411. // Check if the projection uses an infinite far plane.
  36412. if ( projL[ 10 ] === -1 ) {
  36413. // Use the projection matrix from the left eye.
  36414. // The camera offset is sufficient to include the view volumes
  36415. // of both eyes (assuming symmetric projections).
  36416. camera.projectionMatrix.copy( cameraL.projectionMatrix );
  36417. camera.projectionMatrixInverse.copy( cameraL.projectionMatrixInverse );
  36418. } else {
  36419. // Find the union of the frustum values of the cameras and scale
  36420. // the values so that the near plane's position does not change in world space,
  36421. // although must now be relative to the new union camera.
  36422. const near2 = near + zOffset;
  36423. const far2 = far + zOffset;
  36424. const left2 = left - xOffset;
  36425. const right2 = right + ( ipd - xOffset );
  36426. const top2 = topFov * far / far2 * near2;
  36427. const bottom2 = bottomFov * far / far2 * near2;
  36428. camera.projectionMatrix.makePerspective( left2, right2, top2, bottom2, near2, far2 );
  36429. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  36430. }
  36431. }
  36432. /**
  36433. * Updates the world matrices for the given camera based on the parent 3D object.
  36434. *
  36435. * @inner
  36436. * @param {Camera} camera - The camera to update.
  36437. * @param {Object3D} parent - The parent 3D object.
  36438. */
  36439. function updateCamera( camera, parent ) {
  36440. if ( parent === null ) {
  36441. camera.matrixWorld.copy( camera.matrix );
  36442. } else {
  36443. camera.matrixWorld.multiplyMatrices( parent.matrixWorld, camera.matrix );
  36444. }
  36445. camera.matrixWorldInverse.copy( camera.matrixWorld ).invert();
  36446. }
  36447. /**
  36448. * Updates the given camera with the transformation of the XR camera and parent object.
  36449. *
  36450. * @inner
  36451. * @param {Camera} camera - The camera to update.
  36452. * @param {ArrayCamera} cameraXR - The XR camera.
  36453. * @param {Object3D} parent - The parent 3D object.
  36454. */
  36455. function updateUserCamera( camera, cameraXR, parent ) {
  36456. if ( parent === null ) {
  36457. camera.matrix.copy( cameraXR.matrixWorld );
  36458. } else {
  36459. camera.matrix.copy( parent.matrixWorld );
  36460. camera.matrix.invert();
  36461. camera.matrix.multiply( cameraXR.matrixWorld );
  36462. }
  36463. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  36464. camera.updateMatrixWorld( true );
  36465. camera.projectionMatrix.copy( cameraXR.projectionMatrix );
  36466. camera.projectionMatrixInverse.copy( cameraXR.projectionMatrixInverse );
  36467. if ( camera.isPerspectiveCamera ) {
  36468. camera.fov = RAD2DEG * 2 * Math.atan( 1 / camera.projectionMatrix.elements[ 5 ] );
  36469. camera.zoom = 1;
  36470. }
  36471. }
  36472. function onSessionEvent( event ) {
  36473. const controllerIndex = this._controllerInputSources.indexOf( event.inputSource );
  36474. if ( controllerIndex === -1 ) {
  36475. return;
  36476. }
  36477. const controller = this._controllers[ controllerIndex ];
  36478. if ( controller !== undefined ) {
  36479. const referenceSpace = this.getReferenceSpace();
  36480. controller.update( event.inputSource, event.frame, referenceSpace );
  36481. controller.dispatchEvent( { type: event.type, data: event.inputSource } );
  36482. }
  36483. }
  36484. function onSessionEnd() {
  36485. const session = this._session;
  36486. const renderer = this._renderer;
  36487. session.removeEventListener( 'select', this._onSessionEvent );
  36488. session.removeEventListener( 'selectstart', this._onSessionEvent );
  36489. session.removeEventListener( 'selectend', this._onSessionEvent );
  36490. session.removeEventListener( 'squeeze', this._onSessionEvent );
  36491. session.removeEventListener( 'squeezestart', this._onSessionEvent );
  36492. session.removeEventListener( 'squeezeend', this._onSessionEvent );
  36493. session.removeEventListener( 'end', this._onSessionEnd );
  36494. session.removeEventListener( 'inputsourceschange', this._onInputSourcesChange );
  36495. for ( let i = 0; i < this._controllers.length; i ++ ) {
  36496. const inputSource = this._controllerInputSources[ i ];
  36497. if ( inputSource === null ) continue;
  36498. this._controllerInputSources[ i ] = null;
  36499. this._controllers[ i ].disconnect( inputSource );
  36500. }
  36501. this._currentDepthNear = null;
  36502. this._currentDepthFar = null;
  36503. // restore framebuffer/rendering state
  36504. renderer._resetXRState();
  36505. this._session = null;
  36506. this._xrRenderTarget = null;
  36507. // switch layers back to emulated
  36508. if ( this._supportsLayers === true ) {
  36509. for ( const layer of this._layers ) {
  36510. // Recreate layer render target to reset state
  36511. layer.renderTarget = new XRRenderTarget(
  36512. layer.pixelwidth,
  36513. layer.pixelheight,
  36514. {
  36515. format: RGBAFormat,
  36516. type: UnsignedByteType,
  36517. depthTexture: new DepthTexture(
  36518. layer.pixelwidth,
  36519. layer.pixelheight,
  36520. layer.stencilBuffer ? UnsignedInt248Type : UnsignedIntType,
  36521. undefined,
  36522. undefined,
  36523. undefined,
  36524. undefined,
  36525. undefined,
  36526. undefined,
  36527. layer.stencilBuffer ? DepthStencilFormat : DepthFormat
  36528. ),
  36529. stencilBuffer: layer.stencilBuffer,
  36530. resolveDepthBuffer: false,
  36531. resolveStencilBuffer: false
  36532. } );
  36533. layer.renderTarget.isXRRenderTarget = false;
  36534. layer.plane.material = layer.material;
  36535. layer.material.map = layer.renderTarget.texture;
  36536. layer.material.map.offset.y = 1;
  36537. layer.material.map.repeat.y = -1;
  36538. delete layer.xrlayer;
  36539. }
  36540. }
  36541. //
  36542. this.isPresenting = false;
  36543. this._useMultiview = false;
  36544. renderer._animation.stop();
  36545. renderer._animation.setAnimationLoop( this._currentAnimationLoop );
  36546. renderer._animation.setContext( this._currentAnimationContext );
  36547. renderer._animation.start();
  36548. renderer.setPixelRatio( this._currentPixelRatio );
  36549. renderer.setSize( this._currentSize.width, this._currentSize.height, false );
  36550. this.dispatchEvent( { type: 'sessionend' } );
  36551. }
  36552. function onInputSourcesChange( event ) {
  36553. const controllers = this._controllers;
  36554. const controllerInputSources = this._controllerInputSources;
  36555. // Notify disconnected
  36556. for ( let i = 0; i < event.removed.length; i ++ ) {
  36557. const inputSource = event.removed[ i ];
  36558. const index = controllerInputSources.indexOf( inputSource );
  36559. if ( index >= 0 ) {
  36560. controllerInputSources[ index ] = null;
  36561. controllers[ index ].disconnect( inputSource );
  36562. }
  36563. }
  36564. // Notify connected
  36565. for ( let i = 0; i < event.added.length; i ++ ) {
  36566. const inputSource = event.added[ i ];
  36567. let controllerIndex = controllerInputSources.indexOf( inputSource );
  36568. if ( controllerIndex === -1 ) {
  36569. // Assign input source a controller that currently has no input source
  36570. for ( let i = 0; i < controllers.length; i ++ ) {
  36571. if ( i >= controllerInputSources.length ) {
  36572. controllerInputSources.push( inputSource );
  36573. controllerIndex = i;
  36574. break;
  36575. } else if ( controllerInputSources[ i ] === null ) {
  36576. controllerInputSources[ i ] = inputSource;
  36577. controllerIndex = i;
  36578. break;
  36579. }
  36580. }
  36581. // If all controllers do currently receive input we ignore new ones
  36582. if ( controllerIndex === -1 ) break;
  36583. }
  36584. const controller = controllers[ controllerIndex ];
  36585. if ( controller ) {
  36586. controller.connect( inputSource );
  36587. }
  36588. }
  36589. }
  36590. // Creation method for native WebXR layers
  36591. function createXRLayer( layer ) {
  36592. if ( layer.type === 'quad' ) {
  36593. return this._glBinding.createQuadLayer( {
  36594. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  36595. width: layer.width / 2,
  36596. height: layer.height / 2,
  36597. space: this._referenceSpace,
  36598. viewPixelWidth: layer.pixelwidth,
  36599. viewPixelHeight: layer.pixelheight,
  36600. clearOnAccess: false
  36601. } );
  36602. } else {
  36603. return this._glBinding.createCylinderLayer( {
  36604. transform: new XRRigidTransform( layer.translation, layer.quaternion ),
  36605. radius: layer.radius,
  36606. centralAngle: layer.centralAngle,
  36607. aspectRatio: layer.aspectRatio,
  36608. space: this._referenceSpace,
  36609. viewPixelWidth: layer.pixelwidth,
  36610. viewPixelHeight: layer.pixelheight,
  36611. clearOnAccess: false
  36612. } );
  36613. }
  36614. }
  36615. // Animation Loop
  36616. function onAnimationFrame( time, frame ) {
  36617. if ( frame === undefined ) return;
  36618. const cameraXR = this._cameraXR;
  36619. const renderer = this._renderer;
  36620. const backend = renderer.backend;
  36621. const glBaseLayer = this._glBaseLayer;
  36622. const referenceSpace = this.getReferenceSpace();
  36623. const pose = frame.getViewerPose( referenceSpace );
  36624. this._xrFrame = frame;
  36625. if ( pose !== null ) {
  36626. const views = pose.views;
  36627. if ( this._glBaseLayer !== null ) {
  36628. backend.setXRTarget( glBaseLayer.framebuffer );
  36629. }
  36630. let cameraXRNeedsUpdate = false;
  36631. // check if it's necessary to rebuild cameraXR's camera list
  36632. if ( views.length !== cameraXR.cameras.length ) {
  36633. cameraXR.cameras.length = 0;
  36634. cameraXRNeedsUpdate = true;
  36635. }
  36636. for ( let i = 0; i < views.length; i ++ ) {
  36637. const view = views[ i ];
  36638. let viewport;
  36639. if ( this._useLayers === true ) {
  36640. const glSubImage = this._glBinding.getViewSubImage( this._glProjLayer, view );
  36641. viewport = glSubImage.viewport;
  36642. // For side-by-side projection, we only produce a single texture for both eyes.
  36643. if ( i === 0 ) {
  36644. backend.setXRRenderTargetTextures(
  36645. this._xrRenderTarget,
  36646. glSubImage.colorTexture,
  36647. ( this._glProjLayer.ignoreDepthValues && ! this._useMultiview ) ? undefined : glSubImage.depthStencilTexture
  36648. );
  36649. }
  36650. } else {
  36651. viewport = glBaseLayer.getViewport( view );
  36652. }
  36653. let camera = this._cameras[ i ];
  36654. if ( camera === undefined ) {
  36655. camera = new PerspectiveCamera();
  36656. camera.layers.enable( i );
  36657. camera.viewport = new Vector4();
  36658. this._cameras[ i ] = camera;
  36659. }
  36660. camera.matrix.fromArray( view.transform.matrix );
  36661. camera.matrix.decompose( camera.position, camera.quaternion, camera.scale );
  36662. camera.projectionMatrix.fromArray( view.projectionMatrix );
  36663. camera.projectionMatrixInverse.copy( camera.projectionMatrix ).invert();
  36664. camera.viewport.set( viewport.x, viewport.y, viewport.width, viewport.height );
  36665. if ( i === 0 ) {
  36666. cameraXR.matrix.copy( camera.matrix );
  36667. cameraXR.matrix.decompose( cameraXR.position, cameraXR.quaternion, cameraXR.scale );
  36668. }
  36669. if ( cameraXRNeedsUpdate === true ) {
  36670. cameraXR.cameras.push( camera );
  36671. }
  36672. }
  36673. renderer.setOutputRenderTarget( this._xrRenderTarget );
  36674. }
  36675. //
  36676. for ( let i = 0; i < this._controllers.length; i ++ ) {
  36677. const inputSource = this._controllerInputSources[ i ];
  36678. const controller = this._controllers[ i ];
  36679. if ( inputSource !== null && controller !== undefined ) {
  36680. controller.update( inputSource, frame, referenceSpace );
  36681. }
  36682. }
  36683. if ( this._currentAnimationLoop ) this._currentAnimationLoop( time, frame );
  36684. if ( frame.detectedPlanes ) {
  36685. this.dispatchEvent( { type: 'planesdetected', data: frame } );
  36686. }
  36687. this._xrFrame = null;
  36688. }
  36689. const _scene = /*@__PURE__*/ new Scene();
  36690. const _drawingBufferSize$1 = /*@__PURE__*/ new Vector2();
  36691. const _screen = /*@__PURE__*/ new Vector4();
  36692. const _frustum = /*@__PURE__*/ new Frustum();
  36693. const _frustumArray = /*@__PURE__*/ new FrustumArray();
  36694. const _projScreenMatrix = /*@__PURE__*/ new Matrix4();
  36695. const _vector4 = /*@__PURE__*/ new Vector4();
  36696. /**
  36697. * Base class for renderers.
  36698. */
  36699. class Renderer {
  36700. /**
  36701. * Renderer options.
  36702. *
  36703. * @typedef {Object} Renderer~Options
  36704. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  36705. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  36706. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  36707. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  36708. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  36709. * @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
  36710. * to overwrite the default.
  36711. * @property {?Function} [getFallback=null] - This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  36712. * @property {number} [colorBufferType=HalfFloatType] - Defines the type of color buffers. The default `HalfFloatType` is recommend for best
  36713. * quality. To save memory and bandwidth, `UnsignedByteType` might be used. This will reduce rendering quality though.
  36714. * @property {boolean} [multiview=false] - If set to `true`, the renderer will use multiview during WebXR rendering if supported.
  36715. */
  36716. /**
  36717. * Constructs a new renderer.
  36718. *
  36719. * @param {Backend} backend - The backend the renderer is targeting (e.g. WebGPU or WebGL 2).
  36720. * @param {Renderer~Options} [parameters] - The configuration parameter.
  36721. */
  36722. constructor( backend, parameters = {} ) {
  36723. /**
  36724. * This flag can be used for type testing.
  36725. *
  36726. * @type {boolean}
  36727. * @readonly
  36728. * @default true
  36729. */
  36730. this.isRenderer = true;
  36731. //
  36732. const {
  36733. logarithmicDepthBuffer = false,
  36734. alpha = true,
  36735. depth = true,
  36736. stencil = false,
  36737. antialias = false,
  36738. samples = 0,
  36739. getFallback = null,
  36740. colorBufferType = HalfFloatType,
  36741. multiview = false
  36742. } = parameters;
  36743. /**
  36744. * A reference to the canvas element the renderer is drawing to.
  36745. * This value of this property will automatically be created by
  36746. * the renderer.
  36747. *
  36748. * @type {HTMLCanvasElement|OffscreenCanvas}
  36749. */
  36750. this.domElement = backend.getDomElement();
  36751. /**
  36752. * A reference to the current backend.
  36753. *
  36754. * @type {Backend}
  36755. */
  36756. this.backend = backend;
  36757. /**
  36758. * The number of MSAA samples.
  36759. *
  36760. * @type {number}
  36761. * @default 0
  36762. */
  36763. this.samples = samples || ( antialias === true ) ? 4 : 0;
  36764. /**
  36765. * Whether the renderer should automatically clear the current rendering target
  36766. * before execute a `render()` call. The target can be the canvas (default framebuffer)
  36767. * or the current bound render target (custom framebuffer).
  36768. *
  36769. * @type {boolean}
  36770. * @default true
  36771. */
  36772. this.autoClear = true;
  36773. /**
  36774. * When `autoClear` is set to `true`, this property defines whether the renderer
  36775. * should clear the color buffer.
  36776. *
  36777. * @type {boolean}
  36778. * @default true
  36779. */
  36780. this.autoClearColor = true;
  36781. /**
  36782. * When `autoClear` is set to `true`, this property defines whether the renderer
  36783. * should clear the depth buffer.
  36784. *
  36785. * @type {boolean}
  36786. * @default true
  36787. */
  36788. this.autoClearDepth = true;
  36789. /**
  36790. * When `autoClear` is set to `true`, this property defines whether the renderer
  36791. * should clear the stencil buffer.
  36792. *
  36793. * @type {boolean}
  36794. * @default true
  36795. */
  36796. this.autoClearStencil = true;
  36797. /**
  36798. * Whether the default framebuffer should be transparent or opaque.
  36799. *
  36800. * @type {boolean}
  36801. * @default true
  36802. */
  36803. this.alpha = alpha;
  36804. /**
  36805. * Whether logarithmic depth buffer is enabled or not.
  36806. *
  36807. * @type {boolean}
  36808. * @default false
  36809. */
  36810. this.logarithmicDepthBuffer = logarithmicDepthBuffer;
  36811. /**
  36812. * Defines the output color space of the renderer.
  36813. *
  36814. * @type {string}
  36815. * @default SRGBColorSpace
  36816. */
  36817. this.outputColorSpace = SRGBColorSpace;
  36818. /**
  36819. * Defines the tone mapping of the renderer.
  36820. *
  36821. * @type {number}
  36822. * @default NoToneMapping
  36823. */
  36824. this.toneMapping = NoToneMapping;
  36825. /**
  36826. * Defines the tone mapping exposure.
  36827. *
  36828. * @type {number}
  36829. * @default 1
  36830. */
  36831. this.toneMappingExposure = 1.0;
  36832. /**
  36833. * Whether the renderer should sort its render lists or not.
  36834. *
  36835. * Note: Sorting is used to attempt to properly render objects that have some degree of transparency.
  36836. * By definition, sorting objects may not work in all cases. Depending on the needs of application,
  36837. * it may be necessary to turn off sorting and use other methods to deal with transparency rendering
  36838. * e.g. manually determining each object's rendering order.
  36839. *
  36840. * @type {boolean}
  36841. * @default true
  36842. */
  36843. this.sortObjects = true;
  36844. /**
  36845. * Whether the default framebuffer should have a depth buffer or not.
  36846. *
  36847. * @type {boolean}
  36848. * @default true
  36849. */
  36850. this.depth = depth;
  36851. /**
  36852. * Whether the default framebuffer should have a stencil buffer or not.
  36853. *
  36854. * @type {boolean}
  36855. * @default false
  36856. */
  36857. this.stencil = stencil;
  36858. /**
  36859. * Holds a series of statistical information about the GPU memory
  36860. * and the rendering process. Useful for debugging and monitoring.
  36861. *
  36862. * @type {Info}
  36863. */
  36864. this.info = new Info();
  36865. /**
  36866. * Stores override nodes for specific transformations or calculations.
  36867. * These nodes can be used to replace default behavior in the rendering pipeline.
  36868. *
  36869. * @type {Object}
  36870. * @property {?Node} modelViewMatrix - An override node for the model-view matrix.
  36871. * @property {?Node} modelNormalViewMatrix - An override node for the model normal view matrix.
  36872. */
  36873. this.overrideNodes = {
  36874. modelViewMatrix: null,
  36875. modelNormalViewMatrix: null
  36876. };
  36877. /**
  36878. * The node library defines how certain library objects like materials, lights
  36879. * or tone mapping functions are mapped to node types. This is required since
  36880. * although instances of classes like `MeshBasicMaterial` or `PointLight` can
  36881. * be part of the scene graph, they are internally represented as nodes for
  36882. * further processing.
  36883. *
  36884. * @type {NodeLibrary}
  36885. */
  36886. this.library = new NodeLibrary();
  36887. /**
  36888. * A map-like data structure for managing lights.
  36889. *
  36890. * @type {Lighting}
  36891. */
  36892. this.lighting = new Lighting();
  36893. // internals
  36894. /**
  36895. * This callback function can be used to provide a fallback backend, if the primary backend can't be targeted.
  36896. *
  36897. * @private
  36898. * @type {?Function}
  36899. */
  36900. this._getFallback = getFallback;
  36901. /**
  36902. * The renderer's pixel ratio.
  36903. *
  36904. * @private
  36905. * @type {number}
  36906. * @default 1
  36907. */
  36908. this._pixelRatio = 1;
  36909. /**
  36910. * The width of the renderer's default framebuffer in logical pixel unit.
  36911. *
  36912. * @private
  36913. * @type {number}
  36914. */
  36915. this._width = this.domElement.width;
  36916. /**
  36917. * The height of the renderer's default framebuffer in logical pixel unit.
  36918. *
  36919. * @private
  36920. * @type {number}
  36921. */
  36922. this._height = this.domElement.height;
  36923. /**
  36924. * The viewport of the renderer in logical pixel unit.
  36925. *
  36926. * @private
  36927. * @type {Vector4}
  36928. */
  36929. this._viewport = new Vector4( 0, 0, this._width, this._height );
  36930. /**
  36931. * The scissor rectangle of the renderer in logical pixel unit.
  36932. *
  36933. * @private
  36934. * @type {Vector4}
  36935. */
  36936. this._scissor = new Vector4( 0, 0, this._width, this._height );
  36937. /**
  36938. * Whether the scissor test should be enabled or not.
  36939. *
  36940. * @private
  36941. * @type {boolean}
  36942. */
  36943. this._scissorTest = false;
  36944. /**
  36945. * A reference to a renderer module for managing shader attributes.
  36946. *
  36947. * @private
  36948. * @type {?Attributes}
  36949. * @default null
  36950. */
  36951. this._attributes = null;
  36952. /**
  36953. * A reference to a renderer module for managing geometries.
  36954. *
  36955. * @private
  36956. * @type {?Geometries}
  36957. * @default null
  36958. */
  36959. this._geometries = null;
  36960. /**
  36961. * A reference to a renderer module for managing node related logic.
  36962. *
  36963. * @private
  36964. * @type {?Nodes}
  36965. * @default null
  36966. */
  36967. this._nodes = null;
  36968. /**
  36969. * A reference to a renderer module for managing the internal animation loop.
  36970. *
  36971. * @private
  36972. * @type {?Animation}
  36973. * @default null
  36974. */
  36975. this._animation = null;
  36976. /**
  36977. * A reference to a renderer module for managing shader program bindings.
  36978. *
  36979. * @private
  36980. * @type {?Bindings}
  36981. * @default null
  36982. */
  36983. this._bindings = null;
  36984. /**
  36985. * A reference to a renderer module for managing render objects.
  36986. *
  36987. * @private
  36988. * @type {?RenderObjects}
  36989. * @default null
  36990. */
  36991. this._objects = null;
  36992. /**
  36993. * A reference to a renderer module for managing render and compute pipelines.
  36994. *
  36995. * @private
  36996. * @type {?Pipelines}
  36997. * @default null
  36998. */
  36999. this._pipelines = null;
  37000. /**
  37001. * A reference to a renderer module for managing render bundles.
  37002. *
  37003. * @private
  37004. * @type {?RenderBundles}
  37005. * @default null
  37006. */
  37007. this._bundles = null;
  37008. /**
  37009. * A reference to a renderer module for managing render lists.
  37010. *
  37011. * @private
  37012. * @type {?RenderLists}
  37013. * @default null
  37014. */
  37015. this._renderLists = null;
  37016. /**
  37017. * A reference to a renderer module for managing render contexts.
  37018. *
  37019. * @private
  37020. * @type {?RenderContexts}
  37021. * @default null
  37022. */
  37023. this._renderContexts = null;
  37024. /**
  37025. * A reference to a renderer module for managing textures.
  37026. *
  37027. * @private
  37028. * @type {?Textures}
  37029. * @default null
  37030. */
  37031. this._textures = null;
  37032. /**
  37033. * A reference to a renderer module for backgrounds.
  37034. *
  37035. * @private
  37036. * @type {?Background}
  37037. * @default null
  37038. */
  37039. this._background = null;
  37040. /**
  37041. * This fullscreen quad is used for internal render passes
  37042. * like the tone mapping and color space output pass.
  37043. *
  37044. * @private
  37045. * @type {QuadMesh}
  37046. */
  37047. this._quad = new QuadMesh( new NodeMaterial() );
  37048. this._quad.material.name = 'Renderer_output';
  37049. /**
  37050. * A reference to the current render context.
  37051. *
  37052. * @private
  37053. * @type {?RenderContext}
  37054. * @default null
  37055. */
  37056. this._currentRenderContext = null;
  37057. /**
  37058. * A custom sort function for the opaque render list.
  37059. *
  37060. * @private
  37061. * @type {?Function}
  37062. * @default null
  37063. */
  37064. this._opaqueSort = null;
  37065. /**
  37066. * A custom sort function for the transparent render list.
  37067. *
  37068. * @private
  37069. * @type {?Function}
  37070. * @default null
  37071. */
  37072. this._transparentSort = null;
  37073. /**
  37074. * The framebuffer target.
  37075. *
  37076. * @private
  37077. * @type {?RenderTarget}
  37078. * @default null
  37079. */
  37080. this._frameBufferTarget = null;
  37081. const alphaClear = this.alpha === true ? 0 : 1;
  37082. /**
  37083. * The clear color value.
  37084. *
  37085. * @private
  37086. * @type {Color4}
  37087. */
  37088. this._clearColor = new Color4( 0, 0, 0, alphaClear );
  37089. /**
  37090. * The clear depth value.
  37091. *
  37092. * @private
  37093. * @type {number}
  37094. * @default 1
  37095. */
  37096. this._clearDepth = 1;
  37097. /**
  37098. * The clear stencil value.
  37099. *
  37100. * @private
  37101. * @type {number}
  37102. * @default 0
  37103. */
  37104. this._clearStencil = 0;
  37105. /**
  37106. * The current render target.
  37107. *
  37108. * @private
  37109. * @type {?RenderTarget}
  37110. * @default null
  37111. */
  37112. this._renderTarget = null;
  37113. /**
  37114. * The active cube face.
  37115. *
  37116. * @private
  37117. * @type {number}
  37118. * @default 0
  37119. */
  37120. this._activeCubeFace = 0;
  37121. /**
  37122. * The active mipmap level.
  37123. *
  37124. * @private
  37125. * @type {number}
  37126. * @default 0
  37127. */
  37128. this._activeMipmapLevel = 0;
  37129. /**
  37130. * The current output render target.
  37131. *
  37132. * @private
  37133. * @type {?RenderTarget}
  37134. * @default null
  37135. */
  37136. this._outputRenderTarget = null;
  37137. /**
  37138. * The MRT setting.
  37139. *
  37140. * @private
  37141. * @type {?MRTNode}
  37142. * @default null
  37143. */
  37144. this._mrt = null;
  37145. /**
  37146. * This function defines how a render object is going
  37147. * to be rendered.
  37148. *
  37149. * @private
  37150. * @type {?Function}
  37151. * @default null
  37152. */
  37153. this._renderObjectFunction = null;
  37154. /**
  37155. * Used to keep track of the current render object function.
  37156. *
  37157. * @private
  37158. * @type {?Function}
  37159. * @default null
  37160. */
  37161. this._currentRenderObjectFunction = null;
  37162. /**
  37163. * Used to keep track of the current render bundle.
  37164. *
  37165. * @private
  37166. * @type {?RenderBundle}
  37167. * @default null
  37168. */
  37169. this._currentRenderBundle = null;
  37170. /**
  37171. * Next to `_renderObjectFunction()`, this function provides another hook
  37172. * for influencing the render process of a render object. It is meant for internal
  37173. * use and only relevant for `compileAsync()` right now. Instead of using
  37174. * the default logic of `_renderObjectDirect()` which actually draws the render object,
  37175. * a different function might be used which performs no draw but just the node
  37176. * and pipeline updates.
  37177. *
  37178. * @private
  37179. * @type {?Function}
  37180. * @default null
  37181. */
  37182. this._handleObjectFunction = this._renderObjectDirect;
  37183. /**
  37184. * Indicates whether the device has been lost or not. In WebGL terms, the device
  37185. * lost is considered as a context lost. When this is set to `true`, rendering
  37186. * isn't possible anymore.
  37187. *
  37188. * @private
  37189. * @type {boolean}
  37190. * @default false
  37191. */
  37192. this._isDeviceLost = false;
  37193. /**
  37194. * A callback function that defines what should happen when a device/context lost occurs.
  37195. *
  37196. * @type {Function}
  37197. */
  37198. this.onDeviceLost = this._onDeviceLost;
  37199. /**
  37200. * Defines the type of color buffers. The default `HalfFloatType` is recommend for
  37201. * best quality. To save memory and bandwidth, `UnsignedByteType` might be used.
  37202. * This will reduce rendering quality though.
  37203. *
  37204. * @private
  37205. * @type {number}
  37206. * @default HalfFloatType
  37207. */
  37208. this._colorBufferType = colorBufferType;
  37209. /**
  37210. * Whether the renderer has been initialized or not.
  37211. *
  37212. * @private
  37213. * @type {boolean}
  37214. * @default false
  37215. */
  37216. this._initialized = false;
  37217. /**
  37218. * A reference to the promise which initializes the renderer.
  37219. *
  37220. * @private
  37221. * @type {?Promise<this>}
  37222. * @default null
  37223. */
  37224. this._initPromise = null;
  37225. /**
  37226. * An array of compilation promises which are used in `compileAsync()`.
  37227. *
  37228. * @private
  37229. * @type {?Array<Promise>}
  37230. * @default null
  37231. */
  37232. this._compilationPromises = null;
  37233. /**
  37234. * Whether the renderer should render transparent render objects or not.
  37235. *
  37236. * @type {boolean}
  37237. * @default true
  37238. */
  37239. this.transparent = true;
  37240. /**
  37241. * Whether the renderer should render opaque render objects or not.
  37242. *
  37243. * @type {boolean}
  37244. * @default true
  37245. */
  37246. this.opaque = true;
  37247. /**
  37248. * Shadow map configuration
  37249. * @typedef {Object} ShadowMapConfig
  37250. * @property {boolean} enabled - Whether to globally enable shadows or not.
  37251. * @property {number} type - The shadow map type.
  37252. */
  37253. /**
  37254. * The renderer's shadow configuration.
  37255. *
  37256. * @type {ShadowMapConfig}
  37257. */
  37258. this.shadowMap = {
  37259. enabled: false,
  37260. type: PCFShadowMap
  37261. };
  37262. /**
  37263. * XR configuration.
  37264. * @typedef {Object} XRConfig
  37265. * @property {boolean} enabled - Whether to globally enable XR or not.
  37266. */
  37267. /**
  37268. * The renderer's XR manager.
  37269. *
  37270. * @type {XRManager}
  37271. */
  37272. this.xr = new XRManager( this, multiview );
  37273. /**
  37274. * Debug configuration.
  37275. * @typedef {Object} DebugConfig
  37276. * @property {boolean} checkShaderErrors - Whether shader errors should be checked or not.
  37277. * @property {?Function} onShaderError - A callback function that is executed when a shader error happens. Only supported with WebGL 2 right now.
  37278. * @property {Function} getShaderAsync - Allows the get the raw shader code for the given scene, camera and 3D object.
  37279. */
  37280. /**
  37281. * The renderer's debug configuration.
  37282. *
  37283. * @type {DebugConfig}
  37284. */
  37285. this.debug = {
  37286. checkShaderErrors: true,
  37287. onShaderError: null,
  37288. getShaderAsync: async ( scene, camera, object ) => {
  37289. await this.compileAsync( scene, camera );
  37290. const renderList = this._renderLists.get( scene, camera );
  37291. const renderContext = this._renderContexts.get( scene, camera, this._renderTarget );
  37292. const material = scene.overrideMaterial || object.material;
  37293. const renderObject = this._objects.get( object, material, scene, camera, renderList.lightsNode, renderContext, renderContext.clippingContext );
  37294. const { fragmentShader, vertexShader } = renderObject.getNodeBuilderState();
  37295. return { fragmentShader, vertexShader };
  37296. }
  37297. };
  37298. }
  37299. /**
  37300. * Initializes the renderer so it is ready for usage.
  37301. *
  37302. * @async
  37303. * @return {Promise<this>} A Promise that resolves when the renderer has been initialized.
  37304. */
  37305. async init() {
  37306. if ( this._initialized ) {
  37307. throw new Error( 'Renderer: Backend has already been initialized.' );
  37308. }
  37309. if ( this._initPromise !== null ) {
  37310. return this._initPromise;
  37311. }
  37312. this._initPromise = new Promise( async ( resolve, reject ) => {
  37313. let backend = this.backend;
  37314. try {
  37315. await backend.init( this );
  37316. } catch ( error ) {
  37317. if ( this._getFallback !== null ) {
  37318. // try the fallback
  37319. try {
  37320. this.backend = backend = this._getFallback( error );
  37321. await backend.init( this );
  37322. } catch ( error ) {
  37323. reject( error );
  37324. return;
  37325. }
  37326. } else {
  37327. reject( error );
  37328. return;
  37329. }
  37330. }
  37331. this._nodes = new Nodes( this, backend );
  37332. this._animation = new Animation( this._nodes, this.info );
  37333. this._attributes = new Attributes( backend );
  37334. this._background = new Background( this, this._nodes );
  37335. this._geometries = new Geometries( this._attributes, this.info );
  37336. this._textures = new Textures( this, backend, this.info );
  37337. this._pipelines = new Pipelines( backend, this._nodes );
  37338. this._bindings = new Bindings( backend, this._nodes, this._textures, this._attributes, this._pipelines, this.info );
  37339. this._objects = new RenderObjects( this, this._nodes, this._geometries, this._pipelines, this._bindings, this.info );
  37340. this._renderLists = new RenderLists( this.lighting );
  37341. this._bundles = new RenderBundles();
  37342. this._renderContexts = new RenderContexts();
  37343. //
  37344. this._animation.start();
  37345. this._initialized = true;
  37346. resolve( this );
  37347. } );
  37348. return this._initPromise;
  37349. }
  37350. /**
  37351. * The coordinate system of the renderer. The value of this property
  37352. * depends on the selected backend. Either `THREE.WebGLCoordinateSystem` or
  37353. * `THREE.WebGPUCoordinateSystem`.
  37354. *
  37355. * @readonly
  37356. * @type {number}
  37357. */
  37358. get coordinateSystem() {
  37359. return this.backend.coordinateSystem;
  37360. }
  37361. /**
  37362. * Compiles all materials in the given scene. This can be useful to avoid a
  37363. * phenomenon which is called "shader compilation stutter", which occurs when
  37364. * rendering an object with a new shader for the first time.
  37365. *
  37366. * If you want to add a 3D object to an existing scene, use the third optional
  37367. * parameter for applying the target scene. Note that the (target) scene's lighting
  37368. * and environment must be configured before calling this method.
  37369. *
  37370. * @async
  37371. * @param {Object3D} scene - The scene or 3D object to precompile.
  37372. * @param {Camera} camera - The camera that is used to render the scene.
  37373. * @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.
  37374. * @return {Promise<Array|undefined>} A Promise that resolves when the compile has been finished.
  37375. */
  37376. async compileAsync( scene, camera, targetScene = null ) {
  37377. if ( this._isDeviceLost === true ) return;
  37378. if ( this._initialized === false ) await this.init();
  37379. // preserve render tree
  37380. const nodeFrame = this._nodes.nodeFrame;
  37381. const previousRenderId = nodeFrame.renderId;
  37382. const previousRenderContext = this._currentRenderContext;
  37383. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37384. const previousCompilationPromises = this._compilationPromises;
  37385. //
  37386. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37387. if ( targetScene === null ) targetScene = scene;
  37388. const renderTarget = this._renderTarget;
  37389. const renderContext = this._renderContexts.get( targetScene, camera, renderTarget );
  37390. const activeMipmapLevel = this._activeMipmapLevel;
  37391. const compilationPromises = [];
  37392. this._currentRenderContext = renderContext;
  37393. this._currentRenderObjectFunction = this.renderObject;
  37394. this._handleObjectFunction = this._createObjectPipeline;
  37395. this._compilationPromises = compilationPromises;
  37396. nodeFrame.renderId ++;
  37397. //
  37398. nodeFrame.update();
  37399. //
  37400. renderContext.depth = this.depth;
  37401. renderContext.stencil = this.stencil;
  37402. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37403. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  37404. //
  37405. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37406. //
  37407. const renderList = this._renderLists.get( scene, camera );
  37408. renderList.begin();
  37409. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  37410. // include lights from target scene
  37411. if ( targetScene !== scene ) {
  37412. targetScene.traverseVisible( function ( object ) {
  37413. if ( object.isLight && object.layers.test( camera.layers ) ) {
  37414. renderList.pushLight( object );
  37415. }
  37416. } );
  37417. }
  37418. renderList.finish();
  37419. //
  37420. if ( renderTarget !== null ) {
  37421. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37422. const renderTargetData = this._textures.get( renderTarget );
  37423. renderContext.textures = renderTargetData.textures;
  37424. renderContext.depthTexture = renderTargetData.depthTexture;
  37425. } else {
  37426. renderContext.textures = null;
  37427. renderContext.depthTexture = null;
  37428. }
  37429. //
  37430. this._background.update( sceneRef, renderList, renderContext );
  37431. // process render lists
  37432. const opaqueObjects = renderList.opaque;
  37433. const transparentObjects = renderList.transparent;
  37434. const transparentDoublePassObjects = renderList.transparentDoublePass;
  37435. const lightsNode = renderList.lightsNode;
  37436. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37437. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37438. // restore render tree
  37439. nodeFrame.renderId = previousRenderId;
  37440. this._currentRenderContext = previousRenderContext;
  37441. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37442. this._compilationPromises = previousCompilationPromises;
  37443. this._handleObjectFunction = this._renderObjectDirect;
  37444. // wait for all promises setup by backends awaiting compilation/linking/pipeline creation to complete
  37445. await Promise.all( compilationPromises );
  37446. }
  37447. /**
  37448. * Renders the scene in an async fashion.
  37449. *
  37450. * @async
  37451. * @param {Object3D} scene - The scene or 3D object to render.
  37452. * @param {Camera} camera - The camera.
  37453. * @return {Promise} A Promise that resolves when the render has been finished.
  37454. */
  37455. async renderAsync( scene, camera ) {
  37456. if ( this._initialized === false ) await this.init();
  37457. this._renderScene( scene, camera );
  37458. }
  37459. /**
  37460. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  37461. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  37462. *
  37463. * @async
  37464. * @return {Promise} A Promise that resolves when synchronization has been finished.
  37465. */
  37466. async waitForGPU() {
  37467. await this.backend.waitForGPU();
  37468. }
  37469. /**
  37470. * Enables or disables high precision for model-view and normal-view matrices.
  37471. * When enabled, will use CPU 64-bit precision for higher precision instead of GPU 32-bit for higher performance.
  37472. *
  37473. * NOTE: 64-bit precision is not compatible with `InstancedMesh` and `SkinnedMesh`.
  37474. *
  37475. * @param {boolean} value - Whether to enable or disable high precision.
  37476. * @type {boolean}
  37477. */
  37478. set highPrecision( value ) {
  37479. if ( value === true ) {
  37480. this.overrideNodes.modelViewMatrix = highpModelViewMatrix;
  37481. this.overrideNodes.modelNormalViewMatrix = highpModelNormalViewMatrix;
  37482. } else if ( this.highPrecision ) {
  37483. this.overrideNodes.modelViewMatrix = null;
  37484. this.overrideNodes.modelNormalViewMatrix = null;
  37485. }
  37486. }
  37487. /**
  37488. * Returns whether high precision is enabled or not.
  37489. *
  37490. * @return {boolean} Whether high precision is enabled or not.
  37491. * @type {boolean}
  37492. */
  37493. get highPrecision() {
  37494. return this.overrideNodes.modelViewMatrix === highpModelViewMatrix && this.overrideNodes.modelNormalViewMatrix === highpModelNormalViewMatrix;
  37495. }
  37496. /**
  37497. * Sets the given MRT configuration.
  37498. *
  37499. * @param {MRTNode} mrt - The MRT node to set.
  37500. * @return {Renderer} A reference to this renderer.
  37501. */
  37502. setMRT( mrt ) {
  37503. this._mrt = mrt;
  37504. return this;
  37505. }
  37506. /**
  37507. * Returns the MRT configuration.
  37508. *
  37509. * @return {MRTNode} The MRT configuration.
  37510. */
  37511. getMRT() {
  37512. return this._mrt;
  37513. }
  37514. /**
  37515. * Returns the color buffer type.
  37516. *
  37517. * @return {number} The color buffer type.
  37518. */
  37519. getColorBufferType() {
  37520. return this._colorBufferType;
  37521. }
  37522. /**
  37523. * Default implementation of the device lost callback.
  37524. *
  37525. * @private
  37526. * @param {Object} info - Information about the context lost.
  37527. */
  37528. _onDeviceLost( info ) {
  37529. let errorMessage = `THREE.WebGPURenderer: ${info.api} Device Lost:\n\nMessage: ${info.message}`;
  37530. if ( info.reason ) {
  37531. errorMessage += `\nReason: ${info.reason}`;
  37532. }
  37533. console.error( errorMessage );
  37534. this._isDeviceLost = true;
  37535. }
  37536. /**
  37537. * Renders the given render bundle.
  37538. *
  37539. * @private
  37540. * @param {Object} bundle - Render bundle data.
  37541. * @param {Scene} sceneRef - The scene the render bundle belongs to.
  37542. * @param {LightsNode} lightsNode - The lights node.
  37543. */
  37544. _renderBundle( bundle, sceneRef, lightsNode ) {
  37545. const { bundleGroup, camera, renderList } = bundle;
  37546. const renderContext = this._currentRenderContext;
  37547. //
  37548. const renderBundle = this._bundles.get( bundleGroup, camera );
  37549. const renderBundleData = this.backend.get( renderBundle );
  37550. if ( renderBundleData.renderContexts === undefined ) renderBundleData.renderContexts = new Set();
  37551. //
  37552. const needsUpdate = bundleGroup.version !== renderBundleData.version;
  37553. const renderBundleNeedsUpdate = renderBundleData.renderContexts.has( renderContext ) === false || needsUpdate;
  37554. renderBundleData.renderContexts.add( renderContext );
  37555. if ( renderBundleNeedsUpdate ) {
  37556. this.backend.beginBundle( renderContext );
  37557. if ( renderBundleData.renderObjects === undefined || needsUpdate ) {
  37558. renderBundleData.renderObjects = [];
  37559. }
  37560. this._currentRenderBundle = renderBundle;
  37561. const {
  37562. transparentDoublePass: transparentDoublePassObjects,
  37563. transparent: transparentObjects,
  37564. opaque: opaqueObjects
  37565. } = renderList;
  37566. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37567. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37568. this._currentRenderBundle = null;
  37569. //
  37570. this.backend.finishBundle( renderContext, renderBundle );
  37571. renderBundleData.version = bundleGroup.version;
  37572. } else {
  37573. const { renderObjects } = renderBundleData;
  37574. for ( let i = 0, l = renderObjects.length; i < l; i ++ ) {
  37575. const renderObject = renderObjects[ i ];
  37576. if ( this._nodes.needsRefresh( renderObject ) ) {
  37577. this._nodes.updateBefore( renderObject );
  37578. this._nodes.updateForRender( renderObject );
  37579. this._bindings.updateForRender( renderObject );
  37580. this._nodes.updateAfter( renderObject );
  37581. }
  37582. }
  37583. }
  37584. this.backend.addBundle( renderContext, renderBundle );
  37585. }
  37586. /**
  37587. * Renders the scene or 3D object with the given camera. This method can only be called
  37588. * if the renderer has been initialized.
  37589. *
  37590. * The target of the method is the default framebuffer (meaning the canvas)
  37591. * or alternatively a render target when specified via `setRenderTarget()`.
  37592. *
  37593. * @param {Object3D} scene - The scene or 3D object to render.
  37594. * @param {Camera} camera - The camera to render the scene with.
  37595. * @return {?Promise} A Promise that resolve when the scene has been rendered.
  37596. * Only returned when the renderer has not been initialized.
  37597. */
  37598. render( scene, camera ) {
  37599. if ( this._initialized === false ) {
  37600. console.warn( 'THREE.Renderer: .render() called before the backend is initialized. Try using .renderAsync() instead.' );
  37601. return this.renderAsync( scene, camera );
  37602. }
  37603. this._renderScene( scene, camera );
  37604. }
  37605. /**
  37606. * Returns an internal render target which is used when computing the output tone mapping
  37607. * and color space conversion. Unlike in `WebGLRenderer`, this is done in a separate render
  37608. * pass and not inline to achieve more correct results.
  37609. *
  37610. * @private
  37611. * @return {?RenderTarget} The render target. The method returns `null` if no output conversion should be applied.
  37612. */
  37613. _getFrameBufferTarget() {
  37614. const { currentToneMapping, currentColorSpace } = this;
  37615. const useToneMapping = currentToneMapping !== NoToneMapping;
  37616. const useColorSpace = currentColorSpace !== LinearSRGBColorSpace;
  37617. if ( useToneMapping === false && useColorSpace === false ) return null;
  37618. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize$1 );
  37619. const { depth, stencil } = this;
  37620. let frameBufferTarget = this._frameBufferTarget;
  37621. if ( frameBufferTarget === null ) {
  37622. frameBufferTarget = new RenderTarget( width, height, {
  37623. depthBuffer: depth,
  37624. stencilBuffer: stencil,
  37625. type: this._colorBufferType,
  37626. format: RGBAFormat,
  37627. colorSpace: LinearSRGBColorSpace,
  37628. generateMipmaps: false,
  37629. minFilter: LinearFilter,
  37630. magFilter: LinearFilter,
  37631. samples: this.samples
  37632. } );
  37633. frameBufferTarget.isPostProcessingRenderTarget = true;
  37634. this._frameBufferTarget = frameBufferTarget;
  37635. }
  37636. const outputRenderTarget = this.getOutputRenderTarget();
  37637. frameBufferTarget.depthBuffer = depth;
  37638. frameBufferTarget.stencilBuffer = stencil;
  37639. if ( outputRenderTarget !== null ) {
  37640. frameBufferTarget.setSize( outputRenderTarget.width, outputRenderTarget.height, outputRenderTarget.depth );
  37641. } else {
  37642. frameBufferTarget.setSize( width, height, 1 );
  37643. }
  37644. frameBufferTarget.viewport.copy( this._viewport );
  37645. frameBufferTarget.scissor.copy( this._scissor );
  37646. frameBufferTarget.viewport.multiplyScalar( this._pixelRatio );
  37647. frameBufferTarget.scissor.multiplyScalar( this._pixelRatio );
  37648. frameBufferTarget.scissorTest = this._scissorTest;
  37649. frameBufferTarget.multiview = outputRenderTarget !== null ? outputRenderTarget.multiview : false;
  37650. frameBufferTarget.resolveDepthBuffer = outputRenderTarget !== null ? outputRenderTarget.resolveDepthBuffer : true;
  37651. frameBufferTarget._autoAllocateDepthBuffer = outputRenderTarget !== null ? outputRenderTarget._autoAllocateDepthBuffer : false;
  37652. return frameBufferTarget;
  37653. }
  37654. /**
  37655. * Renders the scene or 3D object with the given camera.
  37656. *
  37657. * @private
  37658. * @param {Object3D} scene - The scene or 3D object to render.
  37659. * @param {Camera} camera - The camera to render the scene with.
  37660. * @param {boolean} [useFrameBufferTarget=true] - Whether to use a framebuffer target or not.
  37661. * @return {RenderContext} The current render context.
  37662. */
  37663. _renderScene( scene, camera, useFrameBufferTarget = true ) {
  37664. if ( this._isDeviceLost === true ) return;
  37665. const frameBufferTarget = useFrameBufferTarget ? this._getFrameBufferTarget() : null;
  37666. // preserve render tree
  37667. const nodeFrame = this._nodes.nodeFrame;
  37668. const previousRenderId = nodeFrame.renderId;
  37669. const previousRenderContext = this._currentRenderContext;
  37670. const previousRenderObjectFunction = this._currentRenderObjectFunction;
  37671. //
  37672. const sceneRef = ( scene.isScene === true ) ? scene : _scene;
  37673. const outputRenderTarget = this._renderTarget || this._outputRenderTarget;
  37674. const activeCubeFace = this._activeCubeFace;
  37675. const activeMipmapLevel = this._activeMipmapLevel;
  37676. //
  37677. let renderTarget;
  37678. if ( frameBufferTarget !== null ) {
  37679. renderTarget = frameBufferTarget;
  37680. this.setRenderTarget( renderTarget );
  37681. } else {
  37682. renderTarget = outputRenderTarget;
  37683. }
  37684. //
  37685. const renderContext = this._renderContexts.get( scene, camera, renderTarget );
  37686. this._currentRenderContext = renderContext;
  37687. this._currentRenderObjectFunction = this._renderObjectFunction || this.renderObject;
  37688. //
  37689. this.info.calls ++;
  37690. this.info.render.calls ++;
  37691. this.info.render.frameCalls ++;
  37692. nodeFrame.renderId = this.info.calls;
  37693. //
  37694. const coordinateSystem = this.coordinateSystem;
  37695. const xr = this.xr;
  37696. if ( camera.coordinateSystem !== coordinateSystem && xr.isPresenting === false ) {
  37697. camera.coordinateSystem = coordinateSystem;
  37698. camera.updateProjectionMatrix();
  37699. if ( camera.isArrayCamera ) {
  37700. for ( const subCamera of camera.cameras ) {
  37701. subCamera.coordinateSystem = coordinateSystem;
  37702. subCamera.updateProjectionMatrix();
  37703. }
  37704. }
  37705. }
  37706. //
  37707. if ( scene.matrixWorldAutoUpdate === true ) scene.updateMatrixWorld();
  37708. if ( camera.parent === null && camera.matrixWorldAutoUpdate === true ) camera.updateMatrixWorld();
  37709. if ( xr.enabled === true && xr.isPresenting === true ) {
  37710. if ( xr.cameraAutoUpdate === true ) xr.updateCamera( camera );
  37711. camera = xr.getCamera(); // use XR camera for rendering
  37712. }
  37713. //
  37714. let viewport = this._viewport;
  37715. let scissor = this._scissor;
  37716. let pixelRatio = this._pixelRatio;
  37717. if ( renderTarget !== null ) {
  37718. viewport = renderTarget.viewport;
  37719. scissor = renderTarget.scissor;
  37720. pixelRatio = 1;
  37721. }
  37722. this.getDrawingBufferSize( _drawingBufferSize$1 );
  37723. _screen.set( 0, 0, _drawingBufferSize$1.width, _drawingBufferSize$1.height );
  37724. const minDepth = ( viewport.minDepth === undefined ) ? 0 : viewport.minDepth;
  37725. const maxDepth = ( viewport.maxDepth === undefined ) ? 1 : viewport.maxDepth;
  37726. renderContext.viewportValue.copy( viewport ).multiplyScalar( pixelRatio ).floor();
  37727. renderContext.viewportValue.width >>= activeMipmapLevel;
  37728. renderContext.viewportValue.height >>= activeMipmapLevel;
  37729. renderContext.viewportValue.minDepth = minDepth;
  37730. renderContext.viewportValue.maxDepth = maxDepth;
  37731. renderContext.viewport = renderContext.viewportValue.equals( _screen ) === false;
  37732. renderContext.scissorValue.copy( scissor ).multiplyScalar( pixelRatio ).floor();
  37733. renderContext.scissor = this._scissorTest && renderContext.scissorValue.equals( _screen ) === false;
  37734. renderContext.scissorValue.width >>= activeMipmapLevel;
  37735. renderContext.scissorValue.height >>= activeMipmapLevel;
  37736. if ( ! renderContext.clippingContext ) renderContext.clippingContext = new ClippingContext();
  37737. renderContext.clippingContext.updateGlobal( sceneRef, camera );
  37738. //
  37739. sceneRef.onBeforeRender( this, scene, camera, renderTarget );
  37740. //
  37741. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  37742. if ( ! camera.isArrayCamera ) {
  37743. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  37744. frustum.setFromProjectionMatrix( _projScreenMatrix, coordinateSystem );
  37745. }
  37746. const renderList = this._renderLists.get( scene, camera );
  37747. renderList.begin();
  37748. this._projectObject( scene, camera, 0, renderList, renderContext.clippingContext );
  37749. renderList.finish();
  37750. if ( this.sortObjects === true ) {
  37751. renderList.sort( this._opaqueSort, this._transparentSort );
  37752. }
  37753. //
  37754. if ( renderTarget !== null ) {
  37755. this._textures.updateRenderTarget( renderTarget, activeMipmapLevel );
  37756. const renderTargetData = this._textures.get( renderTarget );
  37757. renderContext.textures = renderTargetData.textures;
  37758. renderContext.depthTexture = renderTargetData.depthTexture;
  37759. renderContext.width = renderTargetData.width;
  37760. renderContext.height = renderTargetData.height;
  37761. renderContext.renderTarget = renderTarget;
  37762. renderContext.depth = renderTarget.depthBuffer;
  37763. renderContext.stencil = renderTarget.stencilBuffer;
  37764. } else {
  37765. renderContext.textures = null;
  37766. renderContext.depthTexture = null;
  37767. renderContext.width = this.domElement.width;
  37768. renderContext.height = this.domElement.height;
  37769. renderContext.depth = this.depth;
  37770. renderContext.stencil = this.stencil;
  37771. }
  37772. renderContext.width >>= activeMipmapLevel;
  37773. renderContext.height >>= activeMipmapLevel;
  37774. renderContext.activeCubeFace = activeCubeFace;
  37775. renderContext.activeMipmapLevel = activeMipmapLevel;
  37776. renderContext.occlusionQueryCount = renderList.occlusionQueryCount;
  37777. //
  37778. this._background.update( sceneRef, renderList, renderContext );
  37779. //
  37780. renderContext.camera = camera;
  37781. this.backend.beginRender( renderContext );
  37782. // process render lists
  37783. const {
  37784. bundles,
  37785. lightsNode,
  37786. transparentDoublePass: transparentDoublePassObjects,
  37787. transparent: transparentObjects,
  37788. opaque: opaqueObjects
  37789. } = renderList;
  37790. if ( bundles.length > 0 ) this._renderBundles( bundles, sceneRef, lightsNode );
  37791. if ( this.opaque === true && opaqueObjects.length > 0 ) this._renderObjects( opaqueObjects, camera, sceneRef, lightsNode );
  37792. if ( this.transparent === true && transparentObjects.length > 0 ) this._renderTransparents( transparentObjects, transparentDoublePassObjects, camera, sceneRef, lightsNode );
  37793. // finish render pass
  37794. this.backend.finishRender( renderContext );
  37795. // restore render tree
  37796. nodeFrame.renderId = previousRenderId;
  37797. this._currentRenderContext = previousRenderContext;
  37798. this._currentRenderObjectFunction = previousRenderObjectFunction;
  37799. //
  37800. if ( frameBufferTarget !== null ) {
  37801. this.setRenderTarget( outputRenderTarget, activeCubeFace, activeMipmapLevel );
  37802. this._renderOutput( renderTarget );
  37803. }
  37804. //
  37805. sceneRef.onAfterRender( this, scene, camera, renderTarget );
  37806. //
  37807. return renderContext;
  37808. }
  37809. _setXRLayerSize( width, height ) {
  37810. this._width = width;
  37811. this._height = height;
  37812. this.setViewport( 0, 0, width, height );
  37813. }
  37814. /**
  37815. * The output pass performs tone mapping and color space conversion.
  37816. *
  37817. * @private
  37818. * @param {RenderTarget} renderTarget - The current render target.
  37819. */
  37820. _renderOutput( renderTarget ) {
  37821. const quad = this._quad;
  37822. if ( this._nodes.hasOutputChange( renderTarget.texture ) ) {
  37823. quad.material.fragmentNode = this._nodes.getOutputNode( renderTarget.texture );
  37824. quad.material.needsUpdate = true;
  37825. }
  37826. // a clear operation clears the intermediate renderTarget texture, but should not update the screen canvas.
  37827. const currentAutoClear = this.autoClear;
  37828. const currentXR = this.xr.enabled;
  37829. this.autoClear = false;
  37830. this.xr.enabled = false;
  37831. this._renderScene( quad, quad.camera, false );
  37832. this.autoClear = currentAutoClear;
  37833. this.xr.enabled = currentXR;
  37834. }
  37835. /**
  37836. * Returns the maximum available anisotropy for texture filtering.
  37837. *
  37838. * @return {number} The maximum available anisotropy.
  37839. */
  37840. getMaxAnisotropy() {
  37841. return this.backend.getMaxAnisotropy();
  37842. }
  37843. /**
  37844. * Returns the active cube face.
  37845. *
  37846. * @return {number} The active cube face.
  37847. */
  37848. getActiveCubeFace() {
  37849. return this._activeCubeFace;
  37850. }
  37851. /**
  37852. * Returns the active mipmap level.
  37853. *
  37854. * @return {number} The active mipmap level.
  37855. */
  37856. getActiveMipmapLevel() {
  37857. return this._activeMipmapLevel;
  37858. }
  37859. /**
  37860. * Applications are advised to always define the animation loop
  37861. * with this method and not manually with `requestAnimationFrame()`
  37862. * for best compatibility.
  37863. *
  37864. * @async
  37865. * @param {?Function} callback - The application's animation loop.
  37866. * @return {Promise} A Promise that resolves when the set has been executed.
  37867. */
  37868. async setAnimationLoop( callback ) {
  37869. if ( this._initialized === false ) await this.init();
  37870. this._animation.setAnimationLoop( callback );
  37871. }
  37872. /**
  37873. * Can be used to transfer buffer data from a storage buffer attribute
  37874. * from the GPU to the CPU in context of compute shaders.
  37875. *
  37876. * @async
  37877. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  37878. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  37879. */
  37880. async getArrayBufferAsync( attribute ) {
  37881. return await this.backend.getArrayBufferAsync( attribute );
  37882. }
  37883. /**
  37884. * Returns the rendering context.
  37885. *
  37886. * @return {GPUCanvasContext|WebGL2RenderingContext} The rendering context.
  37887. */
  37888. getContext() {
  37889. return this.backend.getContext();
  37890. }
  37891. /**
  37892. * Returns the pixel ratio.
  37893. *
  37894. * @return {number} The pixel ratio.
  37895. */
  37896. getPixelRatio() {
  37897. return this._pixelRatio;
  37898. }
  37899. /**
  37900. * Returns the drawing buffer size in physical pixels. This method honors the pixel ratio.
  37901. *
  37902. * @param {Vector2} target - The method writes the result in this target object.
  37903. * @return {Vector2} The drawing buffer size.
  37904. */
  37905. getDrawingBufferSize( target ) {
  37906. return target.set( this._width * this._pixelRatio, this._height * this._pixelRatio ).floor();
  37907. }
  37908. /**
  37909. * Returns the renderer's size in logical pixels. This method does not honor the pixel ratio.
  37910. *
  37911. * @param {Vector2} target - The method writes the result in this target object.
  37912. * @return {Vector2} The renderer's size in logical pixels.
  37913. */
  37914. getSize( target ) {
  37915. return target.set( this._width, this._height );
  37916. }
  37917. /**
  37918. * Sets the given pixel ratio and resizes the canvas if necessary.
  37919. *
  37920. * @param {number} [value=1] - The pixel ratio.
  37921. */
  37922. setPixelRatio( value = 1 ) {
  37923. if ( this._pixelRatio === value ) return;
  37924. this._pixelRatio = value;
  37925. this.setSize( this._width, this._height, false );
  37926. }
  37927. /**
  37928. * This method allows to define the drawing buffer size by specifying
  37929. * width, height and pixel ratio all at once. The size of the drawing
  37930. * buffer is computed with this formula:
  37931. * ```js
  37932. * size.x = width * pixelRatio;
  37933. * size.y = height * pixelRatio;
  37934. * ```
  37935. *
  37936. * @param {number} width - The width in logical pixels.
  37937. * @param {number} height - The height in logical pixels.
  37938. * @param {number} pixelRatio - The pixel ratio.
  37939. */
  37940. setDrawingBufferSize( width, height, pixelRatio ) {
  37941. // Renderer can't be resized while presenting in XR.
  37942. if ( this.xr && this.xr.isPresenting ) return;
  37943. this._width = width;
  37944. this._height = height;
  37945. this._pixelRatio = pixelRatio;
  37946. this.domElement.width = Math.floor( width * pixelRatio );
  37947. this.domElement.height = Math.floor( height * pixelRatio );
  37948. this.setViewport( 0, 0, width, height );
  37949. if ( this._initialized ) this.backend.updateSize();
  37950. }
  37951. /**
  37952. * Sets the size of the renderer.
  37953. *
  37954. * @param {number} width - The width in logical pixels.
  37955. * @param {number} height - The height in logical pixels.
  37956. * @param {boolean} [updateStyle=true] - Whether to update the `style` attribute of the canvas or not.
  37957. */
  37958. setSize( width, height, updateStyle = true ) {
  37959. // Renderer can't be resized while presenting in XR.
  37960. if ( this.xr && this.xr.isPresenting ) return;
  37961. this._width = width;
  37962. this._height = height;
  37963. this.domElement.width = Math.floor( width * this._pixelRatio );
  37964. this.domElement.height = Math.floor( height * this._pixelRatio );
  37965. if ( updateStyle === true ) {
  37966. this.domElement.style.width = width + 'px';
  37967. this.domElement.style.height = height + 'px';
  37968. }
  37969. this.setViewport( 0, 0, width, height );
  37970. if ( this._initialized ) this.backend.updateSize();
  37971. }
  37972. /**
  37973. * Defines a manual sort function for the opaque render list.
  37974. * Pass `null` to use the default sort.
  37975. *
  37976. * @param {Function} method - The sort function.
  37977. */
  37978. setOpaqueSort( method ) {
  37979. this._opaqueSort = method;
  37980. }
  37981. /**
  37982. * Defines a manual sort function for the transparent render list.
  37983. * Pass `null` to use the default sort.
  37984. *
  37985. * @param {Function} method - The sort function.
  37986. */
  37987. setTransparentSort( method ) {
  37988. this._transparentSort = method;
  37989. }
  37990. /**
  37991. * Returns the scissor rectangle.
  37992. *
  37993. * @param {Vector4} target - The method writes the result in this target object.
  37994. * @return {Vector4} The scissor rectangle.
  37995. */
  37996. getScissor( target ) {
  37997. const scissor = this._scissor;
  37998. target.x = scissor.x;
  37999. target.y = scissor.y;
  38000. target.width = scissor.width;
  38001. target.height = scissor.height;
  38002. return target;
  38003. }
  38004. /**
  38005. * Defines the scissor rectangle.
  38006. *
  38007. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the box in logical pixel unit.
  38008. * Instead of passing four arguments, the method also works with a single four-dimensional vector.
  38009. * @param {number} y - The vertical coordinate for the lower left corner of the box in logical pixel unit.
  38010. * @param {number} width - The width of the scissor box in logical pixel unit.
  38011. * @param {number} height - The height of the scissor box in logical pixel unit.
  38012. */
  38013. setScissor( x, y, width, height ) {
  38014. const scissor = this._scissor;
  38015. if ( x.isVector4 ) {
  38016. scissor.copy( x );
  38017. } else {
  38018. scissor.set( x, y, width, height );
  38019. }
  38020. }
  38021. /**
  38022. * Returns the scissor test value.
  38023. *
  38024. * @return {boolean} Whether the scissor test should be enabled or not.
  38025. */
  38026. getScissorTest() {
  38027. return this._scissorTest;
  38028. }
  38029. /**
  38030. * Defines the scissor test.
  38031. *
  38032. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  38033. */
  38034. setScissorTest( boolean ) {
  38035. this._scissorTest = boolean;
  38036. this.backend.setScissorTest( boolean );
  38037. }
  38038. /**
  38039. * Returns the viewport definition.
  38040. *
  38041. * @param {Vector4} target - The method writes the result in this target object.
  38042. * @return {Vector4} The viewport definition.
  38043. */
  38044. getViewport( target ) {
  38045. return target.copy( this._viewport );
  38046. }
  38047. /**
  38048. * Defines the viewport.
  38049. *
  38050. * @param {number | Vector4} x - The horizontal coordinate for the lower left corner of the viewport origin in logical pixel unit.
  38051. * @param {number} y - The vertical coordinate for the lower left corner of the viewport origin in logical pixel unit.
  38052. * @param {number} width - The width of the viewport in logical pixel unit.
  38053. * @param {number} height - The height of the viewport in logical pixel unit.
  38054. * @param {number} minDepth - The minimum depth value of the viewport. WebGPU only.
  38055. * @param {number} maxDepth - The maximum depth value of the viewport. WebGPU only.
  38056. */
  38057. setViewport( x, y, width, height, minDepth = 0, maxDepth = 1 ) {
  38058. const viewport = this._viewport;
  38059. if ( x.isVector4 ) {
  38060. viewport.copy( x );
  38061. } else {
  38062. viewport.set( x, y, width, height );
  38063. }
  38064. viewport.minDepth = minDepth;
  38065. viewport.maxDepth = maxDepth;
  38066. }
  38067. /**
  38068. * Returns the clear color.
  38069. *
  38070. * @param {Color} target - The method writes the result in this target object.
  38071. * @return {Color} The clear color.
  38072. */
  38073. getClearColor( target ) {
  38074. return target.copy( this._clearColor );
  38075. }
  38076. /**
  38077. * Defines the clear color and optionally the clear alpha.
  38078. *
  38079. * @param {Color} color - The clear color.
  38080. * @param {number} [alpha=1] - The clear alpha.
  38081. */
  38082. setClearColor( color, alpha = 1 ) {
  38083. this._clearColor.set( color );
  38084. this._clearColor.a = alpha;
  38085. }
  38086. /**
  38087. * Returns the clear alpha.
  38088. *
  38089. * @return {number} The clear alpha.
  38090. */
  38091. getClearAlpha() {
  38092. return this._clearColor.a;
  38093. }
  38094. /**
  38095. * Defines the clear alpha.
  38096. *
  38097. * @param {number} alpha - The clear alpha.
  38098. */
  38099. setClearAlpha( alpha ) {
  38100. this._clearColor.a = alpha;
  38101. }
  38102. /**
  38103. * Returns the clear depth.
  38104. *
  38105. * @return {number} The clear depth.
  38106. */
  38107. getClearDepth() {
  38108. return this._clearDepth;
  38109. }
  38110. /**
  38111. * Defines the clear depth.
  38112. *
  38113. * @param {number} depth - The clear depth.
  38114. */
  38115. setClearDepth( depth ) {
  38116. this._clearDepth = depth;
  38117. }
  38118. /**
  38119. * Returns the clear stencil.
  38120. *
  38121. * @return {number} The clear stencil.
  38122. */
  38123. getClearStencil() {
  38124. return this._clearStencil;
  38125. }
  38126. /**
  38127. * Defines the clear stencil.
  38128. *
  38129. * @param {number} stencil - The clear stencil.
  38130. */
  38131. setClearStencil( stencil ) {
  38132. this._clearStencil = stencil;
  38133. }
  38134. /**
  38135. * This method performs an occlusion query for the given 3D object.
  38136. * It returns `true` if the given 3D object is fully occluded by other
  38137. * 3D objects in the scene.
  38138. *
  38139. * @param {Object3D} object - The 3D object to test.
  38140. * @return {boolean} Whether the 3D object is fully occluded or not.
  38141. */
  38142. isOccluded( object ) {
  38143. const renderContext = this._currentRenderContext;
  38144. return renderContext && this.backend.isOccluded( renderContext, object );
  38145. }
  38146. /**
  38147. * Performs a manual clear operation. This method ignores `autoClear` properties.
  38148. *
  38149. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  38150. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  38151. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  38152. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38153. * Only returned when the renderer has not been initialized.
  38154. */
  38155. clear( color = true, depth = true, stencil = true ) {
  38156. if ( this._initialized === false ) {
  38157. console.warn( 'THREE.Renderer: .clear() called before the backend is initialized. Try using .clearAsync() instead.' );
  38158. return this.clearAsync( color, depth, stencil );
  38159. }
  38160. const renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38161. let renderContext = null;
  38162. if ( renderTarget !== null ) {
  38163. this._textures.updateRenderTarget( renderTarget );
  38164. const renderTargetData = this._textures.get( renderTarget );
  38165. renderContext = this._renderContexts.getForClear( renderTarget );
  38166. renderContext.textures = renderTargetData.textures;
  38167. renderContext.depthTexture = renderTargetData.depthTexture;
  38168. renderContext.width = renderTargetData.width;
  38169. renderContext.height = renderTargetData.height;
  38170. renderContext.renderTarget = renderTarget;
  38171. renderContext.depth = renderTarget.depthBuffer;
  38172. renderContext.stencil = renderTarget.stencilBuffer;
  38173. // #30329
  38174. renderContext.clearColorValue = this.backend.getClearColor();
  38175. renderContext.activeCubeFace = this.getActiveCubeFace();
  38176. renderContext.activeMipmapLevel = this.getActiveMipmapLevel();
  38177. }
  38178. this.backend.clear( color, depth, stencil, renderContext );
  38179. if ( renderTarget !== null && this._renderTarget === null ) {
  38180. this._renderOutput( renderTarget );
  38181. }
  38182. }
  38183. /**
  38184. * Performs a manual clear operation of the color buffer. This method ignores `autoClear` properties.
  38185. *
  38186. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38187. * Only returned when the renderer has not been initialized.
  38188. */
  38189. clearColor() {
  38190. return this.clear( true, false, false );
  38191. }
  38192. /**
  38193. * Performs a manual clear operation of the depth buffer. This method ignores `autoClear` properties.
  38194. *
  38195. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38196. * Only returned when the renderer has not been initialized.
  38197. */
  38198. clearDepth() {
  38199. return this.clear( false, true, false );
  38200. }
  38201. /**
  38202. * Performs a manual clear operation of the stencil buffer. This method ignores `autoClear` properties.
  38203. *
  38204. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38205. * Only returned when the renderer has not been initialized.
  38206. */
  38207. clearStencil() {
  38208. return this.clear( false, false, true );
  38209. }
  38210. /**
  38211. * Async version of {@link Renderer#clear}.
  38212. *
  38213. * @async
  38214. * @param {boolean} [color=true] - Whether the color buffer should be cleared or not.
  38215. * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not.
  38216. * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not.
  38217. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38218. */
  38219. async clearAsync( color = true, depth = true, stencil = true ) {
  38220. if ( this._initialized === false ) await this.init();
  38221. this.clear( color, depth, stencil );
  38222. }
  38223. /**
  38224. * Async version of {@link Renderer#clearColor}.
  38225. *
  38226. * @async
  38227. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38228. */
  38229. async clearColorAsync() {
  38230. this.clearAsync( true, false, false );
  38231. }
  38232. /**
  38233. * Async version of {@link Renderer#clearDepth}.
  38234. *
  38235. * @async
  38236. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38237. */
  38238. async clearDepthAsync() {
  38239. this.clearAsync( false, true, false );
  38240. }
  38241. /**
  38242. * Async version of {@link Renderer#clearStencil}.
  38243. *
  38244. * @async
  38245. * @return {Promise} A Promise that resolves when the clear operation has been executed.
  38246. */
  38247. async clearStencilAsync() {
  38248. this.clearAsync( false, false, true );
  38249. }
  38250. /**
  38251. * The current output tone mapping of the renderer. When a render target is set,
  38252. * the output tone mapping is always `NoToneMapping`.
  38253. *
  38254. * @type {number}
  38255. */
  38256. get currentToneMapping() {
  38257. return this.isOutputTarget ? this.toneMapping : NoToneMapping;
  38258. }
  38259. /**
  38260. * The current output color space of the renderer. When a render target is set,
  38261. * the output color space is always `LinearSRGBColorSpace`.
  38262. *
  38263. * @type {string}
  38264. */
  38265. get currentColorSpace() {
  38266. return this.isOutputTarget ? this.outputColorSpace : LinearSRGBColorSpace;
  38267. }
  38268. /**
  38269. * Returns `true` if the rendering settings are set to screen output.
  38270. *
  38271. * @returns {boolean} True if the current render target is the same of output render target or `null`, otherwise false.
  38272. */
  38273. get isOutputTarget() {
  38274. return this._renderTarget === this._outputRenderTarget || this._renderTarget === null;
  38275. }
  38276. /**
  38277. * Frees all internal resources of the renderer. Call this method if the renderer
  38278. * is no longer in use by your app.
  38279. */
  38280. dispose() {
  38281. this.info.dispose();
  38282. this.backend.dispose();
  38283. this._animation.dispose();
  38284. this._objects.dispose();
  38285. this._pipelines.dispose();
  38286. this._nodes.dispose();
  38287. this._bindings.dispose();
  38288. this._renderLists.dispose();
  38289. this._renderContexts.dispose();
  38290. this._textures.dispose();
  38291. if ( this._frameBufferTarget !== null ) this._frameBufferTarget.dispose();
  38292. Object.values( this.backend.timestampQueryPool ).forEach( queryPool => {
  38293. if ( queryPool !== null ) queryPool.dispose();
  38294. } );
  38295. this.setRenderTarget( null );
  38296. this.setAnimationLoop( null );
  38297. }
  38298. /**
  38299. * Sets the given render target. Calling this method means the renderer does not
  38300. * target the default framebuffer (meaning the canvas) anymore but a custom framebuffer.
  38301. * Use `null` as the first argument to reset the state.
  38302. *
  38303. * @param {?RenderTarget} renderTarget - The render target to set.
  38304. * @param {number} [activeCubeFace=0] - The active cube face.
  38305. * @param {number} [activeMipmapLevel=0] - The active mipmap level.
  38306. */
  38307. setRenderTarget( renderTarget, activeCubeFace = 0, activeMipmapLevel = 0 ) {
  38308. this._renderTarget = renderTarget;
  38309. this._activeCubeFace = activeCubeFace;
  38310. this._activeMipmapLevel = activeMipmapLevel;
  38311. }
  38312. /**
  38313. * Returns the current render target.
  38314. *
  38315. * @return {?RenderTarget} The render target. Returns `null` if no render target is set.
  38316. */
  38317. getRenderTarget() {
  38318. return this._renderTarget;
  38319. }
  38320. /**
  38321. * Sets the output render target for the renderer.
  38322. *
  38323. * @param {Object} renderTarget - The render target to set as the output target.
  38324. */
  38325. setOutputRenderTarget( renderTarget ) {
  38326. this._outputRenderTarget = renderTarget;
  38327. }
  38328. /**
  38329. * Returns the current output target.
  38330. *
  38331. * @return {?RenderTarget} The current output render target. Returns `null` if no output target is set.
  38332. */
  38333. getOutputRenderTarget() {
  38334. return this._outputRenderTarget;
  38335. }
  38336. /**
  38337. * Resets the renderer to the initial state before WebXR started.
  38338. *
  38339. */
  38340. _resetXRState() {
  38341. this.backend.setXRTarget( null );
  38342. this.setOutputRenderTarget( null );
  38343. this.setRenderTarget( null );
  38344. this._frameBufferTarget.dispose();
  38345. this._frameBufferTarget = null;
  38346. }
  38347. /**
  38348. * Callback for {@link Renderer#setRenderObjectFunction}.
  38349. *
  38350. * @callback renderObjectFunction
  38351. * @param {Object3D} object - The 3D object.
  38352. * @param {Scene} scene - The scene the 3D object belongs to.
  38353. * @param {Camera} camera - The camera the object should be rendered with.
  38354. * @param {BufferGeometry} geometry - The object's geometry.
  38355. * @param {Material} material - The object's material.
  38356. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38357. * @param {LightsNode} lightsNode - The current lights node.
  38358. * @param {ClippingContext} clippingContext - The clipping context.
  38359. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38360. */
  38361. /**
  38362. * Sets the given render object function. Calling this method overwrites the default implementation
  38363. * which is {@link Renderer#renderObject}. Defining a custom function can be useful
  38364. * if you want to modify the way objects are rendered. For example you can define things like "every
  38365. * object that has material of a certain type should perform a pre-pass with a special overwrite material".
  38366. * The custom function must always call `renderObject()` in its implementation.
  38367. *
  38368. * Use `null` as the first argument to reset the state.
  38369. *
  38370. * @param {?renderObjectFunction} renderObjectFunction - The render object function.
  38371. */
  38372. setRenderObjectFunction( renderObjectFunction ) {
  38373. this._renderObjectFunction = renderObjectFunction;
  38374. }
  38375. /**
  38376. * Returns the current render object function.
  38377. *
  38378. * @return {?Function} The current render object function. Returns `null` if no function is set.
  38379. */
  38380. getRenderObjectFunction() {
  38381. return this._renderObjectFunction;
  38382. }
  38383. /**
  38384. * Execute a single or an array of compute nodes. This method can only be called
  38385. * if the renderer has been initialized.
  38386. *
  38387. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  38388. * @return {Promise|undefined} A Promise that resolve when the compute has finished. Only returned when the renderer has not been initialized.
  38389. */
  38390. compute( computeNodes ) {
  38391. if ( this._isDeviceLost === true ) return;
  38392. if ( this._initialized === false ) {
  38393. console.warn( 'THREE.Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead.' );
  38394. return this.computeAsync( computeNodes );
  38395. }
  38396. //
  38397. const nodeFrame = this._nodes.nodeFrame;
  38398. const previousRenderId = nodeFrame.renderId;
  38399. //
  38400. this.info.calls ++;
  38401. this.info.compute.calls ++;
  38402. this.info.compute.frameCalls ++;
  38403. nodeFrame.renderId = this.info.calls;
  38404. //
  38405. const backend = this.backend;
  38406. const pipelines = this._pipelines;
  38407. const bindings = this._bindings;
  38408. const nodes = this._nodes;
  38409. const computeList = Array.isArray( computeNodes ) ? computeNodes : [ computeNodes ];
  38410. if ( computeList[ 0 ] === undefined || computeList[ 0 ].isComputeNode !== true ) {
  38411. throw new Error( 'THREE.Renderer: .compute() expects a ComputeNode.' );
  38412. }
  38413. backend.beginCompute( computeNodes );
  38414. for ( const computeNode of computeList ) {
  38415. // onInit
  38416. if ( pipelines.has( computeNode ) === false ) {
  38417. const dispose = () => {
  38418. computeNode.removeEventListener( 'dispose', dispose );
  38419. pipelines.delete( computeNode );
  38420. bindings.delete( computeNode );
  38421. nodes.delete( computeNode );
  38422. };
  38423. computeNode.addEventListener( 'dispose', dispose );
  38424. //
  38425. const onInitFn = computeNode.onInitFunction;
  38426. if ( onInitFn !== null ) {
  38427. onInitFn.call( computeNode, { renderer: this } );
  38428. }
  38429. }
  38430. nodes.updateForCompute( computeNode );
  38431. bindings.updateForCompute( computeNode );
  38432. const computeBindings = bindings.getForCompute( computeNode );
  38433. const computePipeline = pipelines.getForCompute( computeNode, computeBindings );
  38434. backend.compute( computeNodes, computeNode, computeBindings, computePipeline );
  38435. }
  38436. backend.finishCompute( computeNodes );
  38437. //
  38438. nodeFrame.renderId = previousRenderId;
  38439. }
  38440. /**
  38441. * Execute a single or an array of compute nodes.
  38442. *
  38443. * @async
  38444. * @param {Node|Array<Node>} computeNodes - The compute node(s).
  38445. * @return {Promise} A Promise that resolve when the compute has finished.
  38446. */
  38447. async computeAsync( computeNodes ) {
  38448. if ( this._initialized === false ) await this.init();
  38449. this.compute( computeNodes );
  38450. }
  38451. /**
  38452. * Checks if the given feature is supported by the selected backend.
  38453. *
  38454. * @async
  38455. * @param {string} name - The feature's name.
  38456. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  38457. */
  38458. async hasFeatureAsync( name ) {
  38459. if ( this._initialized === false ) await this.init();
  38460. return this.backend.hasFeature( name );
  38461. }
  38462. async resolveTimestampsAsync( type = 'render' ) {
  38463. if ( this._initialized === false ) await this.init();
  38464. return this.backend.resolveTimestampsAsync( type );
  38465. }
  38466. /**
  38467. * Checks if the given feature is supported by the selected backend. If the
  38468. * renderer has not been initialized, this method always returns `false`.
  38469. *
  38470. * @param {string} name - The feature's name.
  38471. * @return {boolean} Whether the feature is supported or not.
  38472. */
  38473. hasFeature( name ) {
  38474. if ( this._initialized === false ) {
  38475. console.warn( 'THREE.Renderer: .hasFeature() called before the backend is initialized. Try using .hasFeatureAsync() instead.' );
  38476. return false;
  38477. }
  38478. return this.backend.hasFeature( name );
  38479. }
  38480. /**
  38481. * Returns `true` when the renderer has been initialized.
  38482. *
  38483. * @return {boolean} Whether the renderer has been initialized or not.
  38484. */
  38485. hasInitialized() {
  38486. return this._initialized;
  38487. }
  38488. /**
  38489. * Initializes the given textures. Useful for preloading a texture rather than waiting until first render
  38490. * (which can cause noticeable lags due to decode and GPU upload overhead).
  38491. *
  38492. * @async
  38493. * @param {Texture} texture - The texture.
  38494. * @return {Promise} A Promise that resolves when the texture has been initialized.
  38495. */
  38496. async initTextureAsync( texture ) {
  38497. if ( this._initialized === false ) await this.init();
  38498. this._textures.updateTexture( texture );
  38499. }
  38500. /**
  38501. * Initializes the given texture. Useful for preloading a texture rather than waiting until first render
  38502. * (which can cause noticeable lags due to decode and GPU upload overhead).
  38503. *
  38504. * This method can only be used if the renderer has been initialized.
  38505. *
  38506. * @param {Texture} texture - The texture.
  38507. */
  38508. initTexture( texture ) {
  38509. if ( this._initialized === false ) {
  38510. console.warn( 'THREE.Renderer: .initTexture() called before the backend is initialized. Try using .initTextureAsync() instead.' );
  38511. }
  38512. this._textures.updateTexture( texture );
  38513. }
  38514. /**
  38515. * Copies the current bound framebuffer into the given texture.
  38516. *
  38517. * @param {FramebufferTexture} framebufferTexture - The texture.
  38518. * @param {?Vector2|Vector4} [rectangle=null] - A two or four dimensional vector that defines the rectangular portion of the framebuffer that should be copied.
  38519. */
  38520. copyFramebufferToTexture( framebufferTexture, rectangle = null ) {
  38521. if ( rectangle !== null ) {
  38522. if ( rectangle.isVector2 ) {
  38523. rectangle = _vector4.set( rectangle.x, rectangle.y, framebufferTexture.image.width, framebufferTexture.image.height ).floor();
  38524. } else if ( rectangle.isVector4 ) {
  38525. rectangle = _vector4.copy( rectangle ).floor();
  38526. } else {
  38527. console.error( 'THREE.Renderer.copyFramebufferToTexture: Invalid rectangle.' );
  38528. return;
  38529. }
  38530. } else {
  38531. rectangle = _vector4.set( 0, 0, framebufferTexture.image.width, framebufferTexture.image.height );
  38532. }
  38533. //
  38534. let renderContext = this._currentRenderContext;
  38535. let renderTarget;
  38536. if ( renderContext !== null ) {
  38537. renderTarget = renderContext.renderTarget;
  38538. } else {
  38539. renderTarget = this._renderTarget || this._getFrameBufferTarget();
  38540. if ( renderTarget !== null ) {
  38541. this._textures.updateRenderTarget( renderTarget );
  38542. renderContext = this._textures.get( renderTarget );
  38543. }
  38544. }
  38545. //
  38546. this._textures.updateTexture( framebufferTexture, { renderTarget } );
  38547. this.backend.copyFramebufferToTexture( framebufferTexture, renderContext, rectangle );
  38548. }
  38549. /**
  38550. * Copies data of the given source texture into a destination texture.
  38551. *
  38552. * @param {Texture} srcTexture - The source texture.
  38553. * @param {Texture} dstTexture - The destination texture.
  38554. * @param {Box2|Box3} [srcRegion=null] - A bounding box which describes the source region. Can be two or three-dimensional.
  38555. * @param {Vector2|Vector3} [dstPosition=null] - A vector that represents the origin of the destination region. Can be two or three-dimensional.
  38556. * @param {number} [srcLevel=0] - The source mip level to copy from.
  38557. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  38558. */
  38559. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  38560. this._textures.updateTexture( srcTexture );
  38561. this._textures.updateTexture( dstTexture );
  38562. this.backend.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  38563. }
  38564. /**
  38565. * Reads pixel data from the given render target.
  38566. *
  38567. * @async
  38568. * @param {RenderTarget} renderTarget - The render target to read from.
  38569. * @param {number} x - The `x` coordinate of the copy region's origin.
  38570. * @param {number} y - The `y` coordinate of the copy region's origin.
  38571. * @param {number} width - The width of the copy region.
  38572. * @param {number} height - The height of the copy region.
  38573. * @param {number} [textureIndex=0] - The texture index of a MRT render target.
  38574. * @param {number} [faceIndex=0] - The active cube face index.
  38575. * @return {Promise<TypedArray>} A Promise that resolves when the read has been finished. The resolve provides the read data as a typed array.
  38576. */
  38577. async readRenderTargetPixelsAsync( renderTarget, x, y, width, height, textureIndex = 0, faceIndex = 0 ) {
  38578. return this.backend.copyTextureToBuffer( renderTarget.textures[ textureIndex ], x, y, width, height, faceIndex );
  38579. }
  38580. /**
  38581. * Analyzes the given 3D object's hierarchy and builds render lists from the
  38582. * processed hierarchy.
  38583. *
  38584. * @param {Object3D} object - The 3D object to process (usually a scene).
  38585. * @param {Camera} camera - The camera the object is rendered with.
  38586. * @param {number} groupOrder - The group order is derived from the `renderOrder` of groups and is used to group 3D objects within groups.
  38587. * @param {RenderList} renderList - The current render list.
  38588. * @param {ClippingContext} clippingContext - The current clipping context.
  38589. */
  38590. _projectObject( object, camera, groupOrder, renderList, clippingContext ) {
  38591. if ( object.visible === false ) return;
  38592. const visible = object.layers.test( camera.layers );
  38593. if ( visible ) {
  38594. if ( object.isGroup ) {
  38595. groupOrder = object.renderOrder;
  38596. if ( object.isClippingGroup && object.enabled ) clippingContext = clippingContext.getGroupContext( object );
  38597. } else if ( object.isLOD ) {
  38598. if ( object.autoUpdate === true ) object.update( camera );
  38599. } else if ( object.isLight ) {
  38600. renderList.pushLight( object );
  38601. } else if ( object.isSprite ) {
  38602. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  38603. if ( ! object.frustumCulled || frustum.intersectsSprite( object, camera ) ) {
  38604. if ( this.sortObjects === true ) {
  38605. _vector4.setFromMatrixPosition( object.matrixWorld ).applyMatrix4( _projScreenMatrix );
  38606. }
  38607. const { geometry, material } = object;
  38608. if ( material.visible ) {
  38609. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  38610. }
  38611. }
  38612. } else if ( object.isLineLoop ) {
  38613. console.error( 'THREE.Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.' );
  38614. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  38615. const frustum = camera.isArrayCamera ? _frustumArray : _frustum;
  38616. if ( ! object.frustumCulled || frustum.intersectsObject( object, camera ) ) {
  38617. const { geometry, material } = object;
  38618. if ( this.sortObjects === true ) {
  38619. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  38620. _vector4
  38621. .copy( geometry.boundingSphere.center )
  38622. .applyMatrix4( object.matrixWorld )
  38623. .applyMatrix4( _projScreenMatrix );
  38624. }
  38625. if ( Array.isArray( material ) ) {
  38626. const groups = geometry.groups;
  38627. for ( let i = 0, l = groups.length; i < l; i ++ ) {
  38628. const group = groups[ i ];
  38629. const groupMaterial = material[ group.materialIndex ];
  38630. if ( groupMaterial && groupMaterial.visible ) {
  38631. renderList.push( object, geometry, groupMaterial, groupOrder, _vector4.z, group, clippingContext );
  38632. }
  38633. }
  38634. } else if ( material.visible ) {
  38635. renderList.push( object, geometry, material, groupOrder, _vector4.z, null, clippingContext );
  38636. }
  38637. }
  38638. }
  38639. }
  38640. if ( object.isBundleGroup === true && this.backend.beginBundle !== undefined ) {
  38641. const baseRenderList = renderList;
  38642. // replace render list
  38643. renderList = this._renderLists.get( object, camera );
  38644. renderList.begin();
  38645. baseRenderList.pushBundle( {
  38646. bundleGroup: object,
  38647. camera,
  38648. renderList,
  38649. } );
  38650. renderList.finish();
  38651. }
  38652. const children = object.children;
  38653. for ( let i = 0, l = children.length; i < l; i ++ ) {
  38654. this._projectObject( children[ i ], camera, groupOrder, renderList, clippingContext );
  38655. }
  38656. }
  38657. /**
  38658. * Renders the given render bundles.
  38659. *
  38660. * @private
  38661. * @param {Array<Object>} bundles - Array with render bundle data.
  38662. * @param {Scene} sceneRef - The scene the render bundles belong to.
  38663. * @param {LightsNode} lightsNode - The current lights node.
  38664. */
  38665. _renderBundles( bundles, sceneRef, lightsNode ) {
  38666. for ( const bundle of bundles ) {
  38667. this._renderBundle( bundle, sceneRef, lightsNode );
  38668. }
  38669. }
  38670. /**
  38671. * Renders the transparent objects from the given render lists.
  38672. *
  38673. * @private
  38674. * @param {Array<Object>} renderList - The transparent render list.
  38675. * @param {Array<Object>} doublePassList - The list of transparent objects which require a double pass (e.g. because of transmission).
  38676. * @param {Camera} camera - The camera the render list should be rendered with.
  38677. * @param {Scene} scene - The scene the render list belongs to.
  38678. * @param {LightsNode} lightsNode - The current lights node.
  38679. */
  38680. _renderTransparents( renderList, doublePassList, camera, scene, lightsNode ) {
  38681. if ( doublePassList.length > 0 ) {
  38682. // render back side
  38683. for ( const { material } of doublePassList ) {
  38684. material.side = BackSide;
  38685. }
  38686. this._renderObjects( doublePassList, camera, scene, lightsNode, 'backSide' );
  38687. // render front side
  38688. for ( const { material } of doublePassList ) {
  38689. material.side = FrontSide;
  38690. }
  38691. this._renderObjects( renderList, camera, scene, lightsNode );
  38692. // restore
  38693. for ( const { material } of doublePassList ) {
  38694. material.side = DoubleSide;
  38695. }
  38696. } else {
  38697. this._renderObjects( renderList, camera, scene, lightsNode );
  38698. }
  38699. }
  38700. /**
  38701. * Renders the objects from the given render list.
  38702. *
  38703. * @private
  38704. * @param {Array<Object>} renderList - The render list.
  38705. * @param {Camera} camera - The camera the render list should be rendered with.
  38706. * @param {Scene} scene - The scene the render list belongs to.
  38707. * @param {LightsNode} lightsNode - The current lights node.
  38708. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38709. */
  38710. _renderObjects( renderList, camera, scene, lightsNode, passId = null ) {
  38711. for ( let i = 0, il = renderList.length; i < il; i ++ ) {
  38712. const { object, geometry, material, group, clippingContext } = renderList[ i ];
  38713. this._currentRenderObjectFunction( object, scene, camera, geometry, material, group, lightsNode, clippingContext, passId );
  38714. }
  38715. }
  38716. /**
  38717. * This method represents the default render object function that manages the render lifecycle
  38718. * of the object.
  38719. *
  38720. * @param {Object3D} object - The 3D object.
  38721. * @param {Scene} scene - The scene the 3D object belongs to.
  38722. * @param {Camera} camera - The camera the object should be rendered with.
  38723. * @param {BufferGeometry} geometry - The object's geometry.
  38724. * @param {Material} material - The object's material.
  38725. * @param {?Object} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38726. * @param {LightsNode} lightsNode - The current lights node.
  38727. * @param {?ClippingContext} clippingContext - The clipping context.
  38728. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38729. */
  38730. renderObject( object, scene, camera, geometry, material, group, lightsNode, clippingContext = null, passId = null ) {
  38731. let overridePositionNode;
  38732. let overrideColorNode;
  38733. let overrideDepthNode;
  38734. //
  38735. object.onBeforeRender( this, scene, camera, geometry, material, group );
  38736. //
  38737. if ( material.allowOverride === true && scene.overrideMaterial !== null ) {
  38738. const overrideMaterial = scene.overrideMaterial;
  38739. if ( material.positionNode && material.positionNode.isNode ) {
  38740. overridePositionNode = overrideMaterial.positionNode;
  38741. overrideMaterial.positionNode = material.positionNode;
  38742. }
  38743. overrideMaterial.alphaTest = material.alphaTest;
  38744. overrideMaterial.alphaMap = material.alphaMap;
  38745. overrideMaterial.transparent = material.transparent || material.transmission > 0;
  38746. if ( overrideMaterial.isShadowPassMaterial ) {
  38747. overrideMaterial.side = material.shadowSide === null ? material.side : material.shadowSide;
  38748. if ( material.depthNode && material.depthNode.isNode ) {
  38749. overrideDepthNode = overrideMaterial.depthNode;
  38750. overrideMaterial.depthNode = material.depthNode;
  38751. }
  38752. if ( material.castShadowNode && material.castShadowNode.isNode ) {
  38753. overrideColorNode = overrideMaterial.colorNode;
  38754. overrideMaterial.colorNode = material.castShadowNode;
  38755. }
  38756. if ( material.castShadowPositionNode && material.castShadowPositionNode.isNode ) {
  38757. overridePositionNode = overrideMaterial.positionNode;
  38758. overrideMaterial.positionNode = material.castShadowPositionNode;
  38759. }
  38760. }
  38761. material = overrideMaterial;
  38762. }
  38763. //
  38764. if ( material.transparent === true && material.side === DoubleSide && material.forceSinglePass === false ) {
  38765. material.side = BackSide;
  38766. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, 'backSide' ); // create backSide pass id
  38767. material.side = FrontSide;
  38768. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId ); // use default pass id
  38769. material.side = DoubleSide;
  38770. } else {
  38771. this._handleObjectFunction( object, material, scene, camera, lightsNode, group, clippingContext, passId );
  38772. }
  38773. //
  38774. if ( overridePositionNode !== undefined ) {
  38775. scene.overrideMaterial.positionNode = overridePositionNode;
  38776. }
  38777. if ( overrideDepthNode !== undefined ) {
  38778. scene.overrideMaterial.depthNode = overrideDepthNode;
  38779. }
  38780. if ( overrideColorNode !== undefined ) {
  38781. scene.overrideMaterial.colorNode = overrideColorNode;
  38782. }
  38783. //
  38784. object.onAfterRender( this, scene, camera, geometry, material, group );
  38785. }
  38786. /**
  38787. * This method represents the default `_handleObjectFunction` implementation which creates
  38788. * a render object from the given data and performs the draw command with the selected backend.
  38789. *
  38790. * @private
  38791. * @param {Object3D} object - The 3D object.
  38792. * @param {Material} material - The object's material.
  38793. * @param {Scene} scene - The scene the 3D object belongs to.
  38794. * @param {Camera} camera - The camera the object should be rendered with.
  38795. * @param {LightsNode} lightsNode - The current lights node.
  38796. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38797. * @param {ClippingContext} clippingContext - The clipping context.
  38798. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38799. */
  38800. _renderObjectDirect( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  38801. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  38802. renderObject.drawRange = object.geometry.drawRange;
  38803. renderObject.group = group;
  38804. //
  38805. const needsRefresh = this._nodes.needsRefresh( renderObject );
  38806. if ( needsRefresh ) {
  38807. this._nodes.updateBefore( renderObject );
  38808. this._geometries.updateForRender( renderObject );
  38809. this._nodes.updateForRender( renderObject );
  38810. this._bindings.updateForRender( renderObject );
  38811. }
  38812. this._pipelines.updateForRender( renderObject );
  38813. //
  38814. if ( this._currentRenderBundle !== null ) {
  38815. const renderBundleData = this.backend.get( this._currentRenderBundle );
  38816. renderBundleData.renderObjects.push( renderObject );
  38817. renderObject.bundle = this._currentRenderBundle.bundleGroup;
  38818. }
  38819. this.backend.draw( renderObject, this.info );
  38820. if ( needsRefresh ) this._nodes.updateAfter( renderObject );
  38821. }
  38822. /**
  38823. * A different implementation for `_handleObjectFunction` which only makes sure the object is ready for rendering.
  38824. * Used in `compileAsync()`.
  38825. *
  38826. * @private
  38827. * @param {Object3D} object - The 3D object.
  38828. * @param {Material} material - The object's material.
  38829. * @param {Scene} scene - The scene the 3D object belongs to.
  38830. * @param {Camera} camera - The camera the object should be rendered with.
  38831. * @param {LightsNode} lightsNode - The current lights node.
  38832. * @param {?{start: number, count: number}} group - Only relevant for objects using multiple materials. This represents a group entry from the respective `BufferGeometry`.
  38833. * @param {ClippingContext} clippingContext - The clipping context.
  38834. * @param {?string} [passId=null] - An optional ID for identifying the pass.
  38835. */
  38836. _createObjectPipeline( object, material, scene, camera, lightsNode, group, clippingContext, passId ) {
  38837. const renderObject = this._objects.get( object, material, scene, camera, lightsNode, this._currentRenderContext, clippingContext, passId );
  38838. renderObject.drawRange = object.geometry.drawRange;
  38839. renderObject.group = group;
  38840. //
  38841. this._nodes.updateBefore( renderObject );
  38842. this._geometries.updateForRender( renderObject );
  38843. this._nodes.updateForRender( renderObject );
  38844. this._bindings.updateForRender( renderObject );
  38845. this._pipelines.getForRender( renderObject, this._compilationPromises );
  38846. this._nodes.updateAfter( renderObject );
  38847. }
  38848. /**
  38849. * Alias for `compileAsync()`.
  38850. *
  38851. * @method
  38852. * @param {Object3D} scene - The scene or 3D object to precompile.
  38853. * @param {Camera} camera - The camera that is used to render the scene.
  38854. * @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.
  38855. * @return {function(Object3D, Camera, ?Scene): Promise|undefined} A Promise that resolves when the compile has been finished.
  38856. */
  38857. get compile() {
  38858. return this.compileAsync;
  38859. }
  38860. }
  38861. /**
  38862. * A binding represents the connection between a resource (like a texture, sampler
  38863. * or uniform buffer) and the resource definition in a shader stage.
  38864. *
  38865. * This module is an abstract base class for all concrete bindings types.
  38866. *
  38867. * @abstract
  38868. * @private
  38869. */
  38870. class Binding {
  38871. /**
  38872. * Constructs a new binding.
  38873. *
  38874. * @param {string} [name=''] - The binding's name.
  38875. */
  38876. constructor( name = '' ) {
  38877. /**
  38878. * The binding's name.
  38879. *
  38880. * @type {string}
  38881. */
  38882. this.name = name;
  38883. /**
  38884. * A bitmask that defines in what shader stages the
  38885. * binding's resource is accessible.
  38886. *
  38887. * @type {number}
  38888. */
  38889. this.visibility = 0;
  38890. }
  38891. /**
  38892. * Makes sure binding's resource is visible for the given shader stage.
  38893. *
  38894. * @param {number} visibility - The shader stage.
  38895. */
  38896. setVisibility( visibility ) {
  38897. this.visibility |= visibility;
  38898. }
  38899. /**
  38900. * Clones the binding.
  38901. *
  38902. * @return {Binding} The cloned binding.
  38903. */
  38904. clone() {
  38905. return Object.assign( new this.constructor(), this );
  38906. }
  38907. }
  38908. /**
  38909. * This function is usually called with the length in bytes of an array buffer.
  38910. * It returns an padded value which ensure chunk size alignment according to STD140 layout.
  38911. *
  38912. * @function
  38913. * @param {number} floatLength - The buffer length.
  38914. * @return {number} The padded length.
  38915. */
  38916. function getFloatLength( floatLength ) {
  38917. // ensure chunk size alignment (STD140 layout)
  38918. return floatLength + ( ( GPU_CHUNK_BYTES - ( floatLength % GPU_CHUNK_BYTES ) ) % GPU_CHUNK_BYTES );
  38919. }
  38920. /**
  38921. * Represents a buffer binding type.
  38922. *
  38923. * @private
  38924. * @abstract
  38925. * @augments Binding
  38926. */
  38927. class Buffer extends Binding {
  38928. /**
  38929. * Constructs a new buffer.
  38930. *
  38931. * @param {string} name - The buffer's name.
  38932. * @param {TypedArray} [buffer=null] - The buffer.
  38933. */
  38934. constructor( name, buffer = null ) {
  38935. super( name );
  38936. /**
  38937. * This flag can be used for type testing.
  38938. *
  38939. * @type {boolean}
  38940. * @readonly
  38941. * @default true
  38942. */
  38943. this.isBuffer = true;
  38944. /**
  38945. * The bytes per element.
  38946. *
  38947. * @type {number}
  38948. */
  38949. this.bytesPerElement = Float32Array.BYTES_PER_ELEMENT;
  38950. /**
  38951. * A reference to the internal buffer.
  38952. *
  38953. * @private
  38954. * @type {TypedArray}
  38955. */
  38956. this._buffer = buffer;
  38957. }
  38958. /**
  38959. * The buffer's byte length.
  38960. *
  38961. * @type {number}
  38962. * @readonly
  38963. */
  38964. get byteLength() {
  38965. return getFloatLength( this._buffer.byteLength );
  38966. }
  38967. /**
  38968. * A reference to the internal buffer.
  38969. *
  38970. * @type {Float32Array}
  38971. * @readonly
  38972. */
  38973. get buffer() {
  38974. return this._buffer;
  38975. }
  38976. /**
  38977. * Updates the binding.
  38978. *
  38979. * @return {boolean} Whether the buffer has been updated and must be
  38980. * uploaded to the GPU.
  38981. */
  38982. update() {
  38983. return true;
  38984. }
  38985. }
  38986. /**
  38987. * Represents a uniform buffer binding type.
  38988. *
  38989. * @private
  38990. * @augments Buffer
  38991. */
  38992. class UniformBuffer extends Buffer {
  38993. /**
  38994. * Constructs a new uniform buffer.
  38995. *
  38996. * @param {string} name - The buffer's name.
  38997. * @param {TypedArray} [buffer=null] - The buffer.
  38998. */
  38999. constructor( name, buffer = null ) {
  39000. super( name, buffer );
  39001. /**
  39002. * This flag can be used for type testing.
  39003. *
  39004. * @type {boolean}
  39005. * @readonly
  39006. * @default true
  39007. */
  39008. this.isUniformBuffer = true;
  39009. }
  39010. }
  39011. let _id$4 = 0;
  39012. /**
  39013. * A special form of uniform buffer binding type.
  39014. * It's buffer value is managed by a node object.
  39015. *
  39016. * @private
  39017. * @augments UniformBuffer
  39018. */
  39019. class NodeUniformBuffer extends UniformBuffer {
  39020. /**
  39021. * Constructs a new node-based uniform buffer.
  39022. *
  39023. * @param {BufferNode} nodeUniform - The uniform buffer node.
  39024. * @param {UniformGroupNode} groupNode - The uniform group node.
  39025. */
  39026. constructor( nodeUniform, groupNode ) {
  39027. super( 'UniformBuffer_' + _id$4 ++, nodeUniform ? nodeUniform.value : null );
  39028. /**
  39029. * The uniform buffer node.
  39030. *
  39031. * @type {BufferNode}
  39032. */
  39033. this.nodeUniform = nodeUniform;
  39034. /**
  39035. * The uniform group node.
  39036. *
  39037. * @type {UniformGroupNode}
  39038. */
  39039. this.groupNode = groupNode;
  39040. }
  39041. /**
  39042. * The uniform buffer.
  39043. *
  39044. * @type {Float32Array}
  39045. */
  39046. get buffer() {
  39047. return this.nodeUniform.value;
  39048. }
  39049. }
  39050. /**
  39051. * This class represents a uniform buffer binding but with
  39052. * an API that allows to maintain individual uniform objects.
  39053. *
  39054. * @private
  39055. * @augments UniformBuffer
  39056. */
  39057. class UniformsGroup extends UniformBuffer {
  39058. /**
  39059. * Constructs a new uniforms group.
  39060. *
  39061. * @param {string} name - The group's name.
  39062. */
  39063. constructor( name ) {
  39064. super( name );
  39065. /**
  39066. * This flag can be used for type testing.
  39067. *
  39068. * @type {boolean}
  39069. * @readonly
  39070. * @default true
  39071. */
  39072. this.isUniformsGroup = true;
  39073. /**
  39074. * An array with the raw uniform values.
  39075. *
  39076. * @private
  39077. * @type {?Array<number>}
  39078. * @default null
  39079. */
  39080. this._values = null;
  39081. /**
  39082. * An array of uniform objects.
  39083. *
  39084. * The order of uniforms in this array must match the order of uniforms in the shader.
  39085. *
  39086. * @type {Array<Uniform>}
  39087. */
  39088. this.uniforms = [];
  39089. }
  39090. /**
  39091. * Adds a uniform to this group.
  39092. *
  39093. * @param {Uniform} uniform - The uniform to add.
  39094. * @return {UniformsGroup} A reference to this group.
  39095. */
  39096. addUniform( uniform ) {
  39097. this.uniforms.push( uniform );
  39098. return this;
  39099. }
  39100. /**
  39101. * Removes a uniform from this group.
  39102. *
  39103. * @param {Uniform} uniform - The uniform to remove.
  39104. * @return {UniformsGroup} A reference to this group.
  39105. */
  39106. removeUniform( uniform ) {
  39107. const index = this.uniforms.indexOf( uniform );
  39108. if ( index !== -1 ) {
  39109. this.uniforms.splice( index, 1 );
  39110. }
  39111. return this;
  39112. }
  39113. /**
  39114. * An array with the raw uniform values.
  39115. *
  39116. * @type {Array<number>}
  39117. */
  39118. get values() {
  39119. if ( this._values === null ) {
  39120. this._values = Array.from( this.buffer );
  39121. }
  39122. return this._values;
  39123. }
  39124. /**
  39125. * A Float32 array buffer with the uniform values.
  39126. *
  39127. * @type {Float32Array}
  39128. */
  39129. get buffer() {
  39130. let buffer = this._buffer;
  39131. if ( buffer === null ) {
  39132. const byteLength = this.byteLength;
  39133. buffer = new Float32Array( new ArrayBuffer( byteLength ) );
  39134. this._buffer = buffer;
  39135. }
  39136. return buffer;
  39137. }
  39138. /**
  39139. * The byte length of the buffer with correct buffer alignment.
  39140. *
  39141. * @type {number}
  39142. */
  39143. get byteLength() {
  39144. const bytesPerElement = this.bytesPerElement;
  39145. let offset = 0; // global buffer offset in bytes
  39146. for ( let i = 0, l = this.uniforms.length; i < l; i ++ ) {
  39147. const uniform = this.uniforms[ i ];
  39148. const boundary = uniform.boundary;
  39149. const itemSize = uniform.itemSize * bytesPerElement; // size of the uniform in bytes
  39150. const chunkOffset = offset % GPU_CHUNK_BYTES; // offset in the current chunk
  39151. const chunkPadding = chunkOffset % boundary; // required padding to match boundary
  39152. const chunkStart = chunkOffset + chunkPadding; // start position in the current chunk for the data
  39153. offset += chunkPadding;
  39154. // Check for chunk overflow
  39155. if ( chunkStart !== 0 && ( GPU_CHUNK_BYTES - chunkStart ) < itemSize ) {
  39156. // Add padding to the end of the chunk
  39157. offset += ( GPU_CHUNK_BYTES - chunkStart );
  39158. }
  39159. uniform.offset = offset / bytesPerElement;
  39160. offset += itemSize;
  39161. }
  39162. return Math.ceil( offset / GPU_CHUNK_BYTES ) * GPU_CHUNK_BYTES;
  39163. }
  39164. /**
  39165. * Updates this group by updating each uniform object of
  39166. * the internal uniform list. The uniform objects check if their
  39167. * values has actually changed so this method only returns
  39168. * `true` if there is a real value change.
  39169. *
  39170. * @return {boolean} Whether the uniforms have been updated and
  39171. * must be uploaded to the GPU.
  39172. */
  39173. update() {
  39174. let updated = false;
  39175. for ( const uniform of this.uniforms ) {
  39176. if ( this.updateByType( uniform ) === true ) {
  39177. updated = true;
  39178. }
  39179. }
  39180. return updated;
  39181. }
  39182. /**
  39183. * Updates a given uniform by calling an update method matching
  39184. * the uniforms type.
  39185. *
  39186. * @param {Uniform} uniform - The uniform to update.
  39187. * @return {boolean} Whether the uniform has been updated or not.
  39188. */
  39189. updateByType( uniform ) {
  39190. if ( uniform.isNumberUniform ) return this.updateNumber( uniform );
  39191. if ( uniform.isVector2Uniform ) return this.updateVector2( uniform );
  39192. if ( uniform.isVector3Uniform ) return this.updateVector3( uniform );
  39193. if ( uniform.isVector4Uniform ) return this.updateVector4( uniform );
  39194. if ( uniform.isColorUniform ) return this.updateColor( uniform );
  39195. if ( uniform.isMatrix3Uniform ) return this.updateMatrix3( uniform );
  39196. if ( uniform.isMatrix4Uniform ) return this.updateMatrix4( uniform );
  39197. console.error( 'THREE.WebGPUUniformsGroup: Unsupported uniform type.', uniform );
  39198. }
  39199. /**
  39200. * Updates a given Number uniform.
  39201. *
  39202. * @param {NumberUniform} uniform - The Number uniform.
  39203. * @return {boolean} Whether the uniform has been updated or not.
  39204. */
  39205. updateNumber( uniform ) {
  39206. let updated = false;
  39207. const a = this.values;
  39208. const v = uniform.getValue();
  39209. const offset = uniform.offset;
  39210. const type = uniform.getType();
  39211. if ( a[ offset ] !== v ) {
  39212. const b = this._getBufferForType( type );
  39213. b[ offset ] = a[ offset ] = v;
  39214. updated = true;
  39215. }
  39216. return updated;
  39217. }
  39218. /**
  39219. * Updates a given Vector2 uniform.
  39220. *
  39221. * @param {Vector2Uniform} uniform - The Vector2 uniform.
  39222. * @return {boolean} Whether the uniform has been updated or not.
  39223. */
  39224. updateVector2( uniform ) {
  39225. let updated = false;
  39226. const a = this.values;
  39227. const v = uniform.getValue();
  39228. const offset = uniform.offset;
  39229. const type = uniform.getType();
  39230. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y ) {
  39231. const b = this._getBufferForType( type );
  39232. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39233. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39234. updated = true;
  39235. }
  39236. return updated;
  39237. }
  39238. /**
  39239. * Updates a given Vector3 uniform.
  39240. *
  39241. * @param {Vector3Uniform} uniform - The Vector3 uniform.
  39242. * @return {boolean} Whether the uniform has been updated or not.
  39243. */
  39244. updateVector3( uniform ) {
  39245. let updated = false;
  39246. const a = this.values;
  39247. const v = uniform.getValue();
  39248. const offset = uniform.offset;
  39249. const type = uniform.getType();
  39250. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z ) {
  39251. const b = this._getBufferForType( type );
  39252. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39253. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39254. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  39255. updated = true;
  39256. }
  39257. return updated;
  39258. }
  39259. /**
  39260. * Updates a given Vector4 uniform.
  39261. *
  39262. * @param {Vector4Uniform} uniform - The Vector4 uniform.
  39263. * @return {boolean} Whether the uniform has been updated or not.
  39264. */
  39265. updateVector4( uniform ) {
  39266. let updated = false;
  39267. const a = this.values;
  39268. const v = uniform.getValue();
  39269. const offset = uniform.offset;
  39270. const type = uniform.getType();
  39271. if ( a[ offset + 0 ] !== v.x || a[ offset + 1 ] !== v.y || a[ offset + 2 ] !== v.z || a[ offset + 4 ] !== v.w ) {
  39272. const b = this._getBufferForType( type );
  39273. b[ offset + 0 ] = a[ offset + 0 ] = v.x;
  39274. b[ offset + 1 ] = a[ offset + 1 ] = v.y;
  39275. b[ offset + 2 ] = a[ offset + 2 ] = v.z;
  39276. b[ offset + 3 ] = a[ offset + 3 ] = v.w;
  39277. updated = true;
  39278. }
  39279. return updated;
  39280. }
  39281. /**
  39282. * Updates a given Color uniform.
  39283. *
  39284. * @param {ColorUniform} uniform - The Color uniform.
  39285. * @return {boolean} Whether the uniform has been updated or not.
  39286. */
  39287. updateColor( uniform ) {
  39288. let updated = false;
  39289. const a = this.values;
  39290. const c = uniform.getValue();
  39291. const offset = uniform.offset;
  39292. if ( a[ offset + 0 ] !== c.r || a[ offset + 1 ] !== c.g || a[ offset + 2 ] !== c.b ) {
  39293. const b = this.buffer;
  39294. b[ offset + 0 ] = a[ offset + 0 ] = c.r;
  39295. b[ offset + 1 ] = a[ offset + 1 ] = c.g;
  39296. b[ offset + 2 ] = a[ offset + 2 ] = c.b;
  39297. updated = true;
  39298. }
  39299. return updated;
  39300. }
  39301. /**
  39302. * Updates a given Matrix3 uniform.
  39303. *
  39304. * @param {Matrix3Uniform} uniform - The Matrix3 uniform.
  39305. * @return {boolean} Whether the uniform has been updated or not.
  39306. */
  39307. updateMatrix3( uniform ) {
  39308. let updated = false;
  39309. const a = this.values;
  39310. const e = uniform.getValue().elements;
  39311. const offset = uniform.offset;
  39312. if ( a[ offset + 0 ] !== e[ 0 ] || a[ offset + 1 ] !== e[ 1 ] || a[ offset + 2 ] !== e[ 2 ] ||
  39313. a[ offset + 4 ] !== e[ 3 ] || a[ offset + 5 ] !== e[ 4 ] || a[ offset + 6 ] !== e[ 5 ] ||
  39314. a[ offset + 8 ] !== e[ 6 ] || a[ offset + 9 ] !== e[ 7 ] || a[ offset + 10 ] !== e[ 8 ] ) {
  39315. const b = this.buffer;
  39316. b[ offset + 0 ] = a[ offset + 0 ] = e[ 0 ];
  39317. b[ offset + 1 ] = a[ offset + 1 ] = e[ 1 ];
  39318. b[ offset + 2 ] = a[ offset + 2 ] = e[ 2 ];
  39319. b[ offset + 4 ] = a[ offset + 4 ] = e[ 3 ];
  39320. b[ offset + 5 ] = a[ offset + 5 ] = e[ 4 ];
  39321. b[ offset + 6 ] = a[ offset + 6 ] = e[ 5 ];
  39322. b[ offset + 8 ] = a[ offset + 8 ] = e[ 6 ];
  39323. b[ offset + 9 ] = a[ offset + 9 ] = e[ 7 ];
  39324. b[ offset + 10 ] = a[ offset + 10 ] = e[ 8 ];
  39325. updated = true;
  39326. }
  39327. return updated;
  39328. }
  39329. /**
  39330. * Updates a given Matrix4 uniform.
  39331. *
  39332. * @param {Matrix4Uniform} uniform - The Matrix4 uniform.
  39333. * @return {boolean} Whether the uniform has been updated or not.
  39334. */
  39335. updateMatrix4( uniform ) {
  39336. let updated = false;
  39337. const a = this.values;
  39338. const e = uniform.getValue().elements;
  39339. const offset = uniform.offset;
  39340. if ( arraysEqual( a, e, offset ) === false ) {
  39341. const b = this.buffer;
  39342. b.set( e, offset );
  39343. setArray( a, e, offset );
  39344. updated = true;
  39345. }
  39346. return updated;
  39347. }
  39348. /**
  39349. * Returns a typed array that matches the given data type.
  39350. *
  39351. * @param {string} type - The data type.
  39352. * @return {TypedArray} The typed array.
  39353. */
  39354. _getBufferForType( type ) {
  39355. if ( type === 'int' || type === 'ivec2' || type === 'ivec3' || type === 'ivec4' ) return new Int32Array( this.buffer.buffer );
  39356. if ( type === 'uint' || type === 'uvec2' || type === 'uvec3' || type === 'uvec4' ) return new Uint32Array( this.buffer.buffer );
  39357. return this.buffer;
  39358. }
  39359. }
  39360. /**
  39361. * Sets the values of the second array to the first array.
  39362. *
  39363. * @private
  39364. * @param {TypedArray} a - The first array.
  39365. * @param {TypedArray} b - The second array.
  39366. * @param {number} offset - An index offset for the first array.
  39367. */
  39368. function setArray( a, b, offset ) {
  39369. for ( let i = 0, l = b.length; i < l; i ++ ) {
  39370. a[ offset + i ] = b[ i ];
  39371. }
  39372. }
  39373. /**
  39374. * Returns `true` if the given arrays are equal.
  39375. *
  39376. * @private
  39377. * @param {TypedArray} a - The first array.
  39378. * @param {TypedArray} b - The second array.
  39379. * @param {number} offset - An index offset for the first array.
  39380. * @return {boolean} Whether the given arrays are equal or not.
  39381. */
  39382. function arraysEqual( a, b, offset ) {
  39383. for ( let i = 0, l = b.length; i < l; i ++ ) {
  39384. if ( a[ offset + i ] !== b[ i ] ) return false;
  39385. }
  39386. return true;
  39387. }
  39388. let _id$3 = 0;
  39389. /**
  39390. * A special form of uniforms group that represents
  39391. * the individual uniforms as node-based uniforms.
  39392. *
  39393. * @private
  39394. * @augments UniformsGroup
  39395. */
  39396. class NodeUniformsGroup extends UniformsGroup {
  39397. /**
  39398. * Constructs a new node-based uniforms group.
  39399. *
  39400. * @param {string} name - The group's name.
  39401. * @param {UniformGroupNode} groupNode - The uniform group node.
  39402. */
  39403. constructor( name, groupNode ) {
  39404. super( name );
  39405. /**
  39406. * The group's ID.
  39407. *
  39408. * @type {number}
  39409. */
  39410. this.id = _id$3 ++;
  39411. /**
  39412. * The uniform group node.
  39413. *
  39414. * @type {UniformGroupNode}
  39415. */
  39416. this.groupNode = groupNode;
  39417. /**
  39418. * This flag can be used for type testing.
  39419. *
  39420. * @type {boolean}
  39421. * @readonly
  39422. * @default true
  39423. */
  39424. this.isNodeUniformsGroup = true;
  39425. }
  39426. }
  39427. let _id$2 = 0;
  39428. /**
  39429. * Represents a sampled texture binding type.
  39430. *
  39431. * @private
  39432. * @augments Binding
  39433. */
  39434. class SampledTexture extends Binding {
  39435. /**
  39436. * Constructs a new sampled texture.
  39437. *
  39438. * @param {string} name - The sampled texture's name.
  39439. * @param {?Texture} texture - The texture this binding is referring to.
  39440. */
  39441. constructor( name, texture ) {
  39442. super( name );
  39443. /**
  39444. * This identifier.
  39445. *
  39446. * @type {number}
  39447. */
  39448. this.id = _id$2 ++;
  39449. /**
  39450. * The texture this binding is referring to.
  39451. *
  39452. * @type {?Texture}
  39453. */
  39454. this.texture = texture;
  39455. /**
  39456. * The binding's version.
  39457. *
  39458. * @type {number}
  39459. */
  39460. this.version = texture ? texture.version : 0;
  39461. /**
  39462. * Whether the texture is a storage texture or not.
  39463. *
  39464. * @type {boolean}
  39465. * @default false
  39466. */
  39467. this.store = false;
  39468. /**
  39469. * The binding's generation which is an additional version
  39470. * qualifier.
  39471. *
  39472. * @type {?number}
  39473. * @default null
  39474. */
  39475. this.generation = null;
  39476. /**
  39477. * This flag can be used for type testing.
  39478. *
  39479. * @type {boolean}
  39480. * @readonly
  39481. * @default true
  39482. */
  39483. this.isSampledTexture = true;
  39484. }
  39485. /**
  39486. * Returns `true` whether this binding requires an update for the
  39487. * given generation.
  39488. *
  39489. * @param {number} generation - The generation.
  39490. * @return {boolean} Whether an update is required or not.
  39491. */
  39492. needsBindingsUpdate( generation ) {
  39493. const { texture } = this;
  39494. if ( generation !== this.generation ) {
  39495. this.generation = generation;
  39496. return true;
  39497. }
  39498. return texture.isVideoTexture;
  39499. }
  39500. /**
  39501. * Updates the binding.
  39502. *
  39503. * @return {boolean} Whether the texture has been updated and must be
  39504. * uploaded to the GPU.
  39505. */
  39506. update() {
  39507. const { texture, version } = this;
  39508. if ( version !== texture.version ) {
  39509. this.version = texture.version;
  39510. return true;
  39511. }
  39512. return false;
  39513. }
  39514. }
  39515. /**
  39516. * A special form of sampled texture binding type.
  39517. * It's texture value is managed by a node object.
  39518. *
  39519. * @private
  39520. * @augments SampledTexture
  39521. */
  39522. class NodeSampledTexture extends SampledTexture {
  39523. /**
  39524. * Constructs a new node-based sampled texture.
  39525. *
  39526. * @param {string} name - The textures's name.
  39527. * @param {TextureNode} textureNode - The texture node.
  39528. * @param {UniformGroupNode} groupNode - The uniform group node.
  39529. * @param {?string} [access=null] - The access type.
  39530. */
  39531. constructor( name, textureNode, groupNode, access = null ) {
  39532. super( name, textureNode ? textureNode.value : null );
  39533. /**
  39534. * The texture node.
  39535. *
  39536. * @type {TextureNode}
  39537. */
  39538. this.textureNode = textureNode;
  39539. /**
  39540. * The uniform group node.
  39541. *
  39542. * @type {UniformGroupNode}
  39543. */
  39544. this.groupNode = groupNode;
  39545. /**
  39546. * The access type.
  39547. *
  39548. * @type {?string}
  39549. * @default null
  39550. */
  39551. this.access = access;
  39552. }
  39553. /**
  39554. * Overwrites the default to additionally check if the node value has changed.
  39555. *
  39556. * @param {number} generation - The generation.
  39557. * @return {boolean} Whether an update is required or not.
  39558. */
  39559. needsBindingsUpdate( generation ) {
  39560. return this.textureNode.value !== this.texture || super.needsBindingsUpdate( generation );
  39561. }
  39562. /**
  39563. * Updates the binding.
  39564. *
  39565. * @return {boolean} Whether the texture has been updated and must be
  39566. * uploaded to the GPU.
  39567. */
  39568. update() {
  39569. const { textureNode } = this;
  39570. if ( this.texture !== textureNode.value ) {
  39571. this.texture = textureNode.value;
  39572. return true;
  39573. }
  39574. return super.update();
  39575. }
  39576. }
  39577. /**
  39578. * A special form of sampled cube texture binding type.
  39579. * It's texture value is managed by a node object.
  39580. *
  39581. * @private
  39582. * @augments NodeSampledTexture
  39583. */
  39584. class NodeSampledCubeTexture extends NodeSampledTexture {
  39585. /**
  39586. * Constructs a new node-based sampled cube texture.
  39587. *
  39588. * @param {string} name - The textures's name.
  39589. * @param {TextureNode} textureNode - The texture node.
  39590. * @param {UniformGroupNode} groupNode - The uniform group node.
  39591. * @param {?string} [access=null] - The access type.
  39592. */
  39593. constructor( name, textureNode, groupNode, access = null ) {
  39594. super( name, textureNode, groupNode, access );
  39595. /**
  39596. * This flag can be used for type testing.
  39597. *
  39598. * @type {boolean}
  39599. * @readonly
  39600. * @default true
  39601. */
  39602. this.isSampledCubeTexture = true;
  39603. }
  39604. }
  39605. /**
  39606. * A special form of sampled 3D texture binding type.
  39607. * It's texture value is managed by a node object.
  39608. *
  39609. * @private
  39610. * @augments NodeSampledTexture
  39611. */
  39612. class NodeSampledTexture3D extends NodeSampledTexture {
  39613. /**
  39614. * Constructs a new node-based sampled 3D texture.
  39615. *
  39616. * @param {string} name - The textures's name.
  39617. * @param {TextureNode} textureNode - The texture node.
  39618. * @param {UniformGroupNode} groupNode - The uniform group node.
  39619. * @param {?string} [access=null] - The access type.
  39620. */
  39621. constructor( name, textureNode, groupNode, access = null ) {
  39622. super( name, textureNode, groupNode, access );
  39623. /**
  39624. * This flag can be used for type testing.
  39625. *
  39626. * @type {boolean}
  39627. * @readonly
  39628. * @default true
  39629. */
  39630. this.isSampledTexture3D = true;
  39631. }
  39632. }
  39633. const glslMethods = {
  39634. textureDimensions: 'textureSize',
  39635. equals: 'equal'
  39636. };
  39637. const precisionLib = {
  39638. low: 'lowp',
  39639. medium: 'mediump',
  39640. high: 'highp'
  39641. };
  39642. const supports$1 = {
  39643. swizzleAssign: true,
  39644. storageBuffer: false
  39645. };
  39646. const interpolationTypeMap = {
  39647. perspective: 'smooth',
  39648. linear: 'noperspective'
  39649. };
  39650. const interpolationModeMap = {
  39651. 'centroid': 'centroid'
  39652. };
  39653. const defaultPrecisions = `
  39654. precision highp float;
  39655. precision highp int;
  39656. precision highp sampler2D;
  39657. precision highp sampler3D;
  39658. precision highp samplerCube;
  39659. precision highp sampler2DArray;
  39660. precision highp usampler2D;
  39661. precision highp usampler3D;
  39662. precision highp usamplerCube;
  39663. precision highp usampler2DArray;
  39664. precision highp isampler2D;
  39665. precision highp isampler3D;
  39666. precision highp isamplerCube;
  39667. precision highp isampler2DArray;
  39668. precision lowp sampler2DShadow;
  39669. precision lowp sampler2DArrayShadow;
  39670. precision lowp samplerCubeShadow;
  39671. `;
  39672. /**
  39673. * A node builder targeting GLSL.
  39674. *
  39675. * This module generates GLSL shader code from node materials and also
  39676. * generates the respective bindings and vertex buffer definitions. These
  39677. * data are later used by the renderer to create render and compute pipelines
  39678. * for render objects.
  39679. *
  39680. * @augments NodeBuilder
  39681. */
  39682. class GLSLNodeBuilder extends NodeBuilder {
  39683. /**
  39684. * Constructs a new GLSL node builder renderer.
  39685. *
  39686. * @param {Object3D} object - The 3D object.
  39687. * @param {Renderer} renderer - The renderer.
  39688. */
  39689. constructor( object, renderer ) {
  39690. super( object, renderer, new GLSLNodeParser() );
  39691. /**
  39692. * A dictionary holds for each shader stage ('vertex', 'fragment', 'compute')
  39693. * another dictionary which manages UBOs per group ('render','frame','object').
  39694. *
  39695. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  39696. */
  39697. this.uniformGroups = {};
  39698. /**
  39699. * An array that holds objects defining the varying and attribute data in
  39700. * context of Transform Feedback.
  39701. *
  39702. * @type {Array<Object<string,AttributeNode|string>>}
  39703. */
  39704. this.transforms = [];
  39705. /**
  39706. * A dictionary that holds for each shader stage a Map of used extensions.
  39707. *
  39708. * @type {Object<string,Map<string,Object>>}
  39709. */
  39710. this.extensions = {};
  39711. /**
  39712. * A dictionary that holds for each shader stage an Array of used builtins.
  39713. *
  39714. * @type {Object<string,Array<string>>}
  39715. */
  39716. this.builtins = { vertex: [], fragment: [], compute: [] };
  39717. }
  39718. /**
  39719. * Checks if the given texture requires a manual conversion to the working color space.
  39720. *
  39721. * @param {Texture} texture - The texture to check.
  39722. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  39723. */
  39724. needsToWorkingColorSpace( texture ) {
  39725. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  39726. }
  39727. /**
  39728. * Returns the native shader method name for a given generic name.
  39729. *
  39730. * @param {string} method - The method name to resolve.
  39731. * @return {string} The resolved GLSL method name.
  39732. */
  39733. getMethod( method ) {
  39734. return glslMethods[ method ] || method;
  39735. }
  39736. /**
  39737. * Returns the output struct name. Not relevant for GLSL.
  39738. *
  39739. * @return {string}
  39740. */
  39741. getOutputStructName() {
  39742. return '';
  39743. }
  39744. /**
  39745. * Builds the given shader node.
  39746. *
  39747. * @param {ShaderNodeInternal} shaderNode - The shader node.
  39748. * @return {string} The GLSL function code.
  39749. */
  39750. buildFunctionCode( shaderNode ) {
  39751. const layout = shaderNode.layout;
  39752. const flowData = this.flowShaderNode( shaderNode );
  39753. const parameters = [];
  39754. for ( const input of layout.inputs ) {
  39755. parameters.push( this.getType( input.type ) + ' ' + input.name );
  39756. }
  39757. //
  39758. const code = `${ this.getType( layout.type ) } ${ layout.name }( ${ parameters.join( ', ' ) } ) {
  39759. ${ flowData.vars }
  39760. ${ flowData.code }
  39761. return ${ flowData.result };
  39762. }`;
  39763. //
  39764. return code;
  39765. }
  39766. /**
  39767. * Setups the Pixel Buffer Object (PBO) for the given storage
  39768. * buffer node.
  39769. *
  39770. * @param {StorageBufferNode} storageBufferNode - The storage buffer node.
  39771. */
  39772. setupPBO( storageBufferNode ) {
  39773. const attribute = storageBufferNode.value;
  39774. if ( attribute.pbo === undefined ) {
  39775. const originalArray = attribute.array;
  39776. const numElements = attribute.count * attribute.itemSize;
  39777. const { itemSize } = attribute;
  39778. const isInteger = attribute.array.constructor.name.toLowerCase().includes( 'int' );
  39779. let format = isInteger ? RedIntegerFormat : RedFormat;
  39780. if ( itemSize === 2 ) {
  39781. format = isInteger ? RGIntegerFormat : RGFormat;
  39782. } else if ( itemSize === 3 ) {
  39783. format = isInteger ? RGBIntegerFormat : RGBFormat;
  39784. } else if ( itemSize === 4 ) {
  39785. format = isInteger ? RGBAIntegerFormat : RGBAFormat;
  39786. }
  39787. const typeMap = {
  39788. Float32Array: FloatType,
  39789. Uint8Array: UnsignedByteType,
  39790. Uint16Array: UnsignedShortType,
  39791. Uint32Array: UnsignedIntType,
  39792. Int8Array: ByteType,
  39793. Int16Array: ShortType,
  39794. Int32Array: IntType,
  39795. Uint8ClampedArray: UnsignedByteType,
  39796. };
  39797. const width = Math.pow( 2, Math.ceil( Math.log2( Math.sqrt( numElements / itemSize ) ) ) );
  39798. let height = Math.ceil( ( numElements / itemSize ) / width );
  39799. if ( width * height * itemSize < numElements ) height ++; // Ensure enough space
  39800. const newSize = width * height * itemSize;
  39801. const newArray = new originalArray.constructor( newSize );
  39802. newArray.set( originalArray, 0 );
  39803. attribute.array = newArray;
  39804. const pboTexture = new DataTexture( attribute.array, width, height, format, typeMap[ attribute.array.constructor.name ] || FloatType );
  39805. pboTexture.needsUpdate = true;
  39806. pboTexture.isPBOTexture = true;
  39807. const pbo = new TextureNode( pboTexture, null, null );
  39808. pbo.setPrecision( 'high' );
  39809. attribute.pboNode = pbo;
  39810. attribute.pbo = pbo.value;
  39811. this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  39812. }
  39813. }
  39814. /**
  39815. * Returns a GLSL snippet that represents the property name of the given node.
  39816. *
  39817. * @param {Node} node - The node.
  39818. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  39819. * @return {string} The property name.
  39820. */
  39821. getPropertyName( node, shaderStage = this.shaderStage ) {
  39822. if ( node.isNodeUniform && node.node.isTextureNode !== true && node.node.isBufferNode !== true ) {
  39823. return shaderStage.charAt( 0 ) + '_' + node.name;
  39824. }
  39825. return super.getPropertyName( node, shaderStage );
  39826. }
  39827. /**
  39828. * Setups the Pixel Buffer Object (PBO) for the given storage
  39829. * buffer node.
  39830. *
  39831. * @param {StorageArrayElementNode} storageArrayElementNode - The storage array element node.
  39832. * @return {string} The property name.
  39833. */
  39834. generatePBO( storageArrayElementNode ) {
  39835. const { node, indexNode } = storageArrayElementNode;
  39836. const attribute = node.value;
  39837. if ( this.renderer.backend.has( attribute ) ) {
  39838. const attributeData = this.renderer.backend.get( attribute );
  39839. attributeData.pbo = attribute.pbo;
  39840. }
  39841. const nodeUniform = this.getUniformFromNode( attribute.pboNode, 'texture', this.shaderStage, this.context.label );
  39842. const textureName = this.getPropertyName( nodeUniform );
  39843. this.increaseUsage( indexNode ); // force cache generate to be used as index in x,y
  39844. const indexSnippet = indexNode.build( this, 'uint' );
  39845. const elementNodeData = this.getDataFromNode( storageArrayElementNode );
  39846. let propertyName = elementNodeData.propertyName;
  39847. if ( propertyName === undefined ) {
  39848. // property element
  39849. const nodeVar = this.getVarFromNode( storageArrayElementNode );
  39850. propertyName = this.getPropertyName( nodeVar );
  39851. // property size
  39852. const bufferNodeData = this.getDataFromNode( node );
  39853. let propertySizeName = bufferNodeData.propertySizeName;
  39854. if ( propertySizeName === undefined ) {
  39855. propertySizeName = propertyName + 'Size';
  39856. this.getVarFromNode( node, propertySizeName, 'uint' );
  39857. this.addLineFlowCode( `${ propertySizeName } = uint( textureSize( ${ textureName }, 0 ).x )`, storageArrayElementNode );
  39858. bufferNodeData.propertySizeName = propertySizeName;
  39859. }
  39860. //
  39861. const { itemSize } = attribute;
  39862. const channel = '.' + vectorComponents.join( '' ).slice( 0, itemSize );
  39863. const uvSnippet = `ivec2(${indexSnippet} % ${ propertySizeName }, ${indexSnippet} / ${ propertySizeName })`;
  39864. const snippet = this.generateTextureLoad( null, textureName, uvSnippet, null, '0' );
  39865. //
  39866. let prefix = 'vec4';
  39867. if ( attribute.pbo.type === UnsignedIntType ) {
  39868. prefix = 'uvec4';
  39869. } else if ( attribute.pbo.type === IntType ) {
  39870. prefix = 'ivec4';
  39871. }
  39872. this.addLineFlowCode( `${ propertyName } = ${prefix}(${ snippet })${channel}`, storageArrayElementNode );
  39873. elementNodeData.propertyName = propertyName;
  39874. }
  39875. return propertyName;
  39876. }
  39877. /**
  39878. * Generates the GLSL snippet that reads a single texel from a texture without sampling or filtering.
  39879. *
  39880. * @param {Texture} texture - The texture.
  39881. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39882. * @param {string} uvIndexSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39883. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  39884. * @param {string} [levelSnippet='0u'] - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  39885. * @return {string} The GLSL snippet.
  39886. */
  39887. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0' ) {
  39888. if ( depthSnippet ) {
  39889. return `texelFetch( ${ textureProperty }, ivec3( ${ uvIndexSnippet }, ${ depthSnippet } ), ${ levelSnippet } )`;
  39890. } else {
  39891. return `texelFetch( ${ textureProperty }, ${ uvIndexSnippet }, ${ levelSnippet } )`;
  39892. }
  39893. }
  39894. /**
  39895. * Generates the GLSL snippet for sampling/loading the given texture.
  39896. *
  39897. * @param {Texture} texture - The texture.
  39898. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39899. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39900. * @param {?string} depthSnippet - A GLSL snippet that represents the 0-based texture array index to sample.
  39901. * @return {string} The GLSL snippet.
  39902. */
  39903. generateTexture( texture, textureProperty, uvSnippet, depthSnippet ) {
  39904. if ( texture.isDepthTexture ) {
  39905. if ( depthSnippet ) uvSnippet = `vec4( ${ uvSnippet }, ${ depthSnippet } )`;
  39906. return `texture( ${ textureProperty }, ${ uvSnippet } ).x`;
  39907. } else {
  39908. if ( depthSnippet ) uvSnippet = `vec3( ${ uvSnippet }, ${ depthSnippet } )`;
  39909. return `texture( ${ textureProperty }, ${ uvSnippet } )`;
  39910. }
  39911. }
  39912. /**
  39913. * Generates the GLSL snippet when sampling textures with explicit mip level.
  39914. *
  39915. * @param {Texture} texture - The texture.
  39916. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39917. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39918. * @param {string} levelSnippet - A GLSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  39919. * @return {string} The GLSL snippet.
  39920. */
  39921. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet ) {
  39922. return `textureLod( ${ textureProperty }, ${ uvSnippet }, ${ levelSnippet } )`;
  39923. }
  39924. /**
  39925. * Generates the GLSL snippet when sampling textures with a bias to the mip level.
  39926. *
  39927. * @param {Texture} texture - The texture.
  39928. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39929. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39930. * @param {string} biasSnippet - A GLSL snippet that represents the bias to apply to the mip level before sampling.
  39931. * @return {string} The GLSL snippet.
  39932. */
  39933. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet ) {
  39934. return `texture( ${ textureProperty }, ${ uvSnippet }, ${ biasSnippet } )`;
  39935. }
  39936. /**
  39937. * Generates the GLSL snippet for sampling/loading the given texture using explicit gradients.
  39938. *
  39939. * @param {Texture} texture - The texture.
  39940. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39941. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39942. * @param {Array<string>} gradSnippet - An array holding both gradient GLSL snippets.
  39943. * @return {string} The GLSL snippet.
  39944. */
  39945. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet ) {
  39946. return `textureGrad( ${ textureProperty }, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  39947. }
  39948. /**
  39949. * Generates the GLSL snippet for sampling a depth texture and comparing the sampled depth values
  39950. * against a reference value.
  39951. *
  39952. * @param {Texture} texture - The texture.
  39953. * @param {string} textureProperty - The name of the texture uniform in the shader.
  39954. * @param {string} uvSnippet - A GLSL snippet that represents texture coordinates used for sampling.
  39955. * @param {string} compareSnippet - A GLSL snippet that represents the reference value.
  39956. * @param {?string} depthSnippet - A GLSL snippet that represents 0-based texture array index to sample.
  39957. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  39958. * @return {string} The GLSL snippet.
  39959. */
  39960. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  39961. if ( shaderStage === 'fragment' ) {
  39962. if ( depthSnippet ) {
  39963. return `texture( ${ textureProperty }, vec4( ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } ) )`;
  39964. }
  39965. return `texture( ${ textureProperty }, vec3( ${ uvSnippet }, ${ compareSnippet } ) )`;
  39966. } else {
  39967. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  39968. }
  39969. }
  39970. /**
  39971. * Returns the variables of the given shader stage as a GLSL string.
  39972. *
  39973. * @param {string} shaderStage - The shader stage.
  39974. * @return {string} The GLSL snippet that defines the variables.
  39975. */
  39976. getVars( shaderStage ) {
  39977. const snippets = [];
  39978. const vars = this.vars[ shaderStage ];
  39979. if ( vars !== undefined ) {
  39980. for ( const variable of vars ) {
  39981. snippets.push( `${ this.getVar( variable.type, variable.name, variable.count ) };` );
  39982. }
  39983. }
  39984. return snippets.join( '\n\t' );
  39985. }
  39986. /**
  39987. * Returns the uniforms of the given shader stage as a GLSL string.
  39988. *
  39989. * @param {string} shaderStage - The shader stage.
  39990. * @return {string} The GLSL snippet that defines the uniforms.
  39991. */
  39992. getUniforms( shaderStage ) {
  39993. const uniforms = this.uniforms[ shaderStage ];
  39994. const bindingSnippets = [];
  39995. const uniformGroups = {};
  39996. for ( const uniform of uniforms ) {
  39997. let snippet = null;
  39998. let group = false;
  39999. if ( uniform.type === 'texture' || uniform.type === 'texture3D' ) {
  40000. const texture = uniform.node.value;
  40001. let typePrefix = '';
  40002. if ( texture.isDataTexture === true || texture.isData3DTexture === true ) {
  40003. if ( texture.type === UnsignedIntType ) {
  40004. typePrefix = 'u';
  40005. } else if ( texture.type === IntType ) {
  40006. typePrefix = 'i';
  40007. }
  40008. }
  40009. if ( uniform.type === 'texture3D' && texture.isArrayTexture === false ) {
  40010. snippet = `${typePrefix}sampler3D ${ uniform.name };`;
  40011. } else if ( texture.compareFunction ) {
  40012. if ( texture.isArrayTexture === true ) {
  40013. snippet = `sampler2DArrayShadow ${ uniform.name };`;
  40014. } else {
  40015. snippet = `sampler2DShadow ${ uniform.name };`;
  40016. }
  40017. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  40018. snippet = `${typePrefix}sampler2DArray ${ uniform.name };`;
  40019. } else {
  40020. snippet = `${typePrefix}sampler2D ${ uniform.name };`;
  40021. }
  40022. } else if ( uniform.type === 'cubeTexture' ) {
  40023. snippet = `samplerCube ${ uniform.name };`;
  40024. } else if ( uniform.type === 'buffer' ) {
  40025. const bufferNode = uniform.node;
  40026. const bufferType = this.getType( bufferNode.bufferType );
  40027. const bufferCount = bufferNode.bufferCount;
  40028. const bufferCountSnippet = bufferCount > 0 ? bufferCount : '';
  40029. snippet = `${bufferNode.name} {\n\t${ bufferType } ${ uniform.name }[${ bufferCountSnippet }];\n};\n`;
  40030. } else {
  40031. const vectorType = this.getVectorType( uniform.type );
  40032. snippet = `${ vectorType } ${ this.getPropertyName( uniform, shaderStage ) };`;
  40033. group = true;
  40034. }
  40035. const precision = uniform.node.precision;
  40036. if ( precision !== null ) {
  40037. snippet = precisionLib[ precision ] + ' ' + snippet;
  40038. }
  40039. if ( group ) {
  40040. snippet = '\t' + snippet;
  40041. const groupName = uniform.groupNode.name;
  40042. const groupSnippets = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = [] );
  40043. groupSnippets.push( snippet );
  40044. } else {
  40045. snippet = 'uniform ' + snippet;
  40046. bindingSnippets.push( snippet );
  40047. }
  40048. }
  40049. let output = '';
  40050. for ( const name in uniformGroups ) {
  40051. const groupSnippets = uniformGroups[ name ];
  40052. output += this._getGLSLUniformStruct( shaderStage + '_' + name, groupSnippets.join( '\n' ) ) + '\n';
  40053. }
  40054. output += bindingSnippets.join( '\n' );
  40055. return output;
  40056. }
  40057. /**
  40058. * Returns the type for a given buffer attribute.
  40059. *
  40060. * @param {BufferAttribute} attribute - The buffer attribute.
  40061. * @return {string} The type.
  40062. */
  40063. getTypeFromAttribute( attribute ) {
  40064. let nodeType = super.getTypeFromAttribute( attribute );
  40065. if ( /^[iu]/.test( nodeType ) && attribute.gpuType !== IntType ) {
  40066. let dataAttribute = attribute;
  40067. if ( attribute.isInterleavedBufferAttribute ) dataAttribute = attribute.data;
  40068. const array = dataAttribute.array;
  40069. if ( ( array instanceof Uint32Array || array instanceof Int32Array ) === false ) {
  40070. nodeType = nodeType.slice( 1 );
  40071. }
  40072. }
  40073. return nodeType;
  40074. }
  40075. /**
  40076. * Returns the shader attributes of the given shader stage as a GLSL string.
  40077. *
  40078. * @param {string} shaderStage - The shader stage.
  40079. * @return {string} The GLSL snippet that defines the shader attributes.
  40080. */
  40081. getAttributes( shaderStage ) {
  40082. let snippet = '';
  40083. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  40084. const attributes = this.getAttributesArray();
  40085. let location = 0;
  40086. for ( const attribute of attributes ) {
  40087. snippet += `layout( location = ${ location ++ } ) in ${ attribute.type } ${ attribute.name };\n`;
  40088. }
  40089. }
  40090. return snippet;
  40091. }
  40092. /**
  40093. * Returns the members of the given struct type node as a GLSL string.
  40094. *
  40095. * @param {StructTypeNode} struct - The struct type node.
  40096. * @return {string} The GLSL snippet that defines the struct members.
  40097. */
  40098. getStructMembers( struct ) {
  40099. const snippets = [];
  40100. for ( const member of struct.members ) {
  40101. snippets.push( `\t${ member.type } ${ member.name };` );
  40102. }
  40103. return snippets.join( '\n' );
  40104. }
  40105. /**
  40106. * Returns the structs of the given shader stage as a GLSL string.
  40107. *
  40108. * @param {string} shaderStage - The shader stage.
  40109. * @return {string} The GLSL snippet that defines the structs.
  40110. */
  40111. getStructs( shaderStage ) {
  40112. const snippets = [];
  40113. const structs = this.structs[ shaderStage ];
  40114. const outputSnippet = [];
  40115. for ( const struct of structs ) {
  40116. if ( struct.output ) {
  40117. for ( const member of struct.members ) {
  40118. outputSnippet.push( `layout( location = ${ member.index } ) out ${ member.type } ${ member.name };` );
  40119. }
  40120. } else {
  40121. let snippet = 'struct ' + struct.name + ' {\n';
  40122. snippet += this.getStructMembers( struct );
  40123. snippet += '\n};\n';
  40124. snippets.push( snippet );
  40125. }
  40126. }
  40127. if ( outputSnippet.length === 0 ) {
  40128. outputSnippet.push( 'layout( location = 0 ) out vec4 fragColor;' );
  40129. }
  40130. return '\n' + outputSnippet.join( '\n' ) + '\n\n' + snippets.join( '\n' );
  40131. }
  40132. /**
  40133. * Returns the varyings of the given shader stage as a GLSL string.
  40134. *
  40135. * @param {string} shaderStage - The shader stage.
  40136. * @return {string} The GLSL snippet that defines the varyings.
  40137. */
  40138. getVaryings( shaderStage ) {
  40139. let snippet = '';
  40140. const varyings = this.varyings;
  40141. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  40142. for ( const varying of varyings ) {
  40143. if ( shaderStage === 'compute' ) varying.needsInterpolation = true;
  40144. const type = this.getType( varying.type );
  40145. if ( varying.needsInterpolation ) {
  40146. if ( varying.interpolationType ) {
  40147. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  40148. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  40149. snippet += `${ interpolationType } ${ sampling } out ${ type } ${ varying.name };\n`;
  40150. } else {
  40151. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  40152. snippet += `${ flat }out ${ type } ${ varying.name };\n`;
  40153. }
  40154. } else {
  40155. snippet += `${type} ${varying.name};\n`; // generate variable (no varying required)
  40156. }
  40157. }
  40158. } else if ( shaderStage === 'fragment' ) {
  40159. for ( const varying of varyings ) {
  40160. if ( varying.needsInterpolation ) {
  40161. const type = this.getType( varying.type );
  40162. if ( varying.interpolationType ) {
  40163. const interpolationType = interpolationTypeMap[ varying.interpolationType ] || varying.interpolationType;
  40164. const sampling = interpolationModeMap[ varying.interpolationSampling ] || '';
  40165. snippet += `${ interpolationType } ${ sampling } in ${ type } ${ varying.name };\n`;
  40166. } else {
  40167. const flat = type.includes( 'int' ) || type.includes( 'uv' ) || type.includes( 'iv' ) ? 'flat ' : '';
  40168. snippet += `${ flat }in ${ type } ${ varying.name };\n`;
  40169. }
  40170. }
  40171. }
  40172. }
  40173. for ( const builtin of this.builtins[ shaderStage ] ) {
  40174. snippet += `${builtin};\n`;
  40175. }
  40176. return snippet;
  40177. }
  40178. /**
  40179. * Returns the vertex index builtin.
  40180. *
  40181. * @return {string} The vertex index.
  40182. */
  40183. getVertexIndex() {
  40184. return 'uint( gl_VertexID )';
  40185. }
  40186. /**
  40187. * Returns the instance index builtin.
  40188. *
  40189. * @return {string} The instance index.
  40190. */
  40191. getInstanceIndex() {
  40192. return 'uint( gl_InstanceID )';
  40193. }
  40194. /**
  40195. * Returns the invocation local index builtin.
  40196. *
  40197. * @return {string} The invocation local index.
  40198. */
  40199. getInvocationLocalIndex() {
  40200. const workgroupSize = this.object.workgroupSize;
  40201. const size = workgroupSize.reduce( ( acc, curr ) => acc * curr, 1 );
  40202. return `uint( gl_InstanceID ) % ${size}u`;
  40203. }
  40204. /**
  40205. * Returns the draw index builtin.
  40206. *
  40207. * @return {?string} The drawIndex shader string. Returns `null` if `WEBGL_multi_draw` isn't supported by the device.
  40208. */
  40209. getDrawIndex() {
  40210. const extensions = this.renderer.backend.extensions;
  40211. if ( extensions.has( 'WEBGL_multi_draw' ) ) {
  40212. return 'uint( gl_DrawID )';
  40213. }
  40214. return null;
  40215. }
  40216. /**
  40217. * Returns the front facing builtin.
  40218. *
  40219. * @return {string} The front facing builtin.
  40220. */
  40221. getFrontFacing() {
  40222. return 'gl_FrontFacing';
  40223. }
  40224. /**
  40225. * Returns the frag coord builtin.
  40226. *
  40227. * @return {string} The frag coord builtin.
  40228. */
  40229. getFragCoord() {
  40230. return 'gl_FragCoord.xy';
  40231. }
  40232. /**
  40233. * Returns the frag depth builtin.
  40234. *
  40235. * @return {string} The frag depth builtin.
  40236. */
  40237. getFragDepth() {
  40238. return 'gl_FragDepth';
  40239. }
  40240. /**
  40241. * Enables the given extension.
  40242. *
  40243. * @param {string} name - The extension name.
  40244. * @param {string} behavior - The extension behavior.
  40245. * @param {string} [shaderStage=this.shaderStage] - The shader stage.
  40246. */
  40247. enableExtension( name, behavior, shaderStage = this.shaderStage ) {
  40248. const map = this.extensions[ shaderStage ] || ( this.extensions[ shaderStage ] = new Map() );
  40249. if ( map.has( name ) === false ) {
  40250. map.set( name, {
  40251. name,
  40252. behavior
  40253. } );
  40254. }
  40255. }
  40256. /**
  40257. * Returns the enabled extensions of the given shader stage as a GLSL string.
  40258. *
  40259. * @param {string} shaderStage - The shader stage.
  40260. * @return {string} The GLSL snippet that defines the enabled extensions.
  40261. */
  40262. getExtensions( shaderStage ) {
  40263. const snippets = [];
  40264. if ( shaderStage === 'vertex' ) {
  40265. const ext = this.renderer.backend.extensions;
  40266. const isBatchedMesh = this.object.isBatchedMesh;
  40267. if ( isBatchedMesh && ext.has( 'WEBGL_multi_draw' ) ) {
  40268. this.enableExtension( 'GL_ANGLE_multi_draw', 'require', shaderStage );
  40269. }
  40270. }
  40271. const extensions = this.extensions[ shaderStage ];
  40272. if ( extensions !== undefined ) {
  40273. for ( const { name, behavior } of extensions.values() ) {
  40274. snippets.push( `#extension ${name} : ${behavior}` );
  40275. }
  40276. }
  40277. return snippets.join( '\n' );
  40278. }
  40279. /**
  40280. * Returns the clip distances builtin.
  40281. *
  40282. * @return {string} The clip distances builtin.
  40283. */
  40284. getClipDistance() {
  40285. return 'gl_ClipDistance';
  40286. }
  40287. /**
  40288. * Whether the requested feature is available or not.
  40289. *
  40290. * @param {string} name - The requested feature.
  40291. * @return {boolean} Whether the requested feature is supported or not.
  40292. */
  40293. isAvailable( name ) {
  40294. let result = supports$1[ name ];
  40295. if ( result === undefined ) {
  40296. let extensionName;
  40297. result = false;
  40298. switch ( name ) {
  40299. case 'float32Filterable':
  40300. extensionName = 'OES_texture_float_linear';
  40301. break;
  40302. case 'clipDistance':
  40303. extensionName = 'WEBGL_clip_cull_distance';
  40304. break;
  40305. }
  40306. if ( extensionName !== undefined ) {
  40307. const extensions = this.renderer.backend.extensions;
  40308. if ( extensions.has( extensionName ) ) {
  40309. extensions.get( extensionName );
  40310. result = true;
  40311. }
  40312. }
  40313. supports$1[ name ] = result;
  40314. }
  40315. return result;
  40316. }
  40317. /**
  40318. * Whether to flip texture data along its vertical axis or not.
  40319. *
  40320. * @return {boolean} Returns always `true` in context of GLSL.
  40321. */
  40322. isFlipY() {
  40323. return true;
  40324. }
  40325. /**
  40326. * Enables hardware clipping.
  40327. *
  40328. * @param {string} planeCount - The clipping plane count.
  40329. */
  40330. enableHardwareClipping( planeCount ) {
  40331. this.enableExtension( 'GL_ANGLE_clip_cull_distance', 'require' );
  40332. this.builtins[ 'vertex' ].push( `out float gl_ClipDistance[ ${ planeCount } ]` );
  40333. }
  40334. /**
  40335. * Enables multiview.
  40336. */
  40337. enableMultiview() {
  40338. this.enableExtension( 'GL_OVR_multiview2', 'require', 'fragment' );
  40339. this.enableExtension( 'GL_OVR_multiview2', 'require', 'vertex' );
  40340. this.builtins[ 'vertex' ].push( 'layout(num_views = 2) in' );
  40341. }
  40342. /**
  40343. * Registers a transform in context of Transform Feedback.
  40344. *
  40345. * @param {string} varyingName - The varying name.
  40346. * @param {AttributeNode} attributeNode - The attribute node.
  40347. */
  40348. registerTransform( varyingName, attributeNode ) {
  40349. this.transforms.push( { varyingName, attributeNode } );
  40350. }
  40351. /**
  40352. * Returns the transforms of the given shader stage as a GLSL string.
  40353. *
  40354. * @param {string} shaderStage - The shader stage.
  40355. * @return {string} The GLSL snippet that defines the transforms.
  40356. */
  40357. getTransforms( /* shaderStage */ ) {
  40358. const transforms = this.transforms;
  40359. let snippet = '';
  40360. for ( let i = 0; i < transforms.length; i ++ ) {
  40361. const transform = transforms[ i ];
  40362. const attributeName = this.getPropertyName( transform.attributeNode );
  40363. if ( attributeName ) snippet += `${ transform.varyingName } = ${ attributeName };\n\t`;
  40364. }
  40365. return snippet;
  40366. }
  40367. /**
  40368. * Returns a GLSL struct based on the given name and variables.
  40369. *
  40370. * @private
  40371. * @param {string} name - The struct name.
  40372. * @param {string} vars - The struct variables.
  40373. * @return {string} The GLSL snippet representing a struct.
  40374. */
  40375. _getGLSLUniformStruct( name, vars ) {
  40376. return `
  40377. layout( std140 ) uniform ${name} {
  40378. ${vars}
  40379. };`;
  40380. }
  40381. /**
  40382. * Returns a GLSL vertex shader based on the given shader data.
  40383. *
  40384. * @private
  40385. * @param {Object} shaderData - The shader data.
  40386. * @return {string} The vertex shader.
  40387. */
  40388. _getGLSLVertexCode( shaderData ) {
  40389. return `#version 300 es
  40390. ${ this.getSignature() }
  40391. // extensions
  40392. ${shaderData.extensions}
  40393. // precision
  40394. ${ defaultPrecisions }
  40395. // uniforms
  40396. ${shaderData.uniforms}
  40397. // varyings
  40398. ${shaderData.varyings}
  40399. // attributes
  40400. ${shaderData.attributes}
  40401. // codes
  40402. ${shaderData.codes}
  40403. void main() {
  40404. // vars
  40405. ${shaderData.vars}
  40406. // transforms
  40407. ${shaderData.transforms}
  40408. // flow
  40409. ${shaderData.flow}
  40410. gl_PointSize = 1.0;
  40411. }
  40412. `;
  40413. }
  40414. /**
  40415. * Returns a GLSL fragment shader based on the given shader data.
  40416. *
  40417. * @private
  40418. * @param {Object} shaderData - The shader data.
  40419. * @return {string} The vertex shader.
  40420. */
  40421. _getGLSLFragmentCode( shaderData ) {
  40422. return `#version 300 es
  40423. ${ this.getSignature() }
  40424. // extensions
  40425. ${shaderData.extensions}
  40426. // precision
  40427. ${ defaultPrecisions }
  40428. // uniforms
  40429. ${shaderData.uniforms}
  40430. // varyings
  40431. ${shaderData.varyings}
  40432. // codes
  40433. ${shaderData.codes}
  40434. // structs
  40435. ${shaderData.structs}
  40436. void main() {
  40437. // vars
  40438. ${shaderData.vars}
  40439. // flow
  40440. ${shaderData.flow}
  40441. }
  40442. `;
  40443. }
  40444. /**
  40445. * Controls the code build of the shader stages.
  40446. */
  40447. buildCode() {
  40448. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  40449. this.sortBindingGroups();
  40450. for ( const shaderStage in shadersData ) {
  40451. let flow = '// code\n\n';
  40452. flow += this.flowCode[ shaderStage ];
  40453. const flowNodes = this.flowNodes[ shaderStage ];
  40454. const mainNode = flowNodes[ flowNodes.length - 1 ];
  40455. for ( const node of flowNodes ) {
  40456. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  40457. const slotName = node.name;
  40458. if ( slotName ) {
  40459. if ( flow.length > 0 ) flow += '\n';
  40460. flow += `\t// flow -> ${ slotName }\n\t`;
  40461. }
  40462. flow += `${ flowSlotData.code }\n\t`;
  40463. if ( node === mainNode && shaderStage !== 'compute' ) {
  40464. flow += '// result\n\t';
  40465. if ( shaderStage === 'vertex' ) {
  40466. flow += 'gl_Position = ';
  40467. flow += `${ flowSlotData.result };`;
  40468. } else if ( shaderStage === 'fragment' ) {
  40469. if ( ! node.outputNode.isOutputStructNode ) {
  40470. flow += 'fragColor = ';
  40471. flow += `${ flowSlotData.result };`;
  40472. }
  40473. }
  40474. }
  40475. }
  40476. const stageData = shadersData[ shaderStage ];
  40477. stageData.extensions = this.getExtensions( shaderStage );
  40478. stageData.uniforms = this.getUniforms( shaderStage );
  40479. stageData.attributes = this.getAttributes( shaderStage );
  40480. stageData.varyings = this.getVaryings( shaderStage );
  40481. stageData.vars = this.getVars( shaderStage );
  40482. stageData.structs = this.getStructs( shaderStage );
  40483. stageData.codes = this.getCodes( shaderStage );
  40484. stageData.transforms = this.getTransforms( shaderStage );
  40485. stageData.flow = flow;
  40486. }
  40487. if ( this.material !== null ) {
  40488. this.vertexShader = this._getGLSLVertexCode( shadersData.vertex );
  40489. this.fragmentShader = this._getGLSLFragmentCode( shadersData.fragment );
  40490. } else {
  40491. this.computeShader = this._getGLSLVertexCode( shadersData.compute );
  40492. }
  40493. }
  40494. /**
  40495. * This method is one of the more important ones since it's responsible
  40496. * for generating a matching binding instance for the given uniform node.
  40497. *
  40498. * These bindings are later used in the renderer to create bind groups
  40499. * and layouts.
  40500. *
  40501. * @param {UniformNode} node - The uniform node.
  40502. * @param {string} type - The node data type.
  40503. * @param {string} shaderStage - The shader stage.
  40504. * @param {?string} [name=null] - An optional uniform name.
  40505. * @return {NodeUniform} The node uniform object.
  40506. */
  40507. getUniformFromNode( node, type, shaderStage, name = null ) {
  40508. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  40509. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  40510. let uniformGPU = nodeData.uniformGPU;
  40511. if ( uniformGPU === undefined ) {
  40512. const group = node.groupNode;
  40513. const groupName = group.name;
  40514. const bindings = this.getBindGroupArray( groupName, shaderStage );
  40515. if ( type === 'texture' ) {
  40516. uniformGPU = new NodeSampledTexture( uniformNode.name, uniformNode.node, group );
  40517. bindings.push( uniformGPU );
  40518. } else if ( type === 'cubeTexture' ) {
  40519. uniformGPU = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group );
  40520. bindings.push( uniformGPU );
  40521. } else if ( type === 'texture3D' ) {
  40522. uniformGPU = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group );
  40523. bindings.push( uniformGPU );
  40524. } else if ( type === 'buffer' ) {
  40525. node.name = `NodeBuffer_${ node.id }`;
  40526. uniformNode.name = `buffer${ node.id }`;
  40527. const buffer = new NodeUniformBuffer( node, group );
  40528. buffer.name = node.name;
  40529. bindings.push( buffer );
  40530. uniformGPU = buffer;
  40531. } else {
  40532. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  40533. let uniformsGroup = uniformsStage[ groupName ];
  40534. if ( uniformsGroup === undefined ) {
  40535. uniformsGroup = new NodeUniformsGroup( shaderStage + '_' + groupName, group );
  40536. //uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  40537. uniformsStage[ groupName ] = uniformsGroup;
  40538. bindings.push( uniformsGroup );
  40539. }
  40540. uniformGPU = this.getNodeUniform( uniformNode, type );
  40541. uniformsGroup.addUniform( uniformGPU );
  40542. }
  40543. nodeData.uniformGPU = uniformGPU;
  40544. }
  40545. return uniformNode;
  40546. }
  40547. }
  40548. let _vector2 = null;
  40549. let _color4 = null;
  40550. /**
  40551. * Most of the rendering related logic is implemented in the
  40552. * {@link Renderer} module and related management components.
  40553. * Sometimes it is required though to execute commands which are
  40554. * specific to the current 3D backend (which is WebGPU or WebGL 2).
  40555. * This abstract base class defines an interface that encapsulates
  40556. * all backend-related logic. Derived classes for each backend must
  40557. * implement the interface.
  40558. *
  40559. * @abstract
  40560. * @private
  40561. */
  40562. class Backend {
  40563. /**
  40564. * Constructs a new backend.
  40565. *
  40566. * @param {Object} parameters - An object holding parameters for the backend.
  40567. */
  40568. constructor( parameters = {} ) {
  40569. /**
  40570. * The parameters of the backend.
  40571. *
  40572. * @type {Object}
  40573. */
  40574. this.parameters = Object.assign( {}, parameters );
  40575. /**
  40576. * This weak map holds backend-specific data of objects
  40577. * like textures, attributes or render targets.
  40578. *
  40579. * @type {WeakMap}
  40580. */
  40581. this.data = new WeakMap();
  40582. /**
  40583. * A reference to the renderer.
  40584. *
  40585. * @type {?Renderer}
  40586. * @default null
  40587. */
  40588. this.renderer = null;
  40589. /**
  40590. * A reference to the canvas element the renderer is drawing to.
  40591. *
  40592. * @type {?(HTMLCanvasElement|OffscreenCanvas)}
  40593. * @default null
  40594. */
  40595. this.domElement = null;
  40596. /**
  40597. * A reference to the timestamp query pool.
  40598. *
  40599. * @type {{render: ?TimestampQueryPool, compute: ?TimestampQueryPool}}
  40600. */
  40601. this.timestampQueryPool = {
  40602. 'render': null,
  40603. 'compute': null
  40604. };
  40605. /**
  40606. * Whether to track timestamps with a Timestamp Query API or not.
  40607. *
  40608. * @type {boolean}
  40609. * @default false
  40610. */
  40611. this.trackTimestamp = ( parameters.trackTimestamp === true );
  40612. }
  40613. /**
  40614. * Initializes the backend so it is ready for usage. Concrete backends
  40615. * are supposed to implement their rendering context creation and related
  40616. * operations in this method.
  40617. *
  40618. * @async
  40619. * @param {Renderer} renderer - The renderer.
  40620. * @return {Promise} A Promise that resolves when the backend has been initialized.
  40621. */
  40622. async init( renderer ) {
  40623. this.renderer = renderer;
  40624. }
  40625. /**
  40626. * The coordinate system of the backend.
  40627. *
  40628. * @abstract
  40629. * @type {number}
  40630. * @readonly
  40631. */
  40632. get coordinateSystem() {}
  40633. // render context
  40634. /**
  40635. * This method is executed at the beginning of a render call and
  40636. * can be used by the backend to prepare the state for upcoming
  40637. * draw calls.
  40638. *
  40639. * @abstract
  40640. * @param {RenderContext} renderContext - The render context.
  40641. */
  40642. beginRender( /*renderContext*/ ) {}
  40643. /**
  40644. * This method is executed at the end of a render call and
  40645. * can be used by the backend to finalize work after draw
  40646. * calls.
  40647. *
  40648. * @abstract
  40649. * @param {RenderContext} renderContext - The render context.
  40650. */
  40651. finishRender( /*renderContext*/ ) {}
  40652. /**
  40653. * This method is executed at the beginning of a compute call and
  40654. * can be used by the backend to prepare the state for upcoming
  40655. * compute tasks.
  40656. *
  40657. * @abstract
  40658. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40659. */
  40660. beginCompute( /*computeGroup*/ ) {}
  40661. /**
  40662. * This method is executed at the end of a compute call and
  40663. * can be used by the backend to finalize work after compute
  40664. * tasks.
  40665. *
  40666. * @abstract
  40667. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  40668. */
  40669. finishCompute( /*computeGroup*/ ) {}
  40670. // render object
  40671. /**
  40672. * Executes a draw command for the given render object.
  40673. *
  40674. * @abstract
  40675. * @param {RenderObject} renderObject - The render object to draw.
  40676. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  40677. */
  40678. draw( /*renderObject, info*/ ) { }
  40679. // compute node
  40680. /**
  40681. * Executes a compute command for the given compute node.
  40682. *
  40683. * @abstract
  40684. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  40685. * @param {Node} computeNode - The compute node.
  40686. * @param {Array<BindGroup>} bindings - The bindings.
  40687. * @param {ComputePipeline} computePipeline - The compute pipeline.
  40688. */
  40689. compute( /*computeGroup, computeNode, computeBindings, computePipeline*/ ) { }
  40690. // program
  40691. /**
  40692. * Creates a shader program from the given programmable stage.
  40693. *
  40694. * @abstract
  40695. * @param {ProgrammableStage} program - The programmable stage.
  40696. */
  40697. createProgram( /*program*/ ) { }
  40698. /**
  40699. * Destroys the shader program of the given programmable stage.
  40700. *
  40701. * @abstract
  40702. * @param {ProgrammableStage} program - The programmable stage.
  40703. */
  40704. destroyProgram( /*program*/ ) { }
  40705. // bindings
  40706. /**
  40707. * Creates bindings from the given bind group definition.
  40708. *
  40709. * @abstract
  40710. * @param {BindGroup} bindGroup - The bind group.
  40711. * @param {Array<BindGroup>} bindings - Array of bind groups.
  40712. * @param {number} cacheIndex - The cache index.
  40713. * @param {number} version - The version.
  40714. */
  40715. createBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  40716. /**
  40717. * Updates the given bind group definition.
  40718. *
  40719. * @abstract
  40720. * @param {BindGroup} bindGroup - The bind group.
  40721. * @param {Array<BindGroup>} bindings - Array of bind groups.
  40722. * @param {number} cacheIndex - The cache index.
  40723. * @param {number} version - The version.
  40724. */
  40725. updateBindings( /*bindGroup, bindings, cacheIndex, version*/ ) { }
  40726. /**
  40727. * Updates a buffer binding.
  40728. *
  40729. * @abstract
  40730. * @param {Buffer} binding - The buffer binding to update.
  40731. */
  40732. updateBinding( /*binding*/ ) { }
  40733. // pipeline
  40734. /**
  40735. * Creates a render pipeline for the given render object.
  40736. *
  40737. * @abstract
  40738. * @param {RenderObject} renderObject - The render object.
  40739. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  40740. */
  40741. createRenderPipeline( /*renderObject, promises*/ ) { }
  40742. /**
  40743. * Creates a compute pipeline for the given compute node.
  40744. *
  40745. * @abstract
  40746. * @param {ComputePipeline} computePipeline - The compute pipeline.
  40747. * @param {Array<BindGroup>} bindings - The bindings.
  40748. */
  40749. createComputePipeline( /*computePipeline, bindings*/ ) { }
  40750. // cache key
  40751. /**
  40752. * Returns `true` if the render pipeline requires an update.
  40753. *
  40754. * @abstract
  40755. * @param {RenderObject} renderObject - The render object.
  40756. * @return {boolean} Whether the render pipeline requires an update or not.
  40757. */
  40758. needsRenderUpdate( /*renderObject*/ ) { }
  40759. /**
  40760. * Returns a cache key that is used to identify render pipelines.
  40761. *
  40762. * @abstract
  40763. * @param {RenderObject} renderObject - The render object.
  40764. * @return {string} The cache key.
  40765. */
  40766. getRenderCacheKey( /*renderObject*/ ) { }
  40767. // node builder
  40768. /**
  40769. * Returns a node builder for the given render object.
  40770. *
  40771. * @abstract
  40772. * @param {RenderObject} renderObject - The render object.
  40773. * @param {Renderer} renderer - The renderer.
  40774. * @return {NodeBuilder} The node builder.
  40775. */
  40776. createNodeBuilder( /*renderObject, renderer*/ ) { }
  40777. // textures
  40778. /**
  40779. * Creates a GPU sampler for the given texture.
  40780. *
  40781. * @abstract
  40782. * @param {Texture} texture - The texture to create the sampler for.
  40783. */
  40784. createSampler( /*texture*/ ) { }
  40785. /**
  40786. * Destroys the GPU sampler for the given texture.
  40787. *
  40788. * @abstract
  40789. * @param {Texture} texture - The texture to destroy the sampler for.
  40790. */
  40791. destroySampler( /*texture*/ ) {}
  40792. /**
  40793. * Creates a default texture for the given texture that can be used
  40794. * as a placeholder until the actual texture is ready for usage.
  40795. *
  40796. * @abstract
  40797. * @param {Texture} texture - The texture to create a default texture for.
  40798. */
  40799. createDefaultTexture( /*texture*/ ) { }
  40800. /**
  40801. * Defines a texture on the GPU for the given texture object.
  40802. *
  40803. * @abstract
  40804. * @param {Texture} texture - The texture.
  40805. * @param {Object} [options={}] - Optional configuration parameter.
  40806. */
  40807. createTexture( /*texture, options={}*/ ) { }
  40808. /**
  40809. * Uploads the updated texture data to the GPU.
  40810. *
  40811. * @abstract
  40812. * @param {Texture} texture - The texture.
  40813. * @param {Object} [options={}] - Optional configuration parameter.
  40814. */
  40815. updateTexture( /*texture, options = {}*/ ) { }
  40816. /**
  40817. * Generates mipmaps for the given texture.
  40818. *
  40819. * @abstract
  40820. * @param {Texture} texture - The texture.
  40821. */
  40822. generateMipmaps( /*texture*/ ) { }
  40823. /**
  40824. * Destroys the GPU data for the given texture object.
  40825. *
  40826. * @abstract
  40827. * @param {Texture} texture - The texture.
  40828. */
  40829. destroyTexture( /*texture*/ ) { }
  40830. /**
  40831. * Returns texture data as a typed array.
  40832. *
  40833. * @abstract
  40834. * @async
  40835. * @param {Texture} texture - The texture to copy.
  40836. * @param {number} x - The x coordinate of the copy origin.
  40837. * @param {number} y - The y coordinate of the copy origin.
  40838. * @param {number} width - The width of the copy.
  40839. * @param {number} height - The height of the copy.
  40840. * @param {number} faceIndex - The face index.
  40841. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  40842. */
  40843. async copyTextureToBuffer( /*texture, x, y, width, height, faceIndex*/ ) {}
  40844. /**
  40845. * Copies data of the given source texture to the given destination texture.
  40846. *
  40847. * @abstract
  40848. * @param {Texture} srcTexture - The source texture.
  40849. * @param {Texture} dstTexture - The destination texture.
  40850. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  40851. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  40852. * @param {number} [srcLevel=0] - The source mip level to copy from.
  40853. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  40854. */
  40855. copyTextureToTexture( /*srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0*/ ) {}
  40856. /**
  40857. * Copies the current bound framebuffer to the given texture.
  40858. *
  40859. * @abstract
  40860. * @param {Texture} texture - The destination texture.
  40861. * @param {RenderContext} renderContext - The render context.
  40862. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  40863. */
  40864. copyFramebufferToTexture( /*texture, renderContext, rectangle*/ ) {}
  40865. // attributes
  40866. /**
  40867. * Creates the GPU buffer of a shader attribute.
  40868. *
  40869. * @abstract
  40870. * @param {BufferAttribute} attribute - The buffer attribute.
  40871. */
  40872. createAttribute( /*attribute*/ ) { }
  40873. /**
  40874. * Creates the GPU buffer of an indexed shader attribute.
  40875. *
  40876. * @abstract
  40877. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  40878. */
  40879. createIndexAttribute( /*attribute*/ ) { }
  40880. /**
  40881. * Creates the GPU buffer of a storage attribute.
  40882. *
  40883. * @abstract
  40884. * @param {BufferAttribute} attribute - The buffer attribute.
  40885. */
  40886. createStorageAttribute( /*attribute*/ ) { }
  40887. /**
  40888. * Updates the GPU buffer of a shader attribute.
  40889. *
  40890. * @abstract
  40891. * @param {BufferAttribute} attribute - The buffer attribute to update.
  40892. */
  40893. updateAttribute( /*attribute*/ ) { }
  40894. /**
  40895. * Destroys the GPU buffer of a shader attribute.
  40896. *
  40897. * @abstract
  40898. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  40899. */
  40900. destroyAttribute( /*attribute*/ ) { }
  40901. // canvas
  40902. /**
  40903. * Returns the backend's rendering context.
  40904. *
  40905. * @abstract
  40906. * @return {Object} The rendering context.
  40907. */
  40908. getContext() { }
  40909. /**
  40910. * Backends can use this method if they have to run
  40911. * logic when the renderer gets resized.
  40912. *
  40913. * @abstract
  40914. */
  40915. updateSize() { }
  40916. /**
  40917. * Updates the viewport with the values from the given render context.
  40918. *
  40919. * @abstract
  40920. * @param {RenderContext} renderContext - The render context.
  40921. */
  40922. updateViewport( /*renderContext*/ ) {}
  40923. // utils
  40924. /**
  40925. * Returns `true` if the given 3D object is fully occluded by other
  40926. * 3D objects in the scene. Backends must implement this method by using
  40927. * a Occlusion Query API.
  40928. *
  40929. * @abstract
  40930. * @param {RenderContext} renderContext - The render context.
  40931. * @param {Object3D} object - The 3D object to test.
  40932. * @return {boolean} Whether the 3D object is fully occluded or not.
  40933. */
  40934. isOccluded( /*renderContext, object*/ ) {}
  40935. /**
  40936. * Resolves the time stamp for the given render context and type.
  40937. *
  40938. * @async
  40939. * @abstract
  40940. * @param {string} [type='render'] - The type of the time stamp.
  40941. * @return {Promise<number>} A Promise that resolves with the time stamp.
  40942. */
  40943. async resolveTimestampsAsync( type = 'render' ) {
  40944. if ( ! this.trackTimestamp ) {
  40945. warnOnce( 'WebGPURenderer: Timestamp tracking is disabled.' );
  40946. return;
  40947. }
  40948. const queryPool = this.timestampQueryPool[ type ];
  40949. if ( ! queryPool ) {
  40950. warnOnce( `WebGPURenderer: No timestamp query pool for type '${type}' found.` );
  40951. return;
  40952. }
  40953. const duration = await queryPool.resolveQueriesAsync();
  40954. this.renderer.info[ type ].timestamp = duration;
  40955. return duration;
  40956. }
  40957. /**
  40958. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  40959. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  40960. *
  40961. * @async
  40962. * @abstract
  40963. * @return {Promise} A Promise that resolves when synchronization has been finished.
  40964. */
  40965. async waitForGPU() {}
  40966. /**
  40967. * This method performs a readback operation by moving buffer data from
  40968. * a storage buffer attribute from the GPU to the CPU.
  40969. *
  40970. * @async
  40971. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  40972. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  40973. */
  40974. async getArrayBufferAsync( /* attribute */ ) {}
  40975. /**
  40976. * Checks if the given feature is supported by the backend.
  40977. *
  40978. * @async
  40979. * @abstract
  40980. * @param {string} name - The feature's name.
  40981. * @return {Promise<boolean>} A Promise that resolves with a bool that indicates whether the feature is supported or not.
  40982. */
  40983. async hasFeatureAsync( /*name*/ ) { }
  40984. /**
  40985. * Checks if the given feature is supported by the backend.
  40986. *
  40987. * @abstract
  40988. * @param {string} name - The feature's name.
  40989. * @return {boolean} Whether the feature is supported or not.
  40990. */
  40991. hasFeature( /*name*/ ) {}
  40992. /**
  40993. * Returns the maximum anisotropy texture filtering value.
  40994. *
  40995. * @abstract
  40996. * @return {number} The maximum anisotropy texture filtering value.
  40997. */
  40998. getMaxAnisotropy() {}
  40999. /**
  41000. * Returns the drawing buffer size.
  41001. *
  41002. * @return {Vector2} The drawing buffer size.
  41003. */
  41004. getDrawingBufferSize() {
  41005. _vector2 = _vector2 || new Vector2();
  41006. return this.renderer.getDrawingBufferSize( _vector2 );
  41007. }
  41008. /**
  41009. * Defines the scissor test.
  41010. *
  41011. * @abstract
  41012. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  41013. */
  41014. setScissorTest( /*boolean*/ ) { }
  41015. /**
  41016. * Returns the clear color and alpha into a single
  41017. * color object.
  41018. *
  41019. * @return {Color4} The clear color.
  41020. */
  41021. getClearColor() {
  41022. const renderer = this.renderer;
  41023. _color4 = _color4 || new Color4();
  41024. renderer.getClearColor( _color4 );
  41025. _color4.getRGB( _color4 );
  41026. return _color4;
  41027. }
  41028. /**
  41029. * Returns the DOM element. If no DOM element exists, the backend
  41030. * creates a new one.
  41031. *
  41032. * @return {HTMLCanvasElement} The DOM element.
  41033. */
  41034. getDomElement() {
  41035. let domElement = this.domElement;
  41036. if ( domElement === null ) {
  41037. domElement = ( this.parameters.canvas !== undefined ) ? this.parameters.canvas : createCanvasElement();
  41038. // OffscreenCanvas does not have setAttribute, see #22811
  41039. if ( 'setAttribute' in domElement ) domElement.setAttribute( 'data-engine', `three.js r${REVISION} webgpu` );
  41040. this.domElement = domElement;
  41041. }
  41042. return domElement;
  41043. }
  41044. /**
  41045. * Sets a dictionary for the given object into the
  41046. * internal data structure.
  41047. *
  41048. * @param {Object} object - The object.
  41049. * @param {Object} value - The dictionary to set.
  41050. */
  41051. set( object, value ) {
  41052. this.data.set( object, value );
  41053. }
  41054. /**
  41055. * Returns the dictionary for the given object.
  41056. *
  41057. * @param {Object} object - The object.
  41058. * @return {Object} The object's dictionary.
  41059. */
  41060. get( object ) {
  41061. let map = this.data.get( object );
  41062. if ( map === undefined ) {
  41063. map = {};
  41064. this.data.set( object, map );
  41065. }
  41066. return map;
  41067. }
  41068. /**
  41069. * Checks if the given object has a dictionary
  41070. * with data defined.
  41071. *
  41072. * @param {Object} object - The object.
  41073. * @return {boolean} Whether a dictionary for the given object as been defined or not.
  41074. */
  41075. has( object ) {
  41076. return this.data.has( object );
  41077. }
  41078. /**
  41079. * Deletes an object from the internal data structure.
  41080. *
  41081. * @param {Object} object - The object to delete.
  41082. */
  41083. delete( object ) {
  41084. this.data.delete( object );
  41085. }
  41086. /**
  41087. * Frees internal resources.
  41088. *
  41089. * @abstract
  41090. */
  41091. dispose() { }
  41092. }
  41093. let _id$1 = 0;
  41094. /**
  41095. * This module is internally used in context of compute shaders.
  41096. * This type of shader is not natively supported in WebGL 2 and
  41097. * thus implemented via Transform Feedback. `DualAttributeData`
  41098. * manages the related data.
  41099. *
  41100. * @private
  41101. */
  41102. class DualAttributeData {
  41103. constructor( attributeData, dualBuffer ) {
  41104. this.buffers = [ attributeData.bufferGPU, dualBuffer ];
  41105. this.type = attributeData.type;
  41106. this.bufferType = attributeData.bufferType;
  41107. this.pbo = attributeData.pbo;
  41108. this.byteLength = attributeData.byteLength;
  41109. this.bytesPerElement = attributeData.BYTES_PER_ELEMENT;
  41110. this.version = attributeData.version;
  41111. this.isInteger = attributeData.isInteger;
  41112. this.activeBufferIndex = 0;
  41113. this.baseId = attributeData.id;
  41114. }
  41115. get id() {
  41116. return `${ this.baseId }|${ this.activeBufferIndex }`;
  41117. }
  41118. get bufferGPU() {
  41119. return this.buffers[ this.activeBufferIndex ];
  41120. }
  41121. get transformBuffer() {
  41122. return this.buffers[ this.activeBufferIndex ^ 1 ];
  41123. }
  41124. switchBuffers() {
  41125. this.activeBufferIndex ^= 1;
  41126. }
  41127. }
  41128. /**
  41129. * A WebGL 2 backend utility module for managing shader attributes.
  41130. *
  41131. * @private
  41132. */
  41133. class WebGLAttributeUtils {
  41134. /**
  41135. * Constructs a new utility object.
  41136. *
  41137. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41138. */
  41139. constructor( backend ) {
  41140. /**
  41141. * A reference to the WebGL 2 backend.
  41142. *
  41143. * @type {WebGLBackend}
  41144. */
  41145. this.backend = backend;
  41146. }
  41147. /**
  41148. * Creates the GPU buffer for the given buffer attribute.
  41149. *
  41150. * @param {BufferAttribute} attribute - The buffer attribute.
  41151. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  41152. */
  41153. createAttribute( attribute, bufferType ) {
  41154. const backend = this.backend;
  41155. const { gl } = backend;
  41156. const array = attribute.array;
  41157. const usage = attribute.usage || gl.STATIC_DRAW;
  41158. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  41159. const bufferData = backend.get( bufferAttribute );
  41160. let bufferGPU = bufferData.bufferGPU;
  41161. if ( bufferGPU === undefined ) {
  41162. bufferGPU = this._createBuffer( gl, bufferType, array, usage );
  41163. bufferData.bufferGPU = bufferGPU;
  41164. bufferData.bufferType = bufferType;
  41165. bufferData.version = bufferAttribute.version;
  41166. }
  41167. //attribute.onUploadCallback();
  41168. let type;
  41169. if ( array instanceof Float32Array ) {
  41170. type = gl.FLOAT;
  41171. } else if ( array instanceof Uint16Array ) {
  41172. if ( attribute.isFloat16BufferAttribute ) {
  41173. type = gl.HALF_FLOAT;
  41174. } else {
  41175. type = gl.UNSIGNED_SHORT;
  41176. }
  41177. } else if ( array instanceof Int16Array ) {
  41178. type = gl.SHORT;
  41179. } else if ( array instanceof Uint32Array ) {
  41180. type = gl.UNSIGNED_INT;
  41181. } else if ( array instanceof Int32Array ) {
  41182. type = gl.INT;
  41183. } else if ( array instanceof Int8Array ) {
  41184. type = gl.BYTE;
  41185. } else if ( array instanceof Uint8Array ) {
  41186. type = gl.UNSIGNED_BYTE;
  41187. } else if ( array instanceof Uint8ClampedArray ) {
  41188. type = gl.UNSIGNED_BYTE;
  41189. } else {
  41190. throw new Error( 'THREE.WebGLBackend: Unsupported buffer data format: ' + array );
  41191. }
  41192. let attributeData = {
  41193. bufferGPU,
  41194. bufferType,
  41195. type,
  41196. byteLength: array.byteLength,
  41197. bytesPerElement: array.BYTES_PER_ELEMENT,
  41198. version: attribute.version,
  41199. pbo: attribute.pbo,
  41200. isInteger: type === gl.INT || type === gl.UNSIGNED_INT || attribute.gpuType === IntType,
  41201. id: _id$1 ++
  41202. };
  41203. if ( attribute.isStorageBufferAttribute || attribute.isStorageInstancedBufferAttribute ) {
  41204. // create buffer for transform feedback use
  41205. const bufferGPUDual = this._createBuffer( gl, bufferType, array, usage );
  41206. attributeData = new DualAttributeData( attributeData, bufferGPUDual );
  41207. }
  41208. backend.set( attribute, attributeData );
  41209. }
  41210. /**
  41211. * Updates the GPU buffer of the given buffer attribute.
  41212. *
  41213. * @param {BufferAttribute} attribute - The buffer attribute.
  41214. */
  41215. updateAttribute( attribute ) {
  41216. const backend = this.backend;
  41217. const { gl } = backend;
  41218. const array = attribute.array;
  41219. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  41220. const bufferData = backend.get( bufferAttribute );
  41221. const bufferType = bufferData.bufferType;
  41222. const updateRanges = attribute.isInterleavedBufferAttribute ? attribute.data.updateRanges : attribute.updateRanges;
  41223. gl.bindBuffer( bufferType, bufferData.bufferGPU );
  41224. if ( updateRanges.length === 0 ) {
  41225. // Not using update ranges
  41226. gl.bufferSubData( bufferType, 0, array );
  41227. } else {
  41228. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  41229. const range = updateRanges[ i ];
  41230. gl.bufferSubData( bufferType, range.start * array.BYTES_PER_ELEMENT,
  41231. array, range.start, range.count );
  41232. }
  41233. bufferAttribute.clearUpdateRanges();
  41234. }
  41235. gl.bindBuffer( bufferType, null );
  41236. bufferData.version = bufferAttribute.version;
  41237. }
  41238. /**
  41239. * Destroys the GPU buffer of the given buffer attribute.
  41240. *
  41241. * @param {BufferAttribute} attribute - The buffer attribute.
  41242. */
  41243. destroyAttribute( attribute ) {
  41244. const backend = this.backend;
  41245. const { gl } = backend;
  41246. if ( attribute.isInterleavedBufferAttribute ) {
  41247. backend.delete( attribute.data );
  41248. }
  41249. const attributeData = backend.get( attribute );
  41250. gl.deleteBuffer( attributeData.bufferGPU );
  41251. backend.delete( attribute );
  41252. }
  41253. /**
  41254. * This method performs a readback operation by moving buffer data from
  41255. * a storage buffer attribute from the GPU to the CPU.
  41256. *
  41257. * @async
  41258. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  41259. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  41260. */
  41261. async getArrayBufferAsync( attribute ) {
  41262. const backend = this.backend;
  41263. const { gl } = backend;
  41264. const bufferAttribute = attribute.isInterleavedBufferAttribute ? attribute.data : attribute;
  41265. const { bufferGPU } = backend.get( bufferAttribute );
  41266. const array = attribute.array;
  41267. const byteLength = array.byteLength;
  41268. gl.bindBuffer( gl.COPY_READ_BUFFER, bufferGPU );
  41269. const writeBuffer = gl.createBuffer();
  41270. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  41271. gl.bufferData( gl.COPY_WRITE_BUFFER, byteLength, gl.STREAM_READ );
  41272. gl.copyBufferSubData( gl.COPY_READ_BUFFER, gl.COPY_WRITE_BUFFER, 0, 0, byteLength );
  41273. await backend.utils._clientWaitAsync();
  41274. const dstBuffer = new attribute.array.constructor( array.length );
  41275. // Ensure the buffer is bound before reading
  41276. gl.bindBuffer( gl.COPY_WRITE_BUFFER, writeBuffer );
  41277. gl.getBufferSubData( gl.COPY_WRITE_BUFFER, 0, dstBuffer );
  41278. gl.deleteBuffer( writeBuffer );
  41279. gl.bindBuffer( gl.COPY_READ_BUFFER, null );
  41280. gl.bindBuffer( gl.COPY_WRITE_BUFFER, null );
  41281. return dstBuffer.buffer;
  41282. }
  41283. /**
  41284. * Creates a WebGL buffer with the given data.
  41285. *
  41286. * @private
  41287. * @param {WebGL2RenderingContext} gl - The rendering context.
  41288. * @param {GLenum } bufferType - A flag that indicates the buffer type and thus binding point target.
  41289. * @param {TypedArray} array - The array of the buffer attribute.
  41290. * @param {GLenum} usage - The usage.
  41291. * @return {WebGLBuffer} The WebGL buffer.
  41292. */
  41293. _createBuffer( gl, bufferType, array, usage ) {
  41294. const bufferGPU = gl.createBuffer();
  41295. gl.bindBuffer( bufferType, bufferGPU );
  41296. gl.bufferData( bufferType, array, usage );
  41297. gl.bindBuffer( bufferType, null );
  41298. return bufferGPU;
  41299. }
  41300. }
  41301. let equationToGL, factorToGL;
  41302. /**
  41303. * A WebGL 2 backend utility module for managing the WebGL state.
  41304. *
  41305. * The major goal of this module is to reduce the number of state changes
  41306. * by caching the WEbGL state with a series of variables. In this way, the
  41307. * renderer only executes state change commands when necessary which
  41308. * improves the overall performance.
  41309. *
  41310. * @private
  41311. */
  41312. class WebGLState {
  41313. /**
  41314. * Constructs a new utility object.
  41315. *
  41316. * @param {WebGLBackend} backend - The WebGL 2 backend.
  41317. */
  41318. constructor( backend ) {
  41319. /**
  41320. * A reference to the WebGL 2 backend.
  41321. *
  41322. * @type {WebGLBackend}
  41323. */
  41324. this.backend = backend;
  41325. /**
  41326. * A reference to the rendering context.
  41327. *
  41328. * @type {WebGL2RenderingContext}
  41329. */
  41330. this.gl = this.backend.gl;
  41331. // Below properties are intended to cache
  41332. // the WebGL state and are not explicitly
  41333. // documented for convenience reasons.
  41334. this.enabled = {};
  41335. this.currentFlipSided = null;
  41336. this.currentCullFace = null;
  41337. this.currentProgram = null;
  41338. this.currentBlendingEnabled = false;
  41339. this.currentBlending = null;
  41340. this.currentBlendSrc = null;
  41341. this.currentBlendDst = null;
  41342. this.currentBlendSrcAlpha = null;
  41343. this.currentBlendDstAlpha = null;
  41344. this.currentPremultipledAlpha = null;
  41345. this.currentPolygonOffsetFactor = null;
  41346. this.currentPolygonOffsetUnits = null;
  41347. this.currentColorMask = null;
  41348. this.currentDepthFunc = null;
  41349. this.currentDepthMask = null;
  41350. this.currentStencilFunc = null;
  41351. this.currentStencilRef = null;
  41352. this.currentStencilFuncMask = null;
  41353. this.currentStencilFail = null;
  41354. this.currentStencilZFail = null;
  41355. this.currentStencilZPass = null;
  41356. this.currentStencilMask = null;
  41357. this.currentLineWidth = null;
  41358. this.currentClippingPlanes = 0;
  41359. this.currentVAO = null;
  41360. this.currentIndex = null;
  41361. this.currentBoundFramebuffers = {};
  41362. this.currentDrawbuffers = new WeakMap();
  41363. this.maxTextures = this.gl.getParameter( this.gl.MAX_TEXTURE_IMAGE_UNITS );
  41364. this.currentTextureSlot = null;
  41365. this.currentBoundTextures = {};
  41366. this.currentBoundBufferBases = {};
  41367. this._init();
  41368. }
  41369. /**
  41370. * Inits the state of the utility.
  41371. *
  41372. * @private
  41373. */
  41374. _init() {
  41375. const gl = this.gl;
  41376. // Store only WebGL constants here.
  41377. equationToGL = {
  41378. [ AddEquation ]: gl.FUNC_ADD,
  41379. [ SubtractEquation ]: gl.FUNC_SUBTRACT,
  41380. [ ReverseSubtractEquation ]: gl.FUNC_REVERSE_SUBTRACT
  41381. };
  41382. factorToGL = {
  41383. [ ZeroFactor ]: gl.ZERO,
  41384. [ OneFactor ]: gl.ONE,
  41385. [ SrcColorFactor ]: gl.SRC_COLOR,
  41386. [ SrcAlphaFactor ]: gl.SRC_ALPHA,
  41387. [ SrcAlphaSaturateFactor ]: gl.SRC_ALPHA_SATURATE,
  41388. [ DstColorFactor ]: gl.DST_COLOR,
  41389. [ DstAlphaFactor ]: gl.DST_ALPHA,
  41390. [ OneMinusSrcColorFactor ]: gl.ONE_MINUS_SRC_COLOR,
  41391. [ OneMinusSrcAlphaFactor ]: gl.ONE_MINUS_SRC_ALPHA,
  41392. [ OneMinusDstColorFactor ]: gl.ONE_MINUS_DST_COLOR,
  41393. [ OneMinusDstAlphaFactor ]: gl.ONE_MINUS_DST_ALPHA
  41394. };
  41395. const scissorParam = gl.getParameter( gl.SCISSOR_BOX );
  41396. const viewportParam = gl.getParameter( gl.VIEWPORT );
  41397. this.currentScissor = new Vector4().fromArray( scissorParam );
  41398. this.currentViewport = new Vector4().fromArray( viewportParam );
  41399. this._tempVec4 = new Vector4();
  41400. }
  41401. /**
  41402. * Enables the given WebGL capability.
  41403. *
  41404. * This method caches the capability state so
  41405. * `gl.enable()` is only called when necessary.
  41406. *
  41407. * @param {GLenum} id - The capability to enable.
  41408. */
  41409. enable( id ) {
  41410. const { enabled } = this;
  41411. if ( enabled[ id ] !== true ) {
  41412. this.gl.enable( id );
  41413. enabled[ id ] = true;
  41414. }
  41415. }
  41416. /**
  41417. * Disables the given WebGL capability.
  41418. *
  41419. * This method caches the capability state so
  41420. * `gl.disable()` is only called when necessary.
  41421. *
  41422. * @param {GLenum} id - The capability to enable.
  41423. */
  41424. disable( id ) {
  41425. const { enabled } = this;
  41426. if ( enabled[ id ] !== false ) {
  41427. this.gl.disable( id );
  41428. enabled[ id ] = false;
  41429. }
  41430. }
  41431. /**
  41432. * Specifies whether polygons are front- or back-facing
  41433. * by setting the winding orientation.
  41434. *
  41435. * This method caches the state so `gl.frontFace()` is only
  41436. * called when necessary.
  41437. *
  41438. * @param {boolean} flipSided - Whether triangles flipped their sides or not.
  41439. */
  41440. setFlipSided( flipSided ) {
  41441. if ( this.currentFlipSided !== flipSided ) {
  41442. const { gl } = this;
  41443. if ( flipSided ) {
  41444. gl.frontFace( gl.CW );
  41445. } else {
  41446. gl.frontFace( gl.CCW );
  41447. }
  41448. this.currentFlipSided = flipSided;
  41449. }
  41450. }
  41451. /**
  41452. * Specifies whether or not front- and/or back-facing
  41453. * polygons can be culled.
  41454. *
  41455. * This method caches the state so `gl.cullFace()` is only
  41456. * called when necessary.
  41457. *
  41458. * @param {number} cullFace - Defines which polygons are candidates for culling.
  41459. */
  41460. setCullFace( cullFace ) {
  41461. const { gl } = this;
  41462. if ( cullFace !== CullFaceNone ) {
  41463. this.enable( gl.CULL_FACE );
  41464. if ( cullFace !== this.currentCullFace ) {
  41465. if ( cullFace === CullFaceBack ) {
  41466. gl.cullFace( gl.BACK );
  41467. } else if ( cullFace === CullFaceFront ) {
  41468. gl.cullFace( gl.FRONT );
  41469. } else {
  41470. gl.cullFace( gl.FRONT_AND_BACK );
  41471. }
  41472. }
  41473. } else {
  41474. this.disable( gl.CULL_FACE );
  41475. }
  41476. this.currentCullFace = cullFace;
  41477. }
  41478. /**
  41479. * Specifies the width of line primitives.
  41480. *
  41481. * This method caches the state so `gl.lineWidth()` is only
  41482. * called when necessary.
  41483. *
  41484. * @param {number} width - The line width.
  41485. */
  41486. setLineWidth( width ) {
  41487. const { currentLineWidth, gl } = this;
  41488. if ( width !== currentLineWidth ) {
  41489. gl.lineWidth( width );
  41490. this.currentLineWidth = width;
  41491. }
  41492. }
  41493. /**
  41494. * Defines the blending.
  41495. *
  41496. * This method caches the state so `gl.blendEquation()`, `gl.blendEquationSeparate()`,
  41497. * `gl.blendFunc()` and `gl.blendFuncSeparate()` are only called when necessary.
  41498. *
  41499. * @param {number} blending - The blending type.
  41500. * @param {number} blendEquation - The blending equation.
  41501. * @param {number} blendSrc - Only relevant for custom blending. The RGB source blending factor.
  41502. * @param {number} blendDst - Only relevant for custom blending. The RGB destination blending factor.
  41503. * @param {number} blendEquationAlpha - Only relevant for custom blending. The blending equation for alpha.
  41504. * @param {number} blendSrcAlpha - Only relevant for custom blending. The alpha source blending factor.
  41505. * @param {number} blendDstAlpha - Only relevant for custom blending. The alpha destination blending factor.
  41506. * @param {boolean} premultipliedAlpha - Whether premultiplied alpha is enabled or not.
  41507. */
  41508. setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  41509. const { gl } = this;
  41510. if ( blending === NoBlending ) {
  41511. if ( this.currentBlendingEnabled === true ) {
  41512. this.disable( gl.BLEND );
  41513. this.currentBlendingEnabled = false;
  41514. }
  41515. return;
  41516. }
  41517. if ( this.currentBlendingEnabled === false ) {
  41518. this.enable( gl.BLEND );
  41519. this.currentBlendingEnabled = true;
  41520. }
  41521. if ( blending !== CustomBlending ) {
  41522. if ( blending !== this.currentBlending || premultipliedAlpha !== this.currentPremultipledAlpha ) {
  41523. if ( this.currentBlendEquation !== AddEquation || this.currentBlendEquationAlpha !== AddEquation ) {
  41524. gl.blendEquation( gl.FUNC_ADD );
  41525. this.currentBlendEquation = AddEquation;
  41526. this.currentBlendEquationAlpha = AddEquation;
  41527. }
  41528. if ( premultipliedAlpha ) {
  41529. switch ( blending ) {
  41530. case NormalBlending:
  41531. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  41532. break;
  41533. case AdditiveBlending:
  41534. gl.blendFunc( gl.ONE, gl.ONE );
  41535. break;
  41536. case SubtractiveBlending:
  41537. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  41538. break;
  41539. case MultiplyBlending:
  41540. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  41541. break;
  41542. default:
  41543. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  41544. break;
  41545. }
  41546. } else {
  41547. switch ( blending ) {
  41548. case NormalBlending:
  41549. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  41550. break;
  41551. case AdditiveBlending:
  41552. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  41553. break;
  41554. case SubtractiveBlending:
  41555. gl.blendFuncSeparate( gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ZERO, gl.ONE );
  41556. break;
  41557. case MultiplyBlending:
  41558. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  41559. break;
  41560. default:
  41561. console.error( 'THREE.WebGLState: Invalid blending: ', blending );
  41562. break;
  41563. }
  41564. }
  41565. this.currentBlendSrc = null;
  41566. this.currentBlendDst = null;
  41567. this.currentBlendSrcAlpha = null;
  41568. this.currentBlendDstAlpha = null;
  41569. this.currentBlending = blending;
  41570. this.currentPremultipledAlpha = premultipliedAlpha;
  41571. }
  41572. return;
  41573. }
  41574. // custom blending
  41575. blendEquationAlpha = blendEquationAlpha || blendEquation;
  41576. blendSrcAlpha = blendSrcAlpha || blendSrc;
  41577. blendDstAlpha = blendDstAlpha || blendDst;
  41578. if ( blendEquation !== this.currentBlendEquation || blendEquationAlpha !== this.currentBlendEquationAlpha ) {
  41579. gl.blendEquationSeparate( equationToGL[ blendEquation ], equationToGL[ blendEquationAlpha ] );
  41580. this.currentBlendEquation = blendEquation;
  41581. this.currentBlendEquationAlpha = blendEquationAlpha;
  41582. }
  41583. if ( blendSrc !== this.currentBlendSrc || blendDst !== this.currentBlendDst || blendSrcAlpha !== this.currentBlendSrcAlpha || blendDstAlpha !== this.currentBlendDstAlpha ) {
  41584. gl.blendFuncSeparate( factorToGL[ blendSrc ], factorToGL[ blendDst ], factorToGL[ blendSrcAlpha ], factorToGL[ blendDstAlpha ] );
  41585. this.currentBlendSrc = blendSrc;
  41586. this.currentBlendDst = blendDst;
  41587. this.currentBlendSrcAlpha = blendSrcAlpha;
  41588. this.currentBlendDstAlpha = blendDstAlpha;
  41589. }
  41590. this.currentBlending = blending;
  41591. this.currentPremultipledAlpha = false;
  41592. }
  41593. /**
  41594. * Specifies whether colors can be written when rendering
  41595. * into a framebuffer or not.
  41596. *
  41597. * This method caches the state so `gl.colorMask()` is only
  41598. * called when necessary.
  41599. *
  41600. * @param {boolean} colorMask - The color mask.
  41601. */
  41602. setColorMask( colorMask ) {
  41603. if ( this.currentColorMask !== colorMask ) {
  41604. this.gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  41605. this.currentColorMask = colorMask;
  41606. }
  41607. }
  41608. /**
  41609. * Specifies whether the depth test is enabled or not.
  41610. *
  41611. * @param {boolean} depthTest - Whether the depth test is enabled or not.
  41612. */
  41613. setDepthTest( depthTest ) {
  41614. const { gl } = this;
  41615. if ( depthTest ) {
  41616. this.enable( gl.DEPTH_TEST );
  41617. } else {
  41618. this.disable( gl.DEPTH_TEST );
  41619. }
  41620. }
  41621. /**
  41622. * Specifies whether depth values can be written when rendering
  41623. * into a framebuffer or not.
  41624. *
  41625. * This method caches the state so `gl.depthMask()` is only
  41626. * called when necessary.
  41627. *
  41628. * @param {boolean} depthMask - The depth mask.
  41629. */
  41630. setDepthMask( depthMask ) {
  41631. if ( this.currentDepthMask !== depthMask ) {
  41632. this.gl.depthMask( depthMask );
  41633. this.currentDepthMask = depthMask;
  41634. }
  41635. }
  41636. /**
  41637. * Specifies the depth compare function.
  41638. *
  41639. * This method caches the state so `gl.depthFunc()` is only
  41640. * called when necessary.
  41641. *
  41642. * @param {number} depthFunc - The depth compare function.
  41643. */
  41644. setDepthFunc( depthFunc ) {
  41645. if ( this.currentDepthFunc !== depthFunc ) {
  41646. const { gl } = this;
  41647. switch ( depthFunc ) {
  41648. case NeverDepth:
  41649. gl.depthFunc( gl.NEVER );
  41650. break;
  41651. case AlwaysDepth:
  41652. gl.depthFunc( gl.ALWAYS );
  41653. break;
  41654. case LessDepth:
  41655. gl.depthFunc( gl.LESS );
  41656. break;
  41657. case LessEqualDepth:
  41658. gl.depthFunc( gl.LEQUAL );
  41659. break;
  41660. case EqualDepth:
  41661. gl.depthFunc( gl.EQUAL );
  41662. break;
  41663. case GreaterEqualDepth:
  41664. gl.depthFunc( gl.GEQUAL );
  41665. break;
  41666. case GreaterDepth:
  41667. gl.depthFunc( gl.GREATER );
  41668. break;
  41669. case NotEqualDepth:
  41670. gl.depthFunc( gl.NOTEQUAL );
  41671. break;
  41672. default:
  41673. gl.depthFunc( gl.LEQUAL );
  41674. }
  41675. this.currentDepthFunc = depthFunc;
  41676. }
  41677. }
  41678. /**
  41679. * Specifies the scissor box.
  41680. *
  41681. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  41682. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  41683. * @param {number} width - The width of the viewport.
  41684. * @param {number} height - The height of the viewport.
  41685. *
  41686. */
  41687. scissor( x, y, width, height ) {
  41688. const scissor = this._tempVec4.set( x, y, width, height );
  41689. if ( this.currentScissor.equals( scissor ) === false ) {
  41690. const { gl } = this;
  41691. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  41692. this.currentScissor.copy( scissor );
  41693. }
  41694. }
  41695. /**
  41696. * Specifies the viewport.
  41697. *
  41698. * @param {number} x - The x-coordinate of the lower left corner of the viewport.
  41699. * @param {number} y - The y-coordinate of the lower left corner of the viewport.
  41700. * @param {number} width - The width of the viewport.
  41701. * @param {number} height - The height of the viewport.
  41702. *
  41703. */
  41704. viewport( x, y, width, height ) {
  41705. const viewport = this._tempVec4.set( x, y, width, height );
  41706. if ( this.currentViewport.equals( viewport ) === false ) {
  41707. const { gl } = this;
  41708. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  41709. this.currentViewport.copy( viewport );
  41710. }
  41711. }
  41712. /**
  41713. * Defines the scissor test.
  41714. *
  41715. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  41716. */
  41717. setScissorTest( boolean ) {
  41718. const gl = this.gl;
  41719. if ( boolean ) {
  41720. gl.enable( gl.SCISSOR_TEST );
  41721. } else {
  41722. gl.disable( gl.SCISSOR_TEST );
  41723. }
  41724. }
  41725. /**
  41726. * Specifies whether the stencil test is enabled or not.
  41727. *
  41728. * @param {boolean} stencilTest - Whether the stencil test is enabled or not.
  41729. */
  41730. setStencilTest( stencilTest ) {
  41731. const { gl } = this;
  41732. if ( stencilTest ) {
  41733. this.enable( gl.STENCIL_TEST );
  41734. } else {
  41735. this.disable( gl.STENCIL_TEST );
  41736. }
  41737. }
  41738. /**
  41739. * Specifies whether stencil values can be written when rendering
  41740. * into a framebuffer or not.
  41741. *
  41742. * This method caches the state so `gl.stencilMask()` is only
  41743. * called when necessary.
  41744. *
  41745. * @param {boolean} stencilMask - The stencil mask.
  41746. */
  41747. setStencilMask( stencilMask ) {
  41748. if ( this.currentStencilMask !== stencilMask ) {
  41749. this.gl.stencilMask( stencilMask );
  41750. this.currentStencilMask = stencilMask;
  41751. }
  41752. }
  41753. /**
  41754. * Specifies whether the stencil test functions.
  41755. *
  41756. * This method caches the state so `gl.stencilFunc()` is only
  41757. * called when necessary.
  41758. *
  41759. * @param {number} stencilFunc - The stencil compare function.
  41760. * @param {number} stencilRef - The reference value for the stencil test.
  41761. * @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.
  41762. */
  41763. setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  41764. if ( this.currentStencilFunc !== stencilFunc ||
  41765. this.currentStencilRef !== stencilRef ||
  41766. this.currentStencilFuncMask !== stencilMask ) {
  41767. this.gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  41768. this.currentStencilFunc = stencilFunc;
  41769. this.currentStencilRef = stencilRef;
  41770. this.currentStencilFuncMask = stencilMask;
  41771. }
  41772. }
  41773. /**
  41774. * Specifies whether the stencil test operation.
  41775. *
  41776. * This method caches the state so `gl.stencilOp()` is only
  41777. * called when necessary.
  41778. *
  41779. * @param {number} stencilFail - The function to use when the stencil test fails.
  41780. * @param {number} stencilZFail - The function to use when the stencil test passes, but the depth test fail.
  41781. * @param {number} stencilZPass - The function to use when both the stencil test and the depth test pass,
  41782. * or when the stencil test passes and there is no depth buffer or depth testing is disabled.
  41783. */
  41784. setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  41785. if ( this.currentStencilFail !== stencilFail ||
  41786. this.currentStencilZFail !== stencilZFail ||
  41787. this.currentStencilZPass !== stencilZPass ) {
  41788. this.gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  41789. this.currentStencilFail = stencilFail;
  41790. this.currentStencilZFail = stencilZFail;
  41791. this.currentStencilZPass = stencilZPass;
  41792. }
  41793. }
  41794. /**
  41795. * Configures the WebGL state for the given material.
  41796. *
  41797. * @param {Material} material - The material to configure the state for.
  41798. * @param {number} frontFaceCW - Whether the front faces are counter-clockwise or not.
  41799. * @param {number} hardwareClippingPlanes - The number of hardware clipping planes.
  41800. */
  41801. setMaterial( material, frontFaceCW, hardwareClippingPlanes ) {
  41802. const { gl } = this;
  41803. material.side === DoubleSide
  41804. ? this.disable( gl.CULL_FACE )
  41805. : this.enable( gl.CULL_FACE );
  41806. let flipSided = ( material.side === BackSide );
  41807. if ( frontFaceCW ) flipSided = ! flipSided;
  41808. this.setFlipSided( flipSided );
  41809. ( material.blending === NormalBlending && material.transparent === false )
  41810. ? this.setBlending( NoBlending )
  41811. : this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  41812. this.setDepthFunc( material.depthFunc );
  41813. this.setDepthTest( material.depthTest );
  41814. this.setDepthMask( material.depthWrite );
  41815. this.setColorMask( material.colorWrite );
  41816. const stencilWrite = material.stencilWrite;
  41817. this.setStencilTest( stencilWrite );
  41818. if ( stencilWrite ) {
  41819. this.setStencilMask( material.stencilWriteMask );
  41820. this.setStencilFunc( material.stencilFunc, material.stencilRef, material.stencilFuncMask );
  41821. this.setStencilOp( material.stencilFail, material.stencilZFail, material.stencilZPass );
  41822. }
  41823. this.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  41824. material.alphaToCoverage === true && this.backend.renderer.samples > 1
  41825. ? this.enable( gl.SAMPLE_ALPHA_TO_COVERAGE )
  41826. : this.disable( gl.SAMPLE_ALPHA_TO_COVERAGE );
  41827. if ( hardwareClippingPlanes > 0 ) {
  41828. if ( this.currentClippingPlanes !== hardwareClippingPlanes ) {
  41829. const CLIP_DISTANCE0_WEBGL = 0x3000;
  41830. for ( let i = 0; i < 8; i ++ ) {
  41831. if ( i < hardwareClippingPlanes ) {
  41832. this.enable( CLIP_DISTANCE0_WEBGL + i );
  41833. } else {
  41834. this.disable( CLIP_DISTANCE0_WEBGL + i );
  41835. }
  41836. }
  41837. }
  41838. }
  41839. }
  41840. /**
  41841. * Specifies the polygon offset.
  41842. *
  41843. * This method caches the state so `gl.polygonOffset()` is only
  41844. * called when necessary.
  41845. *
  41846. * @param {boolean} polygonOffset - Whether polygon offset is enabled or not.
  41847. * @param {number} factor - The scale factor for the variable depth offset for each polygon.
  41848. * @param {number} units - The multiplier by which an implementation-specific value is multiplied with to create a constant depth offset.
  41849. */
  41850. setPolygonOffset( polygonOffset, factor, units ) {
  41851. const { gl } = this;
  41852. if ( polygonOffset ) {
  41853. this.enable( gl.POLYGON_OFFSET_FILL );
  41854. if ( this.currentPolygonOffsetFactor !== factor || this.currentPolygonOffsetUnits !== units ) {
  41855. gl.polygonOffset( factor, units );
  41856. this.currentPolygonOffsetFactor = factor;
  41857. this.currentPolygonOffsetUnits = units;
  41858. }
  41859. } else {
  41860. this.disable( gl.POLYGON_OFFSET_FILL );
  41861. }
  41862. }
  41863. /**
  41864. * Defines the usage of the given WebGL program.
  41865. *
  41866. * This method caches the state so `gl.useProgram()` is only
  41867. * called when necessary.
  41868. *
  41869. * @param {WebGLProgram} program - The WebGL program to use.
  41870. * @return {boolean} Whether a program change has been executed or not.
  41871. */
  41872. useProgram( program ) {
  41873. if ( this.currentProgram !== program ) {
  41874. this.gl.useProgram( program );
  41875. this.currentProgram = program;
  41876. return true;
  41877. }
  41878. return false;
  41879. }
  41880. /**
  41881. * Sets the vertex state by binding the given VAO and element buffer.
  41882. *
  41883. * @param {WebGLVertexArrayObject} vao - The VAO.
  41884. * @param {WebGLBuffer} indexBuffer - The index buffer.
  41885. * @return {boolean} Whether a vertex state has been changed or not.
  41886. */
  41887. setVertexState( vao, indexBuffer = null ) {
  41888. const gl = this.gl;
  41889. if ( this.currentVAO !== vao || this.currentIndex !== indexBuffer ) {
  41890. gl.bindVertexArray( vao );
  41891. if ( indexBuffer !== null ) {
  41892. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
  41893. }
  41894. this.currentVAO = vao;
  41895. this.currentIndex = indexBuffer;
  41896. return true;
  41897. }
  41898. return false;
  41899. }
  41900. /**
  41901. * Resets the vertex array state by resetting the VAO and element buffer.
  41902. */
  41903. resetVertexState() {
  41904. const gl = this.gl;
  41905. gl.bindVertexArray( null );
  41906. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
  41907. this.currentVAO = null;
  41908. this.currentIndex = null;
  41909. }
  41910. // framebuffer
  41911. /**
  41912. * Binds the given framebuffer.
  41913. *
  41914. * This method caches the state so `gl.bindFramebuffer()` is only
  41915. * called when necessary.
  41916. *
  41917. * @param {number} target - The binding point (target).
  41918. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer to bind.
  41919. * @return {boolean} Whether a bind has been executed or not.
  41920. */
  41921. bindFramebuffer( target, framebuffer ) {
  41922. const { gl, currentBoundFramebuffers } = this;
  41923. if ( currentBoundFramebuffers[ target ] !== framebuffer ) {
  41924. gl.bindFramebuffer( target, framebuffer );
  41925. currentBoundFramebuffers[ target ] = framebuffer;
  41926. // gl.DRAW_FRAMEBUFFER is equivalent to gl.FRAMEBUFFER
  41927. if ( target === gl.DRAW_FRAMEBUFFER ) {
  41928. currentBoundFramebuffers[ gl.FRAMEBUFFER ] = framebuffer;
  41929. }
  41930. if ( target === gl.FRAMEBUFFER ) {
  41931. currentBoundFramebuffers[ gl.DRAW_FRAMEBUFFER ] = framebuffer;
  41932. }
  41933. return true;
  41934. }
  41935. return false;
  41936. }
  41937. /**
  41938. * Defines draw buffers to which fragment colors are written into.
  41939. * Configures the MRT setup of custom framebuffers.
  41940. *
  41941. * This method caches the state so `gl.drawBuffers()` is only
  41942. * called when necessary.
  41943. *
  41944. * @param {RenderContext} renderContext - The render context.
  41945. * @param {WebGLFramebuffer} framebuffer - The WebGL framebuffer.
  41946. */
  41947. drawBuffers( renderContext, framebuffer ) {
  41948. const { gl } = this;
  41949. let drawBuffers = [];
  41950. let needsUpdate = false;
  41951. if ( renderContext.textures !== null ) {
  41952. drawBuffers = this.currentDrawbuffers.get( framebuffer );
  41953. if ( drawBuffers === undefined ) {
  41954. drawBuffers = [];
  41955. this.currentDrawbuffers.set( framebuffer, drawBuffers );
  41956. }
  41957. const textures = renderContext.textures;
  41958. if ( drawBuffers.length !== textures.length || drawBuffers[ 0 ] !== gl.COLOR_ATTACHMENT0 ) {
  41959. for ( let i = 0, il = textures.length; i < il; i ++ ) {
  41960. drawBuffers[ i ] = gl.COLOR_ATTACHMENT0 + i;
  41961. }
  41962. drawBuffers.length = textures.length;
  41963. needsUpdate = true;
  41964. }
  41965. } else {
  41966. if ( drawBuffers[ 0 ] !== gl.BACK ) {
  41967. drawBuffers[ 0 ] = gl.BACK;
  41968. needsUpdate = true;
  41969. }
  41970. }
  41971. if ( needsUpdate ) {
  41972. gl.drawBuffers( drawBuffers );
  41973. }
  41974. }
  41975. // texture
  41976. /**
  41977. * Makes the given texture unit active.
  41978. *
  41979. * This method caches the state so `gl.activeTexture()` is only
  41980. * called when necessary.
  41981. *
  41982. * @param {number} webglSlot - The texture unit to make active.
  41983. */
  41984. activeTexture( webglSlot ) {
  41985. const { gl, currentTextureSlot, maxTextures } = this;
  41986. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  41987. if ( currentTextureSlot !== webglSlot ) {
  41988. gl.activeTexture( webglSlot );
  41989. this.currentTextureSlot = webglSlot;
  41990. }
  41991. }
  41992. /**
  41993. * Binds the given WebGL texture to a target.
  41994. *
  41995. * This method caches the state so `gl.bindTexture()` is only
  41996. * called when necessary.
  41997. *
  41998. * @param {number} webglType - The binding point (target).
  41999. * @param {WebGLTexture} webglTexture - The WebGL texture to bind.
  42000. * @param {number} webglSlot - The texture.
  42001. */
  42002. bindTexture( webglType, webglTexture, webglSlot ) {
  42003. const { gl, currentTextureSlot, currentBoundTextures, maxTextures } = this;
  42004. if ( webglSlot === undefined ) {
  42005. if ( currentTextureSlot === null ) {
  42006. webglSlot = gl.TEXTURE0 + maxTextures - 1;
  42007. } else {
  42008. webglSlot = currentTextureSlot;
  42009. }
  42010. }
  42011. let boundTexture = currentBoundTextures[ webglSlot ];
  42012. if ( boundTexture === undefined ) {
  42013. boundTexture = { type: undefined, texture: undefined };
  42014. currentBoundTextures[ webglSlot ] = boundTexture;
  42015. }
  42016. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  42017. if ( currentTextureSlot !== webglSlot ) {
  42018. gl.activeTexture( webglSlot );
  42019. this.currentTextureSlot = webglSlot;
  42020. }
  42021. gl.bindTexture( webglType, webglTexture );
  42022. boundTexture.type = webglType;
  42023. boundTexture.texture = webglTexture;
  42024. }
  42025. }
  42026. /**
  42027. * Binds a given WebGL buffer to a given binding point (target) at a given index.
  42028. *
  42029. * This method caches the state so `gl.bindBufferBase()` is only
  42030. * called when necessary.
  42031. *
  42032. * @param {number} target - The target for the bind operation.
  42033. * @param {number} index - The index of the target.
  42034. * @param {WebGLBuffer} buffer - The WebGL buffer.
  42035. * @return {boolean} Whether a bind has been executed or not.
  42036. */
  42037. bindBufferBase( target, index, buffer ) {
  42038. const { gl } = this;
  42039. const key = `${target}-${index}`;
  42040. if ( this.currentBoundBufferBases[ key ] !== buffer ) {
  42041. gl.bindBufferBase( target, index, buffer );
  42042. this.currentBoundBufferBases[ key ] = buffer;
  42043. return true;
  42044. }
  42045. return false;
  42046. }
  42047. /**
  42048. * Unbinds the current bound texture.
  42049. *
  42050. * This method caches the state so `gl.bindTexture()` is only
  42051. * called when necessary.
  42052. */
  42053. unbindTexture() {
  42054. const { gl, currentTextureSlot, currentBoundTextures } = this;
  42055. const boundTexture = currentBoundTextures[ currentTextureSlot ];
  42056. if ( boundTexture !== undefined && boundTexture.type !== undefined ) {
  42057. gl.bindTexture( boundTexture.type, null );
  42058. boundTexture.type = undefined;
  42059. boundTexture.texture = undefined;
  42060. }
  42061. }
  42062. }
  42063. /**
  42064. * A WebGL 2 backend utility module with common helpers.
  42065. *
  42066. * @private
  42067. */
  42068. class WebGLUtils {
  42069. /**
  42070. * Constructs a new utility object.
  42071. *
  42072. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42073. */
  42074. constructor( backend ) {
  42075. /**
  42076. * A reference to the WebGL 2 backend.
  42077. *
  42078. * @type {WebGLBackend}
  42079. */
  42080. this.backend = backend;
  42081. /**
  42082. * A reference to the rendering context.
  42083. *
  42084. * @type {WebGL2RenderingContext}
  42085. */
  42086. this.gl = this.backend.gl;
  42087. /**
  42088. * A reference to a backend module holding extension-related
  42089. * utility functions.
  42090. *
  42091. * @type {WebGLExtensions}
  42092. */
  42093. this.extensions = backend.extensions;
  42094. }
  42095. /**
  42096. * Converts the given three.js constant into a WebGL constant.
  42097. * The method currently supports the conversion of texture formats
  42098. * and types.
  42099. *
  42100. * @param {number} p - The three.js constant.
  42101. * @param {string} [colorSpace=NoColorSpace] - The color space.
  42102. * @return {?number} The corresponding WebGL constant.
  42103. */
  42104. convert( p, colorSpace = NoColorSpace ) {
  42105. const { gl, extensions } = this;
  42106. let extension;
  42107. const transfer = ColorManagement.getTransfer( colorSpace );
  42108. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  42109. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  42110. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  42111. if ( p === UnsignedInt5999Type ) return gl.UNSIGNED_INT_5_9_9_9_REV;
  42112. if ( p === ByteType ) return gl.BYTE;
  42113. if ( p === ShortType ) return gl.SHORT;
  42114. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  42115. if ( p === IntType ) return gl.INT;
  42116. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  42117. if ( p === FloatType ) return gl.FLOAT;
  42118. if ( p === HalfFloatType ) {
  42119. return gl.HALF_FLOAT;
  42120. }
  42121. if ( p === AlphaFormat ) return gl.ALPHA;
  42122. if ( p === RGBFormat ) return gl.RGB;
  42123. if ( p === RGBAFormat ) return gl.RGBA;
  42124. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  42125. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  42126. // WebGL2 formats.
  42127. if ( p === RedFormat ) return gl.RED;
  42128. if ( p === RedIntegerFormat ) return gl.RED_INTEGER;
  42129. if ( p === RGFormat ) return gl.RG;
  42130. if ( p === RGIntegerFormat ) return gl.RG_INTEGER;
  42131. if ( p === RGBAIntegerFormat ) return gl.RGBA_INTEGER;
  42132. // S3TC
  42133. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format || p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  42134. if ( transfer === SRGBTransfer ) {
  42135. extension = extensions.get( 'WEBGL_compressed_texture_s3tc_srgb' );
  42136. if ( extension !== null ) {
  42137. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_S3TC_DXT1_EXT;
  42138. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
  42139. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
  42140. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
  42141. } else {
  42142. return null;
  42143. }
  42144. } else {
  42145. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  42146. if ( extension !== null ) {
  42147. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  42148. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  42149. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  42150. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  42151. } else {
  42152. return null;
  42153. }
  42154. }
  42155. }
  42156. // PVRTC
  42157. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format || p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  42158. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  42159. if ( extension !== null ) {
  42160. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  42161. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  42162. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  42163. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  42164. } else {
  42165. return null;
  42166. }
  42167. }
  42168. // ETC
  42169. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format || p === RGBA_ETC2_EAC_Format ) {
  42170. extension = extensions.get( 'WEBGL_compressed_texture_etc' );
  42171. if ( extension !== null ) {
  42172. if ( p === RGB_ETC1_Format || p === RGB_ETC2_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ETC2 : extension.COMPRESSED_RGB8_ETC2;
  42173. if ( p === RGBA_ETC2_EAC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : extension.COMPRESSED_RGBA8_ETC2_EAC;
  42174. } else {
  42175. return null;
  42176. }
  42177. }
  42178. // ASTC
  42179. if ( p === RGBA_ASTC_4x4_Format || p === RGBA_ASTC_5x4_Format || p === RGBA_ASTC_5x5_Format ||
  42180. p === RGBA_ASTC_6x5_Format || p === RGBA_ASTC_6x6_Format || p === RGBA_ASTC_8x5_Format ||
  42181. p === RGBA_ASTC_8x6_Format || p === RGBA_ASTC_8x8_Format || p === RGBA_ASTC_10x5_Format ||
  42182. p === RGBA_ASTC_10x6_Format || p === RGBA_ASTC_10x8_Format || p === RGBA_ASTC_10x10_Format ||
  42183. p === RGBA_ASTC_12x10_Format || p === RGBA_ASTC_12x12_Format ) {
  42184. extension = extensions.get( 'WEBGL_compressed_texture_astc' );
  42185. if ( extension !== null ) {
  42186. if ( p === RGBA_ASTC_4x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : extension.COMPRESSED_RGBA_ASTC_4x4_KHR;
  42187. if ( p === RGBA_ASTC_5x4_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : extension.COMPRESSED_RGBA_ASTC_5x4_KHR;
  42188. if ( p === RGBA_ASTC_5x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : extension.COMPRESSED_RGBA_ASTC_5x5_KHR;
  42189. if ( p === RGBA_ASTC_6x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : extension.COMPRESSED_RGBA_ASTC_6x5_KHR;
  42190. if ( p === RGBA_ASTC_6x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : extension.COMPRESSED_RGBA_ASTC_6x6_KHR;
  42191. if ( p === RGBA_ASTC_8x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : extension.COMPRESSED_RGBA_ASTC_8x5_KHR;
  42192. if ( p === RGBA_ASTC_8x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : extension.COMPRESSED_RGBA_ASTC_8x6_KHR;
  42193. if ( p === RGBA_ASTC_8x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : extension.COMPRESSED_RGBA_ASTC_8x8_KHR;
  42194. if ( p === RGBA_ASTC_10x5_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : extension.COMPRESSED_RGBA_ASTC_10x5_KHR;
  42195. if ( p === RGBA_ASTC_10x6_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : extension.COMPRESSED_RGBA_ASTC_10x6_KHR;
  42196. if ( p === RGBA_ASTC_10x8_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : extension.COMPRESSED_RGBA_ASTC_10x8_KHR;
  42197. if ( p === RGBA_ASTC_10x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : extension.COMPRESSED_RGBA_ASTC_10x10_KHR;
  42198. if ( p === RGBA_ASTC_12x10_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : extension.COMPRESSED_RGBA_ASTC_12x10_KHR;
  42199. if ( p === RGBA_ASTC_12x12_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : extension.COMPRESSED_RGBA_ASTC_12x12_KHR;
  42200. } else {
  42201. return null;
  42202. }
  42203. }
  42204. // BPTC
  42205. if ( p === RGBA_BPTC_Format ) {
  42206. extension = extensions.get( 'EXT_texture_compression_bptc' );
  42207. if ( extension !== null ) {
  42208. if ( p === RGBA_BPTC_Format ) return ( transfer === SRGBTransfer ) ? extension.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : extension.COMPRESSED_RGBA_BPTC_UNORM_EXT;
  42209. } else {
  42210. return null;
  42211. }
  42212. }
  42213. // RGTC
  42214. if ( p === RED_RGTC1_Format || p === SIGNED_RED_RGTC1_Format || p === RED_GREEN_RGTC2_Format || p === SIGNED_RED_GREEN_RGTC2_Format ) {
  42215. extension = extensions.get( 'EXT_texture_compression_rgtc' );
  42216. if ( extension !== null ) {
  42217. if ( p === RGBA_BPTC_Format ) return extension.COMPRESSED_RED_RGTC1_EXT;
  42218. if ( p === SIGNED_RED_RGTC1_Format ) return extension.COMPRESSED_SIGNED_RED_RGTC1_EXT;
  42219. if ( p === RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_RED_GREEN_RGTC2_EXT;
  42220. if ( p === SIGNED_RED_GREEN_RGTC2_Format ) return extension.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT;
  42221. } else {
  42222. return null;
  42223. }
  42224. }
  42225. //
  42226. if ( p === UnsignedInt248Type ) {
  42227. return gl.UNSIGNED_INT_24_8;
  42228. }
  42229. // if "p" can't be resolved, assume the user defines a WebGL constant as a string (fallback/workaround for packed RGB formats)
  42230. return ( gl[ p ] !== undefined ) ? gl[ p ] : null;
  42231. }
  42232. /**
  42233. * This method can be used to synchronize the CPU with the GPU by waiting until
  42234. * ongoing GPU commands have been completed.
  42235. *
  42236. * @private
  42237. * @return {Promise} A promise that resolves when all ongoing GPU commands have been completed.
  42238. */
  42239. _clientWaitAsync() {
  42240. const { gl } = this;
  42241. const sync = gl.fenceSync( gl.SYNC_GPU_COMMANDS_COMPLETE, 0 );
  42242. gl.flush();
  42243. return new Promise( ( resolve, reject ) => {
  42244. function test() {
  42245. const res = gl.clientWaitSync( sync, gl.SYNC_FLUSH_COMMANDS_BIT, 0 );
  42246. if ( res === gl.WAIT_FAILED ) {
  42247. gl.deleteSync( sync );
  42248. reject();
  42249. return;
  42250. }
  42251. if ( res === gl.TIMEOUT_EXPIRED ) {
  42252. requestAnimationFrame( test );
  42253. return;
  42254. }
  42255. gl.deleteSync( sync );
  42256. resolve();
  42257. }
  42258. test();
  42259. } );
  42260. }
  42261. }
  42262. let initialized = false, wrappingToGL, filterToGL, compareToGL;
  42263. /**
  42264. * A WebGL 2 backend utility module for managing textures.
  42265. *
  42266. * @private
  42267. */
  42268. class WebGLTextureUtils {
  42269. /**
  42270. * Constructs a new utility object.
  42271. *
  42272. * @param {WebGLBackend} backend - The WebGL 2 backend.
  42273. */
  42274. constructor( backend ) {
  42275. /**
  42276. * A reference to the WebGL 2 backend.
  42277. *
  42278. * @type {WebGLBackend}
  42279. */
  42280. this.backend = backend;
  42281. /**
  42282. * A reference to the rendering context.
  42283. *
  42284. * @type {WebGL2RenderingContext}
  42285. */
  42286. this.gl = backend.gl;
  42287. /**
  42288. * A reference to a backend module holding extension-related
  42289. * utility functions.
  42290. *
  42291. * @type {WebGLExtensions}
  42292. */
  42293. this.extensions = backend.extensions;
  42294. /**
  42295. * A dictionary for managing default textures. The key
  42296. * is the binding point (target), the value the WEbGL texture object.
  42297. *
  42298. * @type {Object<GLenum,WebGLTexture>}
  42299. */
  42300. this.defaultTextures = {};
  42301. if ( initialized === false ) {
  42302. this._init();
  42303. initialized = true;
  42304. }
  42305. }
  42306. /**
  42307. * Inits the state of the utility.
  42308. *
  42309. * @private
  42310. */
  42311. _init() {
  42312. const gl = this.gl;
  42313. // Store only WebGL constants here.
  42314. wrappingToGL = {
  42315. [ RepeatWrapping ]: gl.REPEAT,
  42316. [ ClampToEdgeWrapping ]: gl.CLAMP_TO_EDGE,
  42317. [ MirroredRepeatWrapping ]: gl.MIRRORED_REPEAT
  42318. };
  42319. filterToGL = {
  42320. [ NearestFilter ]: gl.NEAREST,
  42321. [ NearestMipmapNearestFilter ]: gl.NEAREST_MIPMAP_NEAREST,
  42322. [ NearestMipmapLinearFilter ]: gl.NEAREST_MIPMAP_LINEAR,
  42323. [ LinearFilter ]: gl.LINEAR,
  42324. [ LinearMipmapNearestFilter ]: gl.LINEAR_MIPMAP_NEAREST,
  42325. [ LinearMipmapLinearFilter ]: gl.LINEAR_MIPMAP_LINEAR
  42326. };
  42327. compareToGL = {
  42328. [ NeverCompare ]: gl.NEVER,
  42329. [ AlwaysCompare ]: gl.ALWAYS,
  42330. [ LessCompare ]: gl.LESS,
  42331. [ LessEqualCompare ]: gl.LEQUAL,
  42332. [ EqualCompare ]: gl.EQUAL,
  42333. [ GreaterEqualCompare ]: gl.GEQUAL,
  42334. [ GreaterCompare ]: gl.GREATER,
  42335. [ NotEqualCompare ]: gl.NOTEQUAL
  42336. };
  42337. }
  42338. /**
  42339. * Returns the native texture type for the given texture.
  42340. *
  42341. * @param {Texture} texture - The texture.
  42342. * @return {GLenum} The native texture type.
  42343. */
  42344. getGLTextureType( texture ) {
  42345. const { gl } = this;
  42346. let glTextureType;
  42347. if ( texture.isCubeTexture === true ) {
  42348. glTextureType = gl.TEXTURE_CUBE_MAP;
  42349. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  42350. glTextureType = gl.TEXTURE_2D_ARRAY;
  42351. } else if ( texture.isData3DTexture === true ) { // TODO: isCompressed3DTexture, wait for #26642
  42352. glTextureType = gl.TEXTURE_3D;
  42353. } else {
  42354. glTextureType = gl.TEXTURE_2D;
  42355. }
  42356. return glTextureType;
  42357. }
  42358. /**
  42359. * Returns the native texture type for the given texture.
  42360. *
  42361. * @param {?string} internalFormatName - The internal format name. When `null`, the internal format is derived from the subsequent parameters.
  42362. * @param {GLenum} glFormat - The WebGL format.
  42363. * @param {GLenum} glType - The WebGL type.
  42364. * @param {string} colorSpace - The texture's color space.
  42365. * @param {boolean} [forceLinearTransfer=false] - Whether to force a linear transfer or not.
  42366. * @return {GLenum} The internal format.
  42367. */
  42368. getInternalFormat( internalFormatName, glFormat, glType, colorSpace, forceLinearTransfer = false ) {
  42369. const { gl, extensions } = this;
  42370. if ( internalFormatName !== null ) {
  42371. if ( gl[ internalFormatName ] !== undefined ) return gl[ internalFormatName ];
  42372. console.warn( 'THREE.WebGLRenderer: Attempt to use non-existing WebGL internal format \'' + internalFormatName + '\'' );
  42373. }
  42374. let internalFormat = glFormat;
  42375. if ( glFormat === gl.RED ) {
  42376. if ( glType === gl.FLOAT ) internalFormat = gl.R32F;
  42377. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.R16F;
  42378. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8;
  42379. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16;
  42380. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  42381. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  42382. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  42383. if ( glType === gl.INT ) internalFormat = gl.R32I;
  42384. }
  42385. if ( glFormat === gl.RED_INTEGER ) {
  42386. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.R8UI;
  42387. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.R16UI;
  42388. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.R32UI;
  42389. if ( glType === gl.BYTE ) internalFormat = gl.R8I;
  42390. if ( glType === gl.SHORT ) internalFormat = gl.R16I;
  42391. if ( glType === gl.INT ) internalFormat = gl.R32I;
  42392. }
  42393. if ( glFormat === gl.RG ) {
  42394. if ( glType === gl.FLOAT ) internalFormat = gl.RG32F;
  42395. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RG16F;
  42396. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8;
  42397. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16;
  42398. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  42399. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  42400. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  42401. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  42402. }
  42403. if ( glFormat === gl.RG_INTEGER ) {
  42404. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RG8UI;
  42405. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RG16UI;
  42406. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RG32UI;
  42407. if ( glType === gl.BYTE ) internalFormat = gl.RG8I;
  42408. if ( glType === gl.SHORT ) internalFormat = gl.RG16I;
  42409. if ( glType === gl.INT ) internalFormat = gl.RG32I;
  42410. }
  42411. if ( glFormat === gl.RGB ) {
  42412. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  42413. if ( glType === gl.FLOAT ) internalFormat = gl.RGB32F;
  42414. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGB16F;
  42415. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8;
  42416. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16;
  42417. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  42418. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  42419. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  42420. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  42421. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8 : gl.RGB8;
  42422. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) internalFormat = gl.RGB565;
  42423. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  42424. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGB4;
  42425. if ( glType === gl.UNSIGNED_INT_5_9_9_9_REV ) internalFormat = gl.RGB9_E5;
  42426. }
  42427. if ( glFormat === gl.RGB_INTEGER ) {
  42428. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGB8UI;
  42429. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGB16UI;
  42430. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGB32UI;
  42431. if ( glType === gl.BYTE ) internalFormat = gl.RGB8I;
  42432. if ( glType === gl.SHORT ) internalFormat = gl.RGB16I;
  42433. if ( glType === gl.INT ) internalFormat = gl.RGB32I;
  42434. }
  42435. if ( glFormat === gl.RGBA ) {
  42436. const transfer = forceLinearTransfer ? LinearTransfer : ColorManagement.getTransfer( colorSpace );
  42437. if ( glType === gl.FLOAT ) internalFormat = gl.RGBA32F;
  42438. if ( glType === gl.HALF_FLOAT ) internalFormat = gl.RGBA16F;
  42439. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8;
  42440. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16;
  42441. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  42442. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  42443. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  42444. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  42445. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = ( transfer === SRGBTransfer ) ? gl.SRGB8_ALPHA8 : gl.RGBA8;
  42446. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) internalFormat = gl.RGBA4;
  42447. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) internalFormat = gl.RGB5_A1;
  42448. }
  42449. if ( glFormat === gl.RGBA_INTEGER ) {
  42450. if ( glType === gl.UNSIGNED_BYTE ) internalFormat = gl.RGBA8UI;
  42451. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.RGBA16UI;
  42452. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.RGBA32UI;
  42453. if ( glType === gl.BYTE ) internalFormat = gl.RGBA8I;
  42454. if ( glType === gl.SHORT ) internalFormat = gl.RGBA16I;
  42455. if ( glType === gl.INT ) internalFormat = gl.RGBA32I;
  42456. }
  42457. if ( glFormat === gl.DEPTH_COMPONENT ) {
  42458. if ( glType === gl.UNSIGNED_SHORT ) internalFormat = gl.DEPTH_COMPONENT16;
  42459. if ( glType === gl.UNSIGNED_INT ) internalFormat = gl.DEPTH_COMPONENT24;
  42460. if ( glType === gl.FLOAT ) internalFormat = gl.DEPTH_COMPONENT32F;
  42461. }
  42462. if ( glFormat === gl.DEPTH_STENCIL ) {
  42463. if ( glType === gl.UNSIGNED_INT_24_8 ) internalFormat = gl.DEPTH24_STENCIL8;
  42464. }
  42465. if ( internalFormat === gl.R16F || internalFormat === gl.R32F ||
  42466. internalFormat === gl.RG16F || internalFormat === gl.RG32F ||
  42467. internalFormat === gl.RGBA16F || internalFormat === gl.RGBA32F ) {
  42468. extensions.get( 'EXT_color_buffer_float' );
  42469. }
  42470. return internalFormat;
  42471. }
  42472. /**
  42473. * Sets the texture parameters for the given texture.
  42474. *
  42475. * @param {GLenum} textureType - The texture type.
  42476. * @param {Texture} texture - The texture.
  42477. */
  42478. setTextureParameters( textureType, texture ) {
  42479. const { gl, extensions, backend } = this;
  42480. const workingPrimaries = ColorManagement.getPrimaries( ColorManagement.workingColorSpace );
  42481. const texturePrimaries = texture.colorSpace === NoColorSpace ? null : ColorManagement.getPrimaries( texture.colorSpace );
  42482. const unpackConversion = texture.colorSpace === NoColorSpace || workingPrimaries === texturePrimaries ? gl.NONE : gl.BROWSER_DEFAULT_WEBGL;
  42483. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  42484. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  42485. gl.pixelStorei( gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  42486. gl.pixelStorei( gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, unpackConversion );
  42487. gl.texParameteri( textureType, gl.TEXTURE_WRAP_S, wrappingToGL[ texture.wrapS ] );
  42488. gl.texParameteri( textureType, gl.TEXTURE_WRAP_T, wrappingToGL[ texture.wrapT ] );
  42489. if ( textureType === gl.TEXTURE_3D || textureType === gl.TEXTURE_2D_ARRAY ) {
  42490. // WebGL 2 does not support wrapping for depth 2D array textures
  42491. if ( ! texture.isArrayTexture ) {
  42492. gl.texParameteri( textureType, gl.TEXTURE_WRAP_R, wrappingToGL[ texture.wrapR ] );
  42493. }
  42494. }
  42495. gl.texParameteri( textureType, gl.TEXTURE_MAG_FILTER, filterToGL[ texture.magFilter ] );
  42496. const hasMipmaps = texture.mipmaps !== undefined && texture.mipmaps.length > 0;
  42497. // follow WebGPU backend mapping for texture filtering
  42498. const minFilter = texture.minFilter === LinearFilter && hasMipmaps ? LinearMipmapLinearFilter : texture.minFilter;
  42499. gl.texParameteri( textureType, gl.TEXTURE_MIN_FILTER, filterToGL[ minFilter ] );
  42500. if ( texture.compareFunction ) {
  42501. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE );
  42502. gl.texParameteri( textureType, gl.TEXTURE_COMPARE_FUNC, compareToGL[ texture.compareFunction ] );
  42503. }
  42504. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  42505. if ( texture.magFilter === NearestFilter ) return;
  42506. if ( texture.minFilter !== NearestMipmapLinearFilter && texture.minFilter !== LinearMipmapLinearFilter ) return;
  42507. if ( texture.type === FloatType && extensions.has( 'OES_texture_float_linear' ) === false ) return; // verify extension for WebGL 1 and WebGL 2
  42508. if ( texture.anisotropy > 1 ) {
  42509. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  42510. gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, backend.getMaxAnisotropy() ) );
  42511. }
  42512. }
  42513. }
  42514. /**
  42515. * Creates a default texture for the given texture that can be used
  42516. * as a placeholder until the actual texture is ready for usage.
  42517. *
  42518. * @param {Texture} texture - The texture to create a default texture for.
  42519. */
  42520. createDefaultTexture( texture ) {
  42521. const { gl, backend, defaultTextures } = this;
  42522. const glTextureType = this.getGLTextureType( texture );
  42523. let textureGPU = defaultTextures[ glTextureType ];
  42524. if ( textureGPU === undefined ) {
  42525. textureGPU = gl.createTexture();
  42526. backend.state.bindTexture( glTextureType, textureGPU );
  42527. gl.texParameteri( glTextureType, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  42528. gl.texParameteri( glTextureType, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  42529. // gl.texImage2D( glTextureType, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  42530. defaultTextures[ glTextureType ] = textureGPU;
  42531. }
  42532. backend.set( texture, {
  42533. textureGPU,
  42534. glTextureType,
  42535. isDefault: true
  42536. } );
  42537. }
  42538. /**
  42539. * Defines a texture on the GPU for the given texture object.
  42540. *
  42541. * @param {Texture} texture - The texture.
  42542. * @param {Object} [options={}] - Optional configuration parameter.
  42543. * @return {undefined}
  42544. */
  42545. createTexture( texture, options ) {
  42546. const { gl, backend } = this;
  42547. const { levels, width, height, depth } = options;
  42548. const glFormat = backend.utils.convert( texture.format, texture.colorSpace );
  42549. const glType = backend.utils.convert( texture.type );
  42550. const glInternalFormat = this.getInternalFormat( texture.internalFormat, glFormat, glType, texture.colorSpace, texture.isVideoTexture );
  42551. const textureGPU = gl.createTexture();
  42552. const glTextureType = this.getGLTextureType( texture );
  42553. backend.state.bindTexture( glTextureType, textureGPU );
  42554. this.setTextureParameters( glTextureType, texture );
  42555. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isCompressedArrayTexture ) {
  42556. gl.texStorage3D( gl.TEXTURE_2D_ARRAY, levels, glInternalFormat, width, height, depth );
  42557. } else if ( texture.isData3DTexture ) {
  42558. gl.texStorage3D( gl.TEXTURE_3D, levels, glInternalFormat, width, height, depth );
  42559. } else if ( ! texture.isVideoTexture ) {
  42560. gl.texStorage2D( glTextureType, levels, glInternalFormat, width, height );
  42561. }
  42562. backend.set( texture, {
  42563. textureGPU,
  42564. glTextureType,
  42565. glFormat,
  42566. glType,
  42567. glInternalFormat
  42568. } );
  42569. }
  42570. /**
  42571. * Uploads texture buffer data to the GPU memory.
  42572. *
  42573. * @param {WebGLBuffer} buffer - The buffer data.
  42574. * @param {Texture} texture - The texture,
  42575. */
  42576. copyBufferToTexture( buffer, texture ) {
  42577. const { gl, backend } = this;
  42578. const { textureGPU, glTextureType, glFormat, glType } = backend.get( texture );
  42579. const { width, height } = texture.source.data;
  42580. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, buffer );
  42581. backend.state.bindTexture( glTextureType, textureGPU );
  42582. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, false );
  42583. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false );
  42584. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, 0 );
  42585. gl.bindBuffer( gl.PIXEL_UNPACK_BUFFER, null );
  42586. backend.state.unbindTexture();
  42587. // debug
  42588. // const framebuffer = gl.createFramebuffer();
  42589. // gl.bindFramebuffer( gl.FRAMEBUFFER, framebuffer );
  42590. // gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glTextureType, textureGPU, 0 );
  42591. // const readout = new Float32Array( width * height * 4 );
  42592. // const altFormat = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_FORMAT );
  42593. // const altType = gl.getParameter( gl.IMPLEMENTATION_COLOR_READ_TYPE );
  42594. // gl.readPixels( 0, 0, width, height, altFormat, altType, readout );
  42595. // gl.bindFramebuffer( gl.FRAMEBUFFER, null );
  42596. // console.log( readout );
  42597. }
  42598. /**
  42599. * Uploads the updated texture data to the GPU.
  42600. *
  42601. * @param {Texture} texture - The texture.
  42602. * @param {Object} [options={}] - Optional configuration parameter.
  42603. */
  42604. updateTexture( texture, options ) {
  42605. const { gl } = this;
  42606. const { width, height } = options;
  42607. const { textureGPU, glTextureType, glFormat, glType, glInternalFormat } = this.backend.get( texture );
  42608. if ( texture.isRenderTargetTexture || ( textureGPU === undefined /* unsupported texture format */ ) )
  42609. return;
  42610. this.backend.state.bindTexture( glTextureType, textureGPU );
  42611. this.setTextureParameters( glTextureType, texture );
  42612. if ( texture.isCompressedTexture ) {
  42613. const mipmaps = texture.mipmaps;
  42614. const image = options.image;
  42615. for ( let i = 0; i < mipmaps.length; i ++ ) {
  42616. const mipmap = mipmaps[ i ];
  42617. if ( texture.isCompressedArrayTexture ) {
  42618. if ( texture.format !== gl.RGBA ) {
  42619. if ( glFormat !== null ) {
  42620. gl.compressedTexSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, mipmap.data );
  42621. } else {
  42622. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  42623. }
  42624. } else {
  42625. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, i, 0, 0, 0, mipmap.width, mipmap.height, image.depth, glFormat, glType, mipmap.data );
  42626. }
  42627. } else {
  42628. if ( glFormat !== null ) {
  42629. gl.compressedTexSubImage2D( gl.TEXTURE_2D, i, 0, 0, mipmap.width, mipmap.height, glFormat, mipmap.data );
  42630. } else {
  42631. console.warn( 'Unsupported compressed texture format' );
  42632. }
  42633. }
  42634. }
  42635. } else if ( texture.isCubeTexture ) {
  42636. const images = options.images;
  42637. for ( let i = 0; i < 6; i ++ ) {
  42638. const image = getImage( images[ i ] );
  42639. gl.texSubImage2D( gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, 0, 0, width, height, glFormat, glType, image );
  42640. }
  42641. } else if ( texture.isDataArrayTexture || texture.isArrayTexture ) {
  42642. const image = options.image;
  42643. gl.texSubImage3D( gl.TEXTURE_2D_ARRAY, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  42644. } else if ( texture.isData3DTexture ) {
  42645. const image = options.image;
  42646. gl.texSubImage3D( gl.TEXTURE_3D, 0, 0, 0, 0, image.width, image.height, image.depth, glFormat, glType, image.data );
  42647. } else if ( texture.isVideoTexture ) {
  42648. texture.update();
  42649. gl.texImage2D( glTextureType, 0, glInternalFormat, glFormat, glType, options.image );
  42650. } else {
  42651. const image = getImage( options.image );
  42652. gl.texSubImage2D( glTextureType, 0, 0, 0, width, height, glFormat, glType, image );
  42653. }
  42654. }
  42655. /**
  42656. * Generates mipmaps for the given texture.
  42657. *
  42658. * @param {Texture} texture - The texture.
  42659. */
  42660. generateMipmaps( texture ) {
  42661. const { gl, backend } = this;
  42662. const { textureGPU, glTextureType } = backend.get( texture );
  42663. backend.state.bindTexture( glTextureType, textureGPU );
  42664. gl.generateMipmap( glTextureType );
  42665. }
  42666. /**
  42667. * Deallocates the render buffers of the given render target.
  42668. *
  42669. * @param {RenderTarget} renderTarget - The render target.
  42670. */
  42671. deallocateRenderBuffers( renderTarget ) {
  42672. const { gl, backend } = this;
  42673. // remove framebuffer reference
  42674. if ( renderTarget ) {
  42675. const renderContextData = backend.get( renderTarget );
  42676. renderContextData.renderBufferStorageSetup = undefined;
  42677. if ( renderContextData.framebuffers ) {
  42678. for ( const cacheKey in renderContextData.framebuffers ) {
  42679. gl.deleteFramebuffer( renderContextData.framebuffers[ cacheKey ] );
  42680. }
  42681. delete renderContextData.framebuffers;
  42682. }
  42683. if ( renderContextData.depthRenderbuffer ) {
  42684. gl.deleteRenderbuffer( renderContextData.depthRenderbuffer );
  42685. delete renderContextData.depthRenderbuffer;
  42686. }
  42687. if ( renderContextData.stencilRenderbuffer ) {
  42688. gl.deleteRenderbuffer( renderContextData.stencilRenderbuffer );
  42689. delete renderContextData.stencilRenderbuffer;
  42690. }
  42691. if ( renderContextData.msaaFrameBuffer ) {
  42692. gl.deleteFramebuffer( renderContextData.msaaFrameBuffer );
  42693. delete renderContextData.msaaFrameBuffer;
  42694. }
  42695. if ( renderContextData.msaaRenderbuffers ) {
  42696. for ( let i = 0; i < renderContextData.msaaRenderbuffers.length; i ++ ) {
  42697. gl.deleteRenderbuffer( renderContextData.msaaRenderbuffers[ i ] );
  42698. }
  42699. delete renderContextData.msaaRenderbuffers;
  42700. }
  42701. }
  42702. }
  42703. /**
  42704. * Destroys the GPU data for the given texture object.
  42705. *
  42706. * @param {Texture} texture - The texture.
  42707. */
  42708. destroyTexture( texture ) {
  42709. const { gl, backend } = this;
  42710. const { textureGPU, renderTarget } = backend.get( texture );
  42711. this.deallocateRenderBuffers( renderTarget );
  42712. gl.deleteTexture( textureGPU );
  42713. backend.delete( texture );
  42714. }
  42715. /**
  42716. * Copies data of the given source texture to the given destination texture.
  42717. *
  42718. * @param {Texture} srcTexture - The source texture.
  42719. * @param {Texture} dstTexture - The destination texture.
  42720. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  42721. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  42722. * @param {number} [srcLevel=0] - The source mip level to copy from.
  42723. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  42724. */
  42725. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  42726. const { gl, backend } = this;
  42727. const { state } = this.backend;
  42728. const { textureGPU: dstTextureGPU, glTextureType, glType, glFormat } = backend.get( dstTexture );
  42729. state.bindTexture( glTextureType, dstTextureGPU );
  42730. // gather the necessary dimensions to copy
  42731. let width, height, depth, minX, minY, minZ;
  42732. let dstX, dstY, dstZ;
  42733. const image = srcTexture.isCompressedTexture ? srcTexture.mipmaps[ dstLevel ] : srcTexture.image;
  42734. if ( srcRegion !== null ) {
  42735. width = srcRegion.max.x - srcRegion.min.x;
  42736. height = srcRegion.max.y - srcRegion.min.y;
  42737. depth = srcRegion.isBox3 ? srcRegion.max.z - srcRegion.min.z : 1;
  42738. minX = srcRegion.min.x;
  42739. minY = srcRegion.min.y;
  42740. minZ = srcRegion.isBox3 ? srcRegion.min.z : 0;
  42741. } else {
  42742. const levelScale = Math.pow( 2, - srcLevel );
  42743. width = Math.floor( image.width * levelScale );
  42744. height = Math.floor( image.height * levelScale );
  42745. if ( srcTexture.isDataArrayTexture || srcTexture.isArrayTexture ) {
  42746. depth = image.depth;
  42747. } else if ( srcTexture.isData3DTexture ) {
  42748. depth = Math.floor( image.depth * levelScale );
  42749. } else {
  42750. depth = 1;
  42751. }
  42752. minX = 0;
  42753. minY = 0;
  42754. minZ = 0;
  42755. }
  42756. if ( dstPosition !== null ) {
  42757. dstX = dstPosition.x;
  42758. dstY = dstPosition.y;
  42759. dstZ = dstPosition.z;
  42760. } else {
  42761. dstX = 0;
  42762. dstY = 0;
  42763. dstZ = 0;
  42764. }
  42765. gl.pixelStorei( gl.UNPACK_FLIP_Y_WEBGL, dstTexture.flipY );
  42766. gl.pixelStorei( gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, dstTexture.premultiplyAlpha );
  42767. gl.pixelStorei( gl.UNPACK_ALIGNMENT, dstTexture.unpackAlignment );
  42768. // used for copying data from cpu
  42769. const currentUnpackRowLen = gl.getParameter( gl.UNPACK_ROW_LENGTH );
  42770. const currentUnpackImageHeight = gl.getParameter( gl.UNPACK_IMAGE_HEIGHT );
  42771. const currentUnpackSkipPixels = gl.getParameter( gl.UNPACK_SKIP_PIXELS );
  42772. const currentUnpackSkipRows = gl.getParameter( gl.UNPACK_SKIP_ROWS );
  42773. const currentUnpackSkipImages = gl.getParameter( gl.UNPACK_SKIP_IMAGES );
  42774. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, image.width );
  42775. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, image.height );
  42776. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, minX );
  42777. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, minY );
  42778. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, minZ );
  42779. // set up the src texture
  42780. const isDst3D = dstTexture.isDataArrayTexture || dstTexture.isData3DTexture || dstTexture.isArrayTexture;
  42781. if ( srcTexture.isRenderTargetTexture || srcTexture.isDepthTexture ) {
  42782. const srcTextureData = backend.get( srcTexture );
  42783. const dstTextureData = backend.get( dstTexture );
  42784. const srcRenderContextData = backend.get( srcTextureData.renderTarget );
  42785. const dstRenderContextData = backend.get( dstTextureData.renderTarget );
  42786. const srcFramebuffer = srcRenderContextData.framebuffers[ srcTextureData.cacheKey ];
  42787. const dstFramebuffer = dstRenderContextData.framebuffers[ dstTextureData.cacheKey ];
  42788. state.bindFramebuffer( gl.READ_FRAMEBUFFER, srcFramebuffer );
  42789. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, dstFramebuffer );
  42790. let mask = gl.COLOR_BUFFER_BIT;
  42791. if ( srcTexture.isDepthTexture ) mask = gl.DEPTH_BUFFER_BIT;
  42792. gl.blitFramebuffer( minX, minY, width, height, dstX, dstY, width, height, mask, gl.NEAREST );
  42793. state.bindFramebuffer( gl.READ_FRAMEBUFFER, null );
  42794. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, null );
  42795. } else {
  42796. if ( isDst3D ) {
  42797. // copy data into the 3d texture
  42798. if ( srcTexture.isDataTexture || srcTexture.isData3DTexture ) {
  42799. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image.data );
  42800. } else if ( dstTexture.isCompressedArrayTexture ) {
  42801. gl.compressedTexSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, image.data );
  42802. } else {
  42803. gl.texSubImage3D( glTextureType, dstLevel, dstX, dstY, dstZ, width, height, depth, glFormat, glType, image );
  42804. }
  42805. } else {
  42806. // copy data into the 2d texture
  42807. if ( srcTexture.isDataTexture ) {
  42808. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image.data );
  42809. } else if ( srcTexture.isCompressedTexture ) {
  42810. gl.compressedTexSubImage2D( glTextureType, dstLevel, dstX, dstY, image.width, image.height, glFormat, image.data );
  42811. } else {
  42812. gl.texSubImage2D( glTextureType, dstLevel, dstX, dstY, width, height, glFormat, glType, image );
  42813. }
  42814. }
  42815. }
  42816. // reset values
  42817. gl.pixelStorei( gl.UNPACK_ROW_LENGTH, currentUnpackRowLen );
  42818. gl.pixelStorei( gl.UNPACK_IMAGE_HEIGHT, currentUnpackImageHeight );
  42819. gl.pixelStorei( gl.UNPACK_SKIP_PIXELS, currentUnpackSkipPixels );
  42820. gl.pixelStorei( gl.UNPACK_SKIP_ROWS, currentUnpackSkipRows );
  42821. gl.pixelStorei( gl.UNPACK_SKIP_IMAGES, currentUnpackSkipImages );
  42822. // Generate mipmaps only when copying level 0
  42823. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  42824. gl.generateMipmap( glTextureType );
  42825. }
  42826. state.unbindTexture();
  42827. }
  42828. /**
  42829. * Copies the current bound framebuffer to the given texture.
  42830. *
  42831. * @param {Texture} texture - The destination texture.
  42832. * @param {RenderContext} renderContext - The render context.
  42833. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  42834. */
  42835. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  42836. const { gl } = this;
  42837. const { state } = this.backend;
  42838. const { textureGPU } = this.backend.get( texture );
  42839. const { x, y, z: width, w: height } = rectangle;
  42840. const requireDrawFrameBuffer = texture.isDepthTexture === true || ( renderContext.renderTarget && renderContext.renderTarget.samples > 0 );
  42841. const srcHeight = renderContext.renderTarget ? renderContext.renderTarget.height : this.backend.getDrawingBufferSize().y;
  42842. if ( requireDrawFrameBuffer ) {
  42843. const partial = ( x !== 0 || y !== 0 );
  42844. let mask;
  42845. let attachment;
  42846. if ( texture.isDepthTexture === true ) {
  42847. mask = gl.DEPTH_BUFFER_BIT;
  42848. attachment = gl.DEPTH_ATTACHMENT;
  42849. if ( renderContext.stencil ) {
  42850. mask |= gl.STENCIL_BUFFER_BIT;
  42851. }
  42852. } else {
  42853. mask = gl.COLOR_BUFFER_BIT;
  42854. attachment = gl.COLOR_ATTACHMENT0;
  42855. }
  42856. if ( partial ) {
  42857. const renderTargetContextData = this.backend.get( renderContext.renderTarget );
  42858. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  42859. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  42860. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  42861. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  42862. const flippedY = srcHeight - y - height;
  42863. gl.blitFramebuffer( x, flippedY, x + width, flippedY + height, x, flippedY, x + width, flippedY + height, mask, gl.NEAREST );
  42864. state.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  42865. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  42866. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, flippedY, width, height );
  42867. state.unbindTexture();
  42868. } else {
  42869. const fb = gl.createFramebuffer();
  42870. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  42871. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureGPU, 0 );
  42872. gl.blitFramebuffer( 0, 0, width, height, 0, 0, width, height, mask, gl.NEAREST );
  42873. gl.deleteFramebuffer( fb );
  42874. }
  42875. } else {
  42876. state.bindTexture( gl.TEXTURE_2D, textureGPU );
  42877. gl.copyTexSubImage2D( gl.TEXTURE_2D, 0, 0, 0, x, srcHeight - height - y, width, height );
  42878. state.unbindTexture();
  42879. }
  42880. if ( texture.generateMipmaps ) this.generateMipmaps( texture );
  42881. this.backend._setFramebuffer( renderContext );
  42882. }
  42883. /**
  42884. * SetupS storage for internal depth/stencil buffers and bind to correct framebuffer.
  42885. *
  42886. * @param {WebGLRenderbuffer} renderbuffer - The render buffer.
  42887. * @param {RenderContext} renderContext - The render context.
  42888. * @param {number} samples - The MSAA sample count.
  42889. * @param {boolean} [useMultisampledRTT=false] - Whether to use WEBGL_multisampled_render_to_texture or not.
  42890. */
  42891. setupRenderBufferStorage( renderbuffer, renderContext, samples, useMultisampledRTT = false ) {
  42892. const { gl } = this;
  42893. const renderTarget = renderContext.renderTarget;
  42894. const { depthTexture, depthBuffer, stencilBuffer, width, height } = renderTarget;
  42895. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  42896. if ( depthBuffer && ! stencilBuffer ) {
  42897. let glInternalFormat = gl.DEPTH_COMPONENT24;
  42898. if ( useMultisampledRTT === true ) {
  42899. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  42900. multisampledRTTExt.renderbufferStorageMultisampleEXT( gl.RENDERBUFFER, renderTarget.samples, glInternalFormat, width, height );
  42901. } else if ( samples > 0 ) {
  42902. if ( depthTexture && depthTexture.isDepthTexture ) {
  42903. if ( depthTexture.type === gl.FLOAT ) {
  42904. glInternalFormat = gl.DEPTH_COMPONENT32F;
  42905. }
  42906. }
  42907. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, glInternalFormat, width, height );
  42908. } else {
  42909. gl.renderbufferStorage( gl.RENDERBUFFER, glInternalFormat, width, height );
  42910. }
  42911. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  42912. } else if ( depthBuffer && stencilBuffer ) {
  42913. if ( samples > 0 ) {
  42914. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height );
  42915. } else {
  42916. gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height );
  42917. }
  42918. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, renderbuffer );
  42919. }
  42920. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  42921. }
  42922. /**
  42923. * Returns texture data as a typed array.
  42924. *
  42925. * @async
  42926. * @param {Texture} texture - The texture to copy.
  42927. * @param {number} x - The x coordinate of the copy origin.
  42928. * @param {number} y - The y coordinate of the copy origin.
  42929. * @param {number} width - The width of the copy.
  42930. * @param {number} height - The height of the copy.
  42931. * @param {number} faceIndex - The face index.
  42932. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  42933. */
  42934. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  42935. const { backend, gl } = this;
  42936. const { textureGPU, glFormat, glType } = this.backend.get( texture );
  42937. const fb = gl.createFramebuffer();
  42938. gl.bindFramebuffer( gl.READ_FRAMEBUFFER, fb );
  42939. const target = texture.isCubeTexture ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex : gl.TEXTURE_2D;
  42940. gl.framebufferTexture2D( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, target, textureGPU, 0 );
  42941. const typedArrayType = this._getTypedArrayType( glType );
  42942. const bytesPerTexel = this._getBytesPerTexel( glType, glFormat );
  42943. const elementCount = width * height;
  42944. const byteLength = elementCount * bytesPerTexel;
  42945. const buffer = gl.createBuffer();
  42946. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  42947. gl.bufferData( gl.PIXEL_PACK_BUFFER, byteLength, gl.STREAM_READ );
  42948. gl.readPixels( x, y, width, height, glFormat, glType, 0 );
  42949. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  42950. await backend.utils._clientWaitAsync();
  42951. const dstBuffer = new typedArrayType( byteLength / typedArrayType.BYTES_PER_ELEMENT );
  42952. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, buffer );
  42953. gl.getBufferSubData( gl.PIXEL_PACK_BUFFER, 0, dstBuffer );
  42954. gl.bindBuffer( gl.PIXEL_PACK_BUFFER, null );
  42955. gl.deleteFramebuffer( fb );
  42956. return dstBuffer;
  42957. }
  42958. /**
  42959. * Returns the corresponding typed array type for the given WebGL data type.
  42960. *
  42961. * @private
  42962. * @param {GLenum} glType - The WebGL data type.
  42963. * @return {TypedArray.constructor} The typed array type.
  42964. */
  42965. _getTypedArrayType( glType ) {
  42966. const { gl } = this;
  42967. if ( glType === gl.UNSIGNED_BYTE ) return Uint8Array;
  42968. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ) return Uint16Array;
  42969. if ( glType === gl.UNSIGNED_SHORT_5_5_5_1 ) return Uint16Array;
  42970. if ( glType === gl.UNSIGNED_SHORT_5_6_5 ) return Uint16Array;
  42971. if ( glType === gl.UNSIGNED_SHORT ) return Uint16Array;
  42972. if ( glType === gl.UNSIGNED_INT ) return Uint32Array;
  42973. if ( glType === gl.HALF_FLOAT ) return Uint16Array;
  42974. if ( glType === gl.FLOAT ) return Float32Array;
  42975. throw new Error( `Unsupported WebGL type: ${glType}` );
  42976. }
  42977. /**
  42978. * Returns the bytes-per-texel value for the given WebGL data type and texture format.
  42979. *
  42980. * @private
  42981. * @param {GLenum} glType - The WebGL data type.
  42982. * @param {GLenum} glFormat - The WebGL texture format.
  42983. * @return {number} The bytes-per-texel.
  42984. */
  42985. _getBytesPerTexel( glType, glFormat ) {
  42986. const { gl } = this;
  42987. let bytesPerComponent = 0;
  42988. if ( glType === gl.UNSIGNED_BYTE ) bytesPerComponent = 1;
  42989. if ( glType === gl.UNSIGNED_SHORT_4_4_4_4 ||
  42990. glType === gl.UNSIGNED_SHORT_5_5_5_1 ||
  42991. glType === gl.UNSIGNED_SHORT_5_6_5 ||
  42992. glType === gl.UNSIGNED_SHORT ||
  42993. glType === gl.HALF_FLOAT ) bytesPerComponent = 2;
  42994. if ( glType === gl.UNSIGNED_INT ||
  42995. glType === gl.FLOAT ) bytesPerComponent = 4;
  42996. if ( glFormat === gl.RGBA ) return bytesPerComponent * 4;
  42997. if ( glFormat === gl.RGB ) return bytesPerComponent * 3;
  42998. if ( glFormat === gl.ALPHA ) return bytesPerComponent;
  42999. }
  43000. }
  43001. function getImage( source ) {
  43002. if ( source.isDataTexture ) {
  43003. return source.image.data;
  43004. } else if ( ( typeof HTMLImageElement !== 'undefined' && source instanceof HTMLImageElement ) ||
  43005. ( typeof HTMLCanvasElement !== 'undefined' && source instanceof HTMLCanvasElement ) ||
  43006. ( typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap ) ||
  43007. ( typeof OffscreenCanvas !== 'undefined' && source instanceof OffscreenCanvas ) ) {
  43008. return source;
  43009. }
  43010. return source.data;
  43011. }
  43012. /**
  43013. * A WebGL 2 backend utility module for managing extensions.
  43014. *
  43015. * @private
  43016. */
  43017. class WebGLExtensions {
  43018. /**
  43019. * Constructs a new utility object.
  43020. *
  43021. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43022. */
  43023. constructor( backend ) {
  43024. /**
  43025. * A reference to the WebGL 2 backend.
  43026. *
  43027. * @type {WebGLBackend}
  43028. */
  43029. this.backend = backend;
  43030. /**
  43031. * A reference to the rendering context.
  43032. *
  43033. * @type {WebGL2RenderingContext}
  43034. */
  43035. this.gl = this.backend.gl;
  43036. /**
  43037. * A list with all the supported WebGL extensions.
  43038. *
  43039. * @type {Array<string>}
  43040. */
  43041. this.availableExtensions = this.gl.getSupportedExtensions();
  43042. /**
  43043. * A dictionary with requested WebGL extensions.
  43044. * The key is the name of the extension, the value
  43045. * the requested extension object.
  43046. *
  43047. * @type {Object<string,Object>}
  43048. */
  43049. this.extensions = {};
  43050. }
  43051. /**
  43052. * Returns the extension object for the given extension name.
  43053. *
  43054. * @param {string} name - The extension name.
  43055. * @return {Object} The extension object.
  43056. */
  43057. get( name ) {
  43058. let extension = this.extensions[ name ];
  43059. if ( extension === undefined ) {
  43060. extension = this.gl.getExtension( name );
  43061. this.extensions[ name ] = extension;
  43062. }
  43063. return extension;
  43064. }
  43065. /**
  43066. * Returns `true` if the requested extension is available.
  43067. *
  43068. * @param {string} name - The extension name.
  43069. * @return {boolean} Whether the given extension is available or not.
  43070. */
  43071. has( name ) {
  43072. return this.availableExtensions.includes( name );
  43073. }
  43074. }
  43075. /**
  43076. * A WebGL 2 backend utility module for managing the device's capabilities.
  43077. *
  43078. * @private
  43079. */
  43080. class WebGLCapabilities {
  43081. /**
  43082. * Constructs a new utility object.
  43083. *
  43084. * @param {WebGLBackend} backend - The WebGL 2 backend.
  43085. */
  43086. constructor( backend ) {
  43087. /**
  43088. * A reference to the WebGL 2 backend.
  43089. *
  43090. * @type {WebGLBackend}
  43091. */
  43092. this.backend = backend;
  43093. /**
  43094. * This value holds the cached max anisotropy value.
  43095. *
  43096. * @type {?number}
  43097. * @default null
  43098. */
  43099. this.maxAnisotropy = null;
  43100. }
  43101. /**
  43102. * Returns the maximum anisotropy texture filtering value. This value
  43103. * depends on the device and is reported by the `EXT_texture_filter_anisotropic`
  43104. * WebGL extension.
  43105. *
  43106. * @return {number} The maximum anisotropy texture filtering value.
  43107. */
  43108. getMaxAnisotropy() {
  43109. if ( this.maxAnisotropy !== null ) return this.maxAnisotropy;
  43110. const gl = this.backend.gl;
  43111. const extensions = this.backend.extensions;
  43112. if ( extensions.has( 'EXT_texture_filter_anisotropic' ) === true ) {
  43113. const extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  43114. this.maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  43115. } else {
  43116. this.maxAnisotropy = 0;
  43117. }
  43118. return this.maxAnisotropy;
  43119. }
  43120. }
  43121. const GLFeatureName = {
  43122. 'WEBGL_multi_draw': 'WEBGL_multi_draw',
  43123. 'WEBGL_compressed_texture_astc': 'texture-compression-astc',
  43124. 'WEBGL_compressed_texture_etc': 'texture-compression-etc2',
  43125. 'WEBGL_compressed_texture_etc1': 'texture-compression-etc1',
  43126. 'WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  43127. 'WEBKIT_WEBGL_compressed_texture_pvrtc': 'texture-compression-pvrtc',
  43128. 'WEBGL_compressed_texture_s3tc': 'texture-compression-bc',
  43129. 'EXT_texture_compression_bptc': 'texture-compression-bptc',
  43130. 'EXT_disjoint_timer_query_webgl2': 'timestamp-query',
  43131. 'OVR_multiview2': 'OVR_multiview2'
  43132. };
  43133. class WebGLBufferRenderer {
  43134. constructor( backend ) {
  43135. this.gl = backend.gl;
  43136. this.extensions = backend.extensions;
  43137. this.info = backend.renderer.info;
  43138. this.mode = null;
  43139. this.index = 0;
  43140. this.type = null;
  43141. this.object = null;
  43142. }
  43143. render( start, count ) {
  43144. const { gl, mode, object, type, info, index } = this;
  43145. if ( index !== 0 ) {
  43146. gl.drawElements( mode, count, type, start );
  43147. } else {
  43148. gl.drawArrays( mode, start, count );
  43149. }
  43150. info.update( object, count, 1 );
  43151. }
  43152. renderInstances( start, count, primcount ) {
  43153. const { gl, mode, type, index, object, info } = this;
  43154. if ( primcount === 0 ) return;
  43155. if ( index !== 0 ) {
  43156. gl.drawElementsInstanced( mode, count, type, start, primcount );
  43157. } else {
  43158. gl.drawArraysInstanced( mode, start, count, primcount );
  43159. }
  43160. info.update( object, count, primcount );
  43161. }
  43162. renderMultiDraw( starts, counts, drawCount ) {
  43163. const { extensions, mode, object, info } = this;
  43164. if ( drawCount === 0 ) return;
  43165. const extension = extensions.get( 'WEBGL_multi_draw' );
  43166. if ( extension === null ) {
  43167. for ( let i = 0; i < drawCount; i ++ ) {
  43168. this.render( starts[ i ], counts[ i ] );
  43169. }
  43170. } else {
  43171. if ( this.index !== 0 ) {
  43172. extension.multiDrawElementsWEBGL( mode, counts, 0, this.type, starts, 0, drawCount );
  43173. } else {
  43174. extension.multiDrawArraysWEBGL( mode, starts, 0, counts, 0, drawCount );
  43175. }
  43176. let elementCount = 0;
  43177. for ( let i = 0; i < drawCount; i ++ ) {
  43178. elementCount += counts[ i ];
  43179. }
  43180. info.update( object, elementCount, 1 );
  43181. }
  43182. }
  43183. renderMultiDrawInstances( starts, counts, drawCount, primcount ) {
  43184. const { extensions, mode, object, info } = this;
  43185. if ( drawCount === 0 ) return;
  43186. const extension = extensions.get( 'WEBGL_multi_draw' );
  43187. if ( extension === null ) {
  43188. for ( let i = 0; i < drawCount; i ++ ) {
  43189. this.renderInstances( starts[ i ], counts[ i ], primcount[ i ] );
  43190. }
  43191. } else {
  43192. if ( this.index !== 0 ) {
  43193. extension.multiDrawElementsInstancedWEBGL( mode, counts, 0, this.type, starts, 0, primcount, 0, drawCount );
  43194. } else {
  43195. extension.multiDrawArraysInstancedWEBGL( mode, starts, 0, counts, 0, primcount, 0, drawCount );
  43196. }
  43197. let elementCount = 0;
  43198. for ( let i = 0; i < drawCount; i ++ ) {
  43199. elementCount += counts[ i ] * primcount[ i ];
  43200. }
  43201. info.update( object, elementCount, 1 );
  43202. }
  43203. }
  43204. //
  43205. }
  43206. /**
  43207. * Abstract base class of a timestamp query pool.
  43208. *
  43209. * @abstract
  43210. */
  43211. class TimestampQueryPool {
  43212. /**
  43213. * Creates a new timestamp query pool.
  43214. *
  43215. * @param {number} [maxQueries=256] - Maximum number of queries this pool can hold.
  43216. */
  43217. constructor( maxQueries = 256 ) {
  43218. /**
  43219. * Whether to track timestamps or not.
  43220. *
  43221. * @type {boolean}
  43222. * @default true
  43223. */
  43224. this.trackTimestamp = true;
  43225. /**
  43226. * Maximum number of queries this pool can hold.
  43227. *
  43228. * @type {number}
  43229. * @default 256
  43230. */
  43231. this.maxQueries = maxQueries;
  43232. /**
  43233. * How many queries allocated so far.
  43234. *
  43235. * @type {number}
  43236. * @default 0
  43237. */
  43238. this.currentQueryIndex = 0;
  43239. /**
  43240. * Tracks offsets for different contexts.
  43241. *
  43242. * @type {Map<string, number>}
  43243. */
  43244. this.queryOffsets = new Map();
  43245. /**
  43246. * Whether the pool has been disposed or not.
  43247. *
  43248. * @type {boolean}
  43249. * @default false
  43250. */
  43251. this.isDisposed = false;
  43252. /**
  43253. * TODO
  43254. *
  43255. * @type {number}
  43256. * @default 0
  43257. */
  43258. this.lastValue = 0;
  43259. /**
  43260. * TODO
  43261. *
  43262. * @type {boolean}
  43263. * @default false
  43264. */
  43265. this.pendingResolve = false;
  43266. }
  43267. /**
  43268. * Allocate queries for a specific renderContext.
  43269. *
  43270. * @abstract
  43271. * @param {Object} renderContext - The render context to allocate queries for.
  43272. * @returns {?number}
  43273. */
  43274. allocateQueriesForContext( /* renderContext */ ) {}
  43275. /**
  43276. * Resolve all timestamps and return data (or process them).
  43277. *
  43278. * @abstract
  43279. * @async
  43280. * @returns {Promise<number>|number} The resolved timestamp value.
  43281. */
  43282. async resolveQueriesAsync() {}
  43283. /**
  43284. * Dispose of the query pool.
  43285. *
  43286. * @abstract
  43287. */
  43288. dispose() {}
  43289. }
  43290. /**
  43291. * Manages a pool of WebGL timestamp queries for performance measurement.
  43292. * Handles creation, execution, and resolution of timer queries using WebGL extensions.
  43293. *
  43294. * @augments TimestampQueryPool
  43295. */
  43296. class WebGLTimestampQueryPool extends TimestampQueryPool {
  43297. /**
  43298. * Creates a new WebGL timestamp query pool.
  43299. *
  43300. * @param {WebGLRenderingContext|WebGL2RenderingContext} gl - The WebGL context.
  43301. * @param {string} type - The type identifier for this query pool.
  43302. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  43303. */
  43304. constructor( gl, type, maxQueries = 2048 ) {
  43305. super( maxQueries );
  43306. this.gl = gl;
  43307. this.type = type;
  43308. // Check for timer query extensions
  43309. this.ext = gl.getExtension( 'EXT_disjoint_timer_query_webgl2' ) ||
  43310. gl.getExtension( 'EXT_disjoint_timer_query' );
  43311. if ( ! this.ext ) {
  43312. console.warn( 'EXT_disjoint_timer_query not supported; timestamps will be disabled.' );
  43313. this.trackTimestamp = false;
  43314. return;
  43315. }
  43316. // Create query objects
  43317. this.queries = [];
  43318. for ( let i = 0; i < this.maxQueries; i ++ ) {
  43319. this.queries.push( gl.createQuery() );
  43320. }
  43321. this.activeQuery = null;
  43322. this.queryStates = new Map(); // Track state of each query: 'inactive', 'started', 'ended'
  43323. }
  43324. /**
  43325. * Allocates a pair of queries for a given render context.
  43326. *
  43327. * @param {Object} renderContext - The render context to allocate queries for.
  43328. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  43329. */
  43330. allocateQueriesForContext( renderContext ) {
  43331. if ( ! this.trackTimestamp ) return null;
  43332. // Check if we have enough space for a new query pair
  43333. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  43334. 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() } ).` );
  43335. return null;
  43336. }
  43337. const baseOffset = this.currentQueryIndex;
  43338. this.currentQueryIndex += 2;
  43339. // Initialize query states
  43340. this.queryStates.set( baseOffset, 'inactive' );
  43341. this.queryOffsets.set( renderContext.id, baseOffset );
  43342. return baseOffset;
  43343. }
  43344. /**
  43345. * Begins a timestamp query for the specified render context.
  43346. *
  43347. * @param {Object} renderContext - The render context to begin timing for.
  43348. */
  43349. beginQuery( renderContext ) {
  43350. if ( ! this.trackTimestamp || this.isDisposed ) {
  43351. return;
  43352. }
  43353. const baseOffset = this.queryOffsets.get( renderContext.id );
  43354. if ( baseOffset == null ) {
  43355. return;
  43356. }
  43357. // Don't start a new query if there's an active one
  43358. if ( this.activeQuery !== null ) {
  43359. return;
  43360. }
  43361. const query = this.queries[ baseOffset ];
  43362. if ( ! query ) {
  43363. return;
  43364. }
  43365. try {
  43366. // Only begin if query is inactive
  43367. if ( this.queryStates.get( baseOffset ) === 'inactive' ) {
  43368. this.gl.beginQuery( this.ext.TIME_ELAPSED_EXT, query );
  43369. this.activeQuery = baseOffset;
  43370. this.queryStates.set( baseOffset, 'started' );
  43371. }
  43372. } catch ( error ) {
  43373. console.error( 'Error in beginQuery:', error );
  43374. this.activeQuery = null;
  43375. this.queryStates.set( baseOffset, 'inactive' );
  43376. }
  43377. }
  43378. /**
  43379. * Ends the active timestamp query for the specified render context.
  43380. *
  43381. * @param {Object} renderContext - The render context to end timing for.
  43382. * @param {string} renderContext.id - Unique identifier for the render context.
  43383. */
  43384. endQuery( renderContext ) {
  43385. if ( ! this.trackTimestamp || this.isDisposed ) {
  43386. return;
  43387. }
  43388. const baseOffset = this.queryOffsets.get( renderContext.id );
  43389. if ( baseOffset == null ) {
  43390. return;
  43391. }
  43392. // Only end if this is the active query
  43393. if ( this.activeQuery !== baseOffset ) {
  43394. return;
  43395. }
  43396. try {
  43397. this.gl.endQuery( this.ext.TIME_ELAPSED_EXT );
  43398. this.queryStates.set( baseOffset, 'ended' );
  43399. this.activeQuery = null;
  43400. } catch ( error ) {
  43401. console.error( 'Error in endQuery:', error );
  43402. // Reset state on error
  43403. this.queryStates.set( baseOffset, 'inactive' );
  43404. this.activeQuery = null;
  43405. }
  43406. }
  43407. /**
  43408. * Asynchronously resolves all completed queries and returns the total duration.
  43409. *
  43410. * @async
  43411. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  43412. */
  43413. async resolveQueriesAsync() {
  43414. if ( ! this.trackTimestamp || this.pendingResolve ) {
  43415. return this.lastValue;
  43416. }
  43417. this.pendingResolve = true;
  43418. try {
  43419. // Wait for all ended queries to complete
  43420. const resolvePromises = [];
  43421. for ( const [ baseOffset, state ] of this.queryStates ) {
  43422. if ( state === 'ended' ) {
  43423. const query = this.queries[ baseOffset ];
  43424. resolvePromises.push( this.resolveQuery( query ) );
  43425. }
  43426. }
  43427. if ( resolvePromises.length === 0 ) {
  43428. return this.lastValue;
  43429. }
  43430. const results = await Promise.all( resolvePromises );
  43431. const totalDuration = results.reduce( ( acc, val ) => acc + val, 0 );
  43432. // Store the last valid result
  43433. this.lastValue = totalDuration;
  43434. // Reset states
  43435. this.currentQueryIndex = 0;
  43436. this.queryOffsets.clear();
  43437. this.queryStates.clear();
  43438. this.activeQuery = null;
  43439. return totalDuration;
  43440. } catch ( error ) {
  43441. console.error( 'Error resolving queries:', error );
  43442. return this.lastValue;
  43443. } finally {
  43444. this.pendingResolve = false;
  43445. }
  43446. }
  43447. /**
  43448. * Resolves a single query, checking for completion and disjoint operation.
  43449. *
  43450. * @async
  43451. * @param {WebGLQuery} query - The query object to resolve.
  43452. * @returns {Promise<number>} The elapsed time in milliseconds.
  43453. */
  43454. async resolveQuery( query ) {
  43455. return new Promise( ( resolve ) => {
  43456. if ( this.isDisposed ) {
  43457. resolve( this.lastValue );
  43458. return;
  43459. }
  43460. let timeoutId;
  43461. let isResolved = false;
  43462. const cleanup = () => {
  43463. if ( timeoutId ) {
  43464. clearTimeout( timeoutId );
  43465. timeoutId = null;
  43466. }
  43467. };
  43468. const finalizeResolution = ( value ) => {
  43469. if ( ! isResolved ) {
  43470. isResolved = true;
  43471. cleanup();
  43472. resolve( value );
  43473. }
  43474. };
  43475. const checkQuery = () => {
  43476. if ( this.isDisposed ) {
  43477. finalizeResolution( this.lastValue );
  43478. return;
  43479. }
  43480. try {
  43481. // Check if the GPU timer was disjoint (i.e., timing was unreliable)
  43482. const disjoint = this.gl.getParameter( this.ext.GPU_DISJOINT_EXT );
  43483. if ( disjoint ) {
  43484. finalizeResolution( this.lastValue );
  43485. return;
  43486. }
  43487. const available = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT_AVAILABLE );
  43488. if ( ! available ) {
  43489. timeoutId = setTimeout( checkQuery, 1 );
  43490. return;
  43491. }
  43492. const elapsed = this.gl.getQueryParameter( query, this.gl.QUERY_RESULT );
  43493. resolve( Number( elapsed ) / 1e6 ); // Convert nanoseconds to milliseconds
  43494. } catch ( error ) {
  43495. console.error( 'Error checking query:', error );
  43496. resolve( this.lastValue );
  43497. }
  43498. };
  43499. checkQuery();
  43500. } );
  43501. }
  43502. /**
  43503. * Releases all resources held by this query pool.
  43504. * This includes deleting all query objects and clearing internal state.
  43505. */
  43506. dispose() {
  43507. if ( this.isDisposed ) {
  43508. return;
  43509. }
  43510. this.isDisposed = true;
  43511. if ( ! this.trackTimestamp ) return;
  43512. for ( const query of this.queries ) {
  43513. this.gl.deleteQuery( query );
  43514. }
  43515. this.queries = [];
  43516. this.queryStates.clear();
  43517. this.queryOffsets.clear();
  43518. this.lastValue = 0;
  43519. this.activeQuery = null;
  43520. }
  43521. }
  43522. const _drawingBufferSize = /*@__PURE__*/ new Vector2();
  43523. /**
  43524. * A backend implementation targeting WebGL 2.
  43525. *
  43526. * @private
  43527. * @augments Backend
  43528. */
  43529. class WebGLBackend extends Backend {
  43530. /**
  43531. * WebGLBackend options.
  43532. *
  43533. * @typedef {Object} WebGLBackend~Options
  43534. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  43535. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  43536. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  43537. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  43538. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  43539. * @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.
  43540. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  43541. * @property {WebGL2RenderingContext} [context=undefined] - A WebGL 2 rendering context.
  43542. */
  43543. /**
  43544. * Constructs a new WebGPU backend.
  43545. *
  43546. * @param {WebGLBackend~Options} [parameters] - The configuration parameter.
  43547. */
  43548. constructor( parameters = {} ) {
  43549. super( parameters );
  43550. /**
  43551. * This flag can be used for type testing.
  43552. *
  43553. * @type {boolean}
  43554. * @readonly
  43555. * @default true
  43556. */
  43557. this.isWebGLBackend = true;
  43558. /**
  43559. * A reference to a backend module holding shader attribute-related
  43560. * utility functions.
  43561. *
  43562. * @type {?WebGLAttributeUtils}
  43563. * @default null
  43564. */
  43565. this.attributeUtils = null;
  43566. /**
  43567. * A reference to a backend module holding extension-related
  43568. * utility functions.
  43569. *
  43570. * @type {?WebGLExtensions}
  43571. * @default null
  43572. */
  43573. this.extensions = null;
  43574. /**
  43575. * A reference to a backend module holding capability-related
  43576. * utility functions.
  43577. *
  43578. * @type {?WebGLCapabilities}
  43579. * @default null
  43580. */
  43581. this.capabilities = null;
  43582. /**
  43583. * A reference to a backend module holding texture-related
  43584. * utility functions.
  43585. *
  43586. * @type {?WebGLTextureUtils}
  43587. * @default null
  43588. */
  43589. this.textureUtils = null;
  43590. /**
  43591. * A reference to a backend module holding renderer-related
  43592. * utility functions.
  43593. *
  43594. * @type {?WebGLBufferRenderer}
  43595. * @default null
  43596. */
  43597. this.bufferRenderer = null;
  43598. /**
  43599. * A reference to the rendering context.
  43600. *
  43601. * @type {?WebGL2RenderingContext}
  43602. * @default null
  43603. */
  43604. this.gl = null;
  43605. /**
  43606. * A reference to a backend module holding state-related
  43607. * utility functions.
  43608. *
  43609. * @type {?WebGLState}
  43610. * @default null
  43611. */
  43612. this.state = null;
  43613. /**
  43614. * A reference to a backend module holding common
  43615. * utility functions.
  43616. *
  43617. * @type {?WebGLUtils}
  43618. * @default null
  43619. */
  43620. this.utils = null;
  43621. /**
  43622. * Dictionary for caching VAOs.
  43623. *
  43624. * @type {Object<string,WebGLVertexArrayObject>}
  43625. */
  43626. this.vaoCache = {};
  43627. /**
  43628. * Dictionary for caching transform feedback objects.
  43629. *
  43630. * @type {Object<string,WebGLTransformFeedback>}
  43631. */
  43632. this.transformFeedbackCache = {};
  43633. /**
  43634. * Controls if `gl.RASTERIZER_DISCARD` should be enabled or not.
  43635. * Only relevant when using compute shaders.
  43636. *
  43637. * @type {boolean}
  43638. * @default false
  43639. */
  43640. this.discard = false;
  43641. /**
  43642. * A reference to the `EXT_disjoint_timer_query_webgl2` extension. `null` if the
  43643. * device does not support the extension.
  43644. *
  43645. * @type {?EXTDisjointTimerQueryWebGL2}
  43646. * @default null
  43647. */
  43648. this.disjoint = null;
  43649. /**
  43650. * A reference to the `KHR_parallel_shader_compile` extension. `null` if the
  43651. * device does not support the extension.
  43652. *
  43653. * @type {?KHRParallelShaderCompile}
  43654. * @default null
  43655. */
  43656. this.parallel = null;
  43657. /**
  43658. * A reference to the current render context.
  43659. *
  43660. * @private
  43661. * @type {RenderContext}
  43662. * @default null
  43663. */
  43664. this._currentContext = null;
  43665. /**
  43666. * A unique collection of bindings.
  43667. *
  43668. * @private
  43669. * @type {WeakSet}
  43670. */
  43671. this._knownBindings = new WeakSet();
  43672. /**
  43673. * Whether the device supports framebuffers invalidation or not.
  43674. *
  43675. * @private
  43676. * @type {boolean}
  43677. */
  43678. this._supportsInvalidateFramebuffer = typeof navigator === 'undefined' ? false : /OculusBrowser/g.test( navigator.userAgent );
  43679. /**
  43680. * The target framebuffer when rendering with
  43681. * the WebXR device API.
  43682. *
  43683. * @private
  43684. * @type {WebGLFramebuffer}
  43685. * @default null
  43686. */
  43687. this._xrFramebuffer = null;
  43688. }
  43689. /**
  43690. * Initializes the backend so it is ready for usage.
  43691. *
  43692. * @param {Renderer} renderer - The renderer.
  43693. */
  43694. init( renderer ) {
  43695. super.init( renderer );
  43696. //
  43697. const parameters = this.parameters;
  43698. const contextAttributes = {
  43699. antialias: renderer.samples > 0,
  43700. alpha: true, // always true for performance reasons
  43701. depth: renderer.depth,
  43702. stencil: renderer.stencil
  43703. };
  43704. const glContext = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgl2', contextAttributes );
  43705. function onContextLost( event ) {
  43706. event.preventDefault();
  43707. const contextLossInfo = {
  43708. api: 'WebGL',
  43709. message: event.statusMessage || 'Unknown reason',
  43710. reason: null,
  43711. originalEvent: event
  43712. };
  43713. renderer.onDeviceLost( contextLossInfo );
  43714. }
  43715. this._onContextLost = onContextLost;
  43716. renderer.domElement.addEventListener( 'webglcontextlost', onContextLost, false );
  43717. this.gl = glContext;
  43718. this.extensions = new WebGLExtensions( this );
  43719. this.capabilities = new WebGLCapabilities( this );
  43720. this.attributeUtils = new WebGLAttributeUtils( this );
  43721. this.textureUtils = new WebGLTextureUtils( this );
  43722. this.bufferRenderer = new WebGLBufferRenderer( this );
  43723. this.state = new WebGLState( this );
  43724. this.utils = new WebGLUtils( this );
  43725. this.extensions.get( 'EXT_color_buffer_float' );
  43726. this.extensions.get( 'WEBGL_clip_cull_distance' );
  43727. this.extensions.get( 'OES_texture_float_linear' );
  43728. this.extensions.get( 'EXT_color_buffer_half_float' );
  43729. this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  43730. this.extensions.get( 'WEBGL_render_shared_exponent' );
  43731. this.extensions.get( 'WEBGL_multi_draw' );
  43732. this.extensions.get( 'OVR_multiview2' );
  43733. this.disjoint = this.extensions.get( 'EXT_disjoint_timer_query_webgl2' );
  43734. this.parallel = this.extensions.get( 'KHR_parallel_shader_compile' );
  43735. }
  43736. /**
  43737. * The coordinate system of the backend.
  43738. *
  43739. * @type {number}
  43740. * @readonly
  43741. */
  43742. get coordinateSystem() {
  43743. return WebGLCoordinateSystem;
  43744. }
  43745. /**
  43746. * This method performs a readback operation by moving buffer data from
  43747. * a storage buffer attribute from the GPU to the CPU.
  43748. *
  43749. * @async
  43750. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  43751. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  43752. */
  43753. async getArrayBufferAsync( attribute ) {
  43754. return await this.attributeUtils.getArrayBufferAsync( attribute );
  43755. }
  43756. /**
  43757. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  43758. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  43759. *
  43760. * @async
  43761. * @return {Promise} A Promise that resolves when synchronization has been finished.
  43762. */
  43763. async waitForGPU() {
  43764. await this.utils._clientWaitAsync();
  43765. }
  43766. /**
  43767. * Ensures the backend is XR compatible.
  43768. *
  43769. * @async
  43770. * @return {Promise} A Promise that resolve when the renderer is XR compatible.
  43771. */
  43772. async makeXRCompatible() {
  43773. const attributes = this.gl.getContextAttributes();
  43774. if ( attributes.xrCompatible !== true ) {
  43775. await this.gl.makeXRCompatible();
  43776. }
  43777. }
  43778. /**
  43779. * Sets the XR rendering destination.
  43780. *
  43781. * @param {WebGLFramebuffer} xrFramebuffer - The XR framebuffer.
  43782. */
  43783. setXRTarget( xrFramebuffer ) {
  43784. this._xrFramebuffer = xrFramebuffer;
  43785. }
  43786. /**
  43787. * Configures the given XR render target with external textures.
  43788. *
  43789. * This method is only relevant when using the WebXR Layers API.
  43790. *
  43791. * @param {XRRenderTarget} renderTarget - The XR render target.
  43792. * @param {WebGLTexture} colorTexture - A native color texture.
  43793. * @param {?WebGLTexture} [depthTexture=null] - A native depth texture.
  43794. */
  43795. setXRRenderTargetTextures( renderTarget, colorTexture, depthTexture = null ) {
  43796. const gl = this.gl;
  43797. this.set( renderTarget.texture, { textureGPU: colorTexture, glInternalFormat: gl.RGBA8 } ); // see #24698 why RGBA8 and not SRGB8_ALPHA8 is used
  43798. if ( depthTexture !== null ) {
  43799. const glInternalFormat = renderTarget.stencilBuffer ? gl.DEPTH24_STENCIL8 : gl.DEPTH_COMPONENT24;
  43800. this.set( renderTarget.depthTexture, { textureGPU: depthTexture, glInternalFormat: glInternalFormat } );
  43801. // The multisample_render_to_texture extension doesn't work properly if there
  43802. // are midframe flushes and an external depth texture.
  43803. if ( ( this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true ) && renderTarget._autoAllocateDepthBuffer === true && renderTarget.multiview === false ) {
  43804. console.warn( 'THREE.WebGLBackend: Render-to-texture extension was disabled because an external texture was provided' );
  43805. }
  43806. renderTarget._autoAllocateDepthBuffer = false;
  43807. }
  43808. }
  43809. /**
  43810. * Inits a time stamp query for the given render context.
  43811. *
  43812. * @param {RenderContext} renderContext - The render context.
  43813. */
  43814. initTimestampQuery( renderContext ) {
  43815. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  43816. const type = renderContext.isComputeNode ? 'compute' : 'render';
  43817. if ( ! this.timestampQueryPool[ type ] ) {
  43818. // TODO: Variable maxQueries?
  43819. this.timestampQueryPool[ type ] = new WebGLTimestampQueryPool( this.gl, type, 2048 );
  43820. }
  43821. const timestampQueryPool = this.timestampQueryPool[ type ];
  43822. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  43823. if ( baseOffset !== null ) {
  43824. timestampQueryPool.beginQuery( renderContext );
  43825. }
  43826. }
  43827. // timestamp utils
  43828. /**
  43829. * Prepares the timestamp buffer.
  43830. *
  43831. * @param {RenderContext} renderContext - The render context.
  43832. */
  43833. prepareTimestampBuffer( renderContext ) {
  43834. if ( ! this.disjoint || ! this.trackTimestamp ) return;
  43835. const type = renderContext.isComputeNode ? 'compute' : 'render';
  43836. const timestampQueryPool = this.timestampQueryPool[ type ];
  43837. timestampQueryPool.endQuery( renderContext );
  43838. }
  43839. /**
  43840. * Returns the backend's rendering context.
  43841. *
  43842. * @return {WebGL2RenderingContext} The rendering context.
  43843. */
  43844. getContext() {
  43845. return this.gl;
  43846. }
  43847. /**
  43848. * This method is executed at the beginning of a render call and prepares
  43849. * the WebGL state for upcoming render calls
  43850. *
  43851. * @param {RenderContext} renderContext - The render context.
  43852. */
  43853. beginRender( renderContext ) {
  43854. const { state } = this;
  43855. const renderContextData = this.get( renderContext );
  43856. //
  43857. if ( renderContext.viewport ) {
  43858. this.updateViewport( renderContext );
  43859. } else {
  43860. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  43861. state.viewport( 0, 0, width, height );
  43862. }
  43863. if ( renderContext.scissor ) {
  43864. const { x, y, width, height } = renderContext.scissorValue;
  43865. state.scissor( x, renderContext.height - height - y, width, height );
  43866. }
  43867. //
  43868. this.initTimestampQuery( renderContext );
  43869. renderContextData.previousContext = this._currentContext;
  43870. this._currentContext = renderContext;
  43871. this._setFramebuffer( renderContext );
  43872. this.clear( renderContext.clearColor, renderContext.clearDepth, renderContext.clearStencil, renderContext, false );
  43873. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43874. if ( occlusionQueryCount > 0 ) {
  43875. // Get a reference to the array of objects with queries. The renderContextData property
  43876. // can be changed by another render pass before the async reading of all previous queries complete
  43877. renderContextData.currentOcclusionQueries = renderContextData.occlusionQueries;
  43878. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  43879. renderContextData.lastOcclusionObject = null;
  43880. renderContextData.occlusionQueries = new Array( occlusionQueryCount );
  43881. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  43882. renderContextData.occlusionQueryIndex = 0;
  43883. }
  43884. }
  43885. /**
  43886. * This method is executed at the end of a render call and finalizes work
  43887. * after draw calls.
  43888. *
  43889. * @param {RenderContext} renderContext - The render context.
  43890. */
  43891. finishRender( renderContext ) {
  43892. const { gl, state } = this;
  43893. const renderContextData = this.get( renderContext );
  43894. const previousContext = renderContextData.previousContext;
  43895. state.resetVertexState();
  43896. const occlusionQueryCount = renderContext.occlusionQueryCount;
  43897. if ( occlusionQueryCount > 0 ) {
  43898. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  43899. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  43900. }
  43901. this.resolveOccludedAsync( renderContext );
  43902. }
  43903. const textures = renderContext.textures;
  43904. if ( textures !== null ) {
  43905. for ( let i = 0; i < textures.length; i ++ ) {
  43906. const texture = textures[ i ];
  43907. if ( texture.generateMipmaps ) {
  43908. this.generateMipmaps( texture );
  43909. }
  43910. }
  43911. }
  43912. this._currentContext = previousContext;
  43913. const renderTarget = renderContext.renderTarget;
  43914. if ( renderContext.textures !== null && renderTarget ) {
  43915. const renderTargetContextData = this.get( renderTarget );
  43916. if ( renderTarget.samples > 0 && this._useMultisampledExtension( renderTarget ) === false ) {
  43917. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  43918. let mask = gl.COLOR_BUFFER_BIT;
  43919. if ( renderTarget.resolveDepthBuffer ) {
  43920. if ( renderTarget.depthBuffer ) mask |= gl.DEPTH_BUFFER_BIT;
  43921. if ( renderTarget.stencilBuffer && renderTarget.resolveStencilBuffer ) mask |= gl.STENCIL_BUFFER_BIT;
  43922. }
  43923. const msaaFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  43924. const msaaRenderbuffers = renderTargetContextData.msaaRenderbuffers;
  43925. const textures = renderContext.textures;
  43926. const isMRT = textures.length > 1;
  43927. state.bindFramebuffer( gl.READ_FRAMEBUFFER, msaaFrameBuffer );
  43928. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  43929. if ( isMRT ) {
  43930. // blitFramebuffer() can only copy/resolve the first color attachment of a framebuffer. When using MRT,
  43931. // the engine temporarily removes all attachments and then configures each attachment for the resolve.
  43932. for ( let i = 0; i < textures.length; i ++ ) {
  43933. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, null );
  43934. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, null, 0 );
  43935. }
  43936. }
  43937. for ( let i = 0; i < textures.length; i ++ ) {
  43938. if ( isMRT ) {
  43939. // configure attachment for resolve
  43940. const { textureGPU } = this.get( textures[ i ] );
  43941. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  43942. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureGPU, 0 );
  43943. }
  43944. if ( renderContext.scissor ) {
  43945. const { x, y, width, height } = renderContext.scissorValue;
  43946. const viewY = renderContext.height - height - y;
  43947. gl.blitFramebuffer( x, viewY, x + width, viewY + height, x, viewY, x + width, viewY + height, mask, gl.NEAREST );
  43948. if ( this._supportsInvalidateFramebuffer === true ) {
  43949. gl.invalidateSubFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray, x, viewY, width, height );
  43950. }
  43951. } else {
  43952. gl.blitFramebuffer( 0, 0, renderContext.width, renderContext.height, 0, 0, renderContext.width, renderContext.height, mask, gl.NEAREST );
  43953. if ( this._supportsInvalidateFramebuffer === true ) {
  43954. gl.invalidateFramebuffer( gl.READ_FRAMEBUFFER, renderTargetContextData.invalidationArray );
  43955. }
  43956. }
  43957. }
  43958. if ( isMRT ) {
  43959. // restore attachments
  43960. for ( let i = 0; i < textures.length; i ++ ) {
  43961. const { textureGPU } = this.get( textures[ i ] );
  43962. gl.framebufferRenderbuffer( gl.READ_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  43963. gl.framebufferTexture2D( gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.TEXTURE_2D, textureGPU, 0 );
  43964. }
  43965. }
  43966. } else if ( renderTarget.resolveDepthBuffer === false && renderTargetContextData.framebuffers ) {
  43967. const fb = renderTargetContextData.framebuffers[ renderContext.getCacheKey() ];
  43968. state.bindFramebuffer( gl.DRAW_FRAMEBUFFER, fb );
  43969. gl.invalidateFramebuffer( gl.DRAW_FRAMEBUFFER, renderTargetContextData.depthInvalidationArray );
  43970. }
  43971. }
  43972. if ( previousContext !== null ) {
  43973. this._setFramebuffer( previousContext );
  43974. if ( previousContext.viewport ) {
  43975. this.updateViewport( previousContext );
  43976. } else {
  43977. const { width, height } = this.getDrawingBufferSize( _drawingBufferSize );
  43978. state.viewport( 0, 0, width, height );
  43979. }
  43980. }
  43981. this.prepareTimestampBuffer( renderContext );
  43982. }
  43983. /**
  43984. * This method processes the result of occlusion queries and writes it
  43985. * into render context data.
  43986. *
  43987. * @async
  43988. * @param {RenderContext} renderContext - The render context.
  43989. */
  43990. resolveOccludedAsync( renderContext ) {
  43991. const renderContextData = this.get( renderContext );
  43992. // handle occlusion query results
  43993. const { currentOcclusionQueries, currentOcclusionQueryObjects } = renderContextData;
  43994. if ( currentOcclusionQueries && currentOcclusionQueryObjects ) {
  43995. const occluded = new WeakSet();
  43996. const { gl } = this;
  43997. renderContextData.currentOcclusionQueryObjects = null;
  43998. renderContextData.currentOcclusionQueries = null;
  43999. const check = () => {
  44000. let completed = 0;
  44001. // check all queries and requeue as appropriate
  44002. for ( let i = 0; i < currentOcclusionQueries.length; i ++ ) {
  44003. const query = currentOcclusionQueries[ i ];
  44004. if ( query === null ) continue;
  44005. if ( gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE ) ) {
  44006. if ( gl.getQueryParameter( query, gl.QUERY_RESULT ) === 0 ) occluded.add( currentOcclusionQueryObjects[ i ] );
  44007. currentOcclusionQueries[ i ] = null;
  44008. gl.deleteQuery( query );
  44009. completed ++;
  44010. }
  44011. }
  44012. if ( completed < currentOcclusionQueries.length ) {
  44013. requestAnimationFrame( check );
  44014. } else {
  44015. renderContextData.occluded = occluded;
  44016. }
  44017. };
  44018. check();
  44019. }
  44020. }
  44021. /**
  44022. * Returns `true` if the given 3D object is fully occluded by other
  44023. * 3D objects in the scene.
  44024. *
  44025. * @param {RenderContext} renderContext - The render context.
  44026. * @param {Object3D} object - The 3D object to test.
  44027. * @return {boolean} Whether the 3D object is fully occluded or not.
  44028. */
  44029. isOccluded( renderContext, object ) {
  44030. const renderContextData = this.get( renderContext );
  44031. return renderContextData.occluded && renderContextData.occluded.has( object );
  44032. }
  44033. /**
  44034. * Updates the viewport with the values from the given render context.
  44035. *
  44036. * @param {RenderContext} renderContext - The render context.
  44037. */
  44038. updateViewport( renderContext ) {
  44039. const { state } = this;
  44040. const { x, y, width, height } = renderContext.viewportValue;
  44041. state.viewport( x, renderContext.height - height - y, width, height );
  44042. }
  44043. /**
  44044. * Defines the scissor test.
  44045. *
  44046. * @param {boolean} boolean - Whether the scissor test should be enabled or not.
  44047. */
  44048. setScissorTest( boolean ) {
  44049. const state = this.state;
  44050. state.setScissorTest( boolean );
  44051. }
  44052. /**
  44053. * Returns the clear color and alpha into a single
  44054. * color object.
  44055. *
  44056. * @return {Color4} The clear color.
  44057. */
  44058. getClearColor() {
  44059. const clearColor = super.getClearColor();
  44060. // Since the canvas is always created with alpha: true,
  44061. // WebGL must always premultiply the clear color.
  44062. clearColor.r *= clearColor.a;
  44063. clearColor.g *= clearColor.a;
  44064. clearColor.b *= clearColor.a;
  44065. return clearColor;
  44066. }
  44067. /**
  44068. * Performs a clear operation.
  44069. *
  44070. * @param {boolean} color - Whether the color buffer should be cleared or not.
  44071. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  44072. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  44073. * @param {?Object} [descriptor=null] - The render context of the current set render target.
  44074. * @param {boolean} [setFrameBuffer=true] - TODO.
  44075. */
  44076. clear( color, depth, stencil, descriptor = null, setFrameBuffer = true ) {
  44077. const { gl, renderer } = this;
  44078. if ( descriptor === null ) {
  44079. const clearColor = this.getClearColor();
  44080. descriptor = {
  44081. textures: null,
  44082. clearColorValue: clearColor
  44083. };
  44084. }
  44085. //
  44086. let clear = 0;
  44087. if ( color ) clear |= gl.COLOR_BUFFER_BIT;
  44088. if ( depth ) clear |= gl.DEPTH_BUFFER_BIT;
  44089. if ( stencil ) clear |= gl.STENCIL_BUFFER_BIT;
  44090. if ( clear !== 0 ) {
  44091. let clearColor;
  44092. if ( descriptor.clearColorValue ) {
  44093. clearColor = descriptor.clearColorValue;
  44094. } else {
  44095. clearColor = this.getClearColor();
  44096. }
  44097. const clearDepth = renderer.getClearDepth();
  44098. const clearStencil = renderer.getClearStencil();
  44099. if ( depth ) this.state.setDepthMask( true );
  44100. if ( descriptor.textures === null ) {
  44101. gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearColor.a );
  44102. gl.clear( clear );
  44103. } else {
  44104. if ( setFrameBuffer ) this._setFramebuffer( descriptor );
  44105. if ( color ) {
  44106. for ( let i = 0; i < descriptor.textures.length; i ++ ) {
  44107. if ( i === 0 ) {
  44108. gl.clearBufferfv( gl.COLOR, i, [ clearColor.r, clearColor.g, clearColor.b, clearColor.a ] );
  44109. } else {
  44110. gl.clearBufferfv( gl.COLOR, i, [ 0, 0, 0, 1 ] );
  44111. }
  44112. }
  44113. }
  44114. if ( depth && stencil ) {
  44115. gl.clearBufferfi( gl.DEPTH_STENCIL, 0, clearDepth, clearStencil );
  44116. } else if ( depth ) {
  44117. gl.clearBufferfv( gl.DEPTH, 0, [ clearDepth ] );
  44118. } else if ( stencil ) {
  44119. gl.clearBufferiv( gl.STENCIL, 0, [ clearStencil ] );
  44120. }
  44121. }
  44122. }
  44123. }
  44124. /**
  44125. * This method is executed at the beginning of a compute call and
  44126. * prepares the state for upcoming compute tasks.
  44127. *
  44128. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  44129. */
  44130. beginCompute( computeGroup ) {
  44131. const { state, gl } = this;
  44132. state.bindFramebuffer( gl.FRAMEBUFFER, null );
  44133. this.initTimestampQuery( computeGroup );
  44134. }
  44135. /**
  44136. * Executes a compute command for the given compute node.
  44137. *
  44138. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  44139. * @param {Node} computeNode - The compute node.
  44140. * @param {Array<BindGroup>} bindings - The bindings.
  44141. * @param {ComputePipeline} pipeline - The compute pipeline.
  44142. */
  44143. compute( computeGroup, computeNode, bindings, pipeline ) {
  44144. const { state, gl } = this;
  44145. if ( this.discard === false ) {
  44146. // required here to handle async behaviour of render.compute()
  44147. gl.enable( gl.RASTERIZER_DISCARD );
  44148. this.discard = true;
  44149. }
  44150. const { programGPU, transformBuffers, attributes } = this.get( pipeline );
  44151. const vaoKey = this._getVaoKey( attributes );
  44152. const vaoGPU = this.vaoCache[ vaoKey ];
  44153. if ( vaoGPU === undefined ) {
  44154. this.vaoCache[ vaoKey ] = this._createVao( attributes );
  44155. } else {
  44156. state.setVertexState( vaoGPU );
  44157. }
  44158. state.useProgram( programGPU );
  44159. this._bindUniforms( bindings );
  44160. const transformFeedbackGPU = this._getTransformFeedback( transformBuffers );
  44161. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  44162. gl.beginTransformFeedback( gl.POINTS );
  44163. if ( attributes[ 0 ].isStorageInstancedBufferAttribute ) {
  44164. gl.drawArraysInstanced( gl.POINTS, 0, 1, computeNode.count );
  44165. } else {
  44166. gl.drawArrays( gl.POINTS, 0, computeNode.count );
  44167. }
  44168. gl.endTransformFeedback();
  44169. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  44170. // switch active buffers
  44171. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  44172. const dualAttributeData = transformBuffers[ i ];
  44173. if ( dualAttributeData.pbo && this.has( dualAttributeData.pbo ) ) {
  44174. this.textureUtils.copyBufferToTexture( dualAttributeData.transformBuffer, dualAttributeData.pbo );
  44175. }
  44176. dualAttributeData.switchBuffers();
  44177. }
  44178. }
  44179. /**
  44180. * This method is executed at the end of a compute call and
  44181. * finalizes work after compute tasks.
  44182. *
  44183. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  44184. */
  44185. finishCompute( computeGroup ) {
  44186. const gl = this.gl;
  44187. this.discard = false;
  44188. gl.disable( gl.RASTERIZER_DISCARD );
  44189. this.prepareTimestampBuffer( computeGroup );
  44190. if ( this._currentContext ) {
  44191. this._setFramebuffer( this._currentContext );
  44192. }
  44193. }
  44194. /**
  44195. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  44196. *
  44197. * @param {RenderContext} renderContext - The render context.
  44198. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  44199. *
  44200. * @private
  44201. */
  44202. _isRenderCameraDepthArray( renderContext ) {
  44203. return renderContext.depthTexture && renderContext.depthTexture.isArrayTexture && renderContext.camera.isArrayCamera;
  44204. }
  44205. /**
  44206. * Executes a draw command for the given render object.
  44207. *
  44208. * @param {RenderObject} renderObject - The render object to draw.
  44209. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  44210. */
  44211. draw( renderObject/*, info*/ ) {
  44212. const { object, pipeline, material, context, hardwareClippingPlanes } = renderObject;
  44213. const { programGPU } = this.get( pipeline );
  44214. const { gl, state } = this;
  44215. const contextData = this.get( context );
  44216. const drawParams = renderObject.getDrawParameters();
  44217. if ( drawParams === null ) return;
  44218. //
  44219. this._bindUniforms( renderObject.getBindings() );
  44220. const frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  44221. state.setMaterial( material, frontFaceCW, hardwareClippingPlanes );
  44222. state.useProgram( programGPU );
  44223. // vertex state
  44224. const attributes = renderObject.getAttributes();
  44225. const attributesData = this.get( attributes );
  44226. let vaoGPU = attributesData.vaoGPU;
  44227. if ( vaoGPU === undefined ) {
  44228. const vaoKey = this._getVaoKey( attributes );
  44229. vaoGPU = this.vaoCache[ vaoKey ];
  44230. if ( vaoGPU === undefined ) {
  44231. vaoGPU = this._createVao( attributes );
  44232. this.vaoCache[ vaoKey ] = vaoGPU;
  44233. attributesData.vaoGPU = vaoGPU;
  44234. }
  44235. }
  44236. const index = renderObject.getIndex();
  44237. const indexGPU = ( index !== null ) ? this.get( index ).bufferGPU : null;
  44238. state.setVertexState( vaoGPU, indexGPU );
  44239. //
  44240. const lastObject = contextData.lastOcclusionObject;
  44241. if ( lastObject !== object && lastObject !== undefined ) {
  44242. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  44243. gl.endQuery( gl.ANY_SAMPLES_PASSED );
  44244. contextData.occlusionQueryIndex ++;
  44245. }
  44246. if ( object.occlusionTest === true ) {
  44247. const query = gl.createQuery();
  44248. gl.beginQuery( gl.ANY_SAMPLES_PASSED, query );
  44249. contextData.occlusionQueries[ contextData.occlusionQueryIndex ] = query;
  44250. contextData.occlusionQueryObjects[ contextData.occlusionQueryIndex ] = object;
  44251. }
  44252. contextData.lastOcclusionObject = object;
  44253. }
  44254. //
  44255. const renderer = this.bufferRenderer;
  44256. if ( object.isPoints ) renderer.mode = gl.POINTS;
  44257. else if ( object.isLineSegments ) renderer.mode = gl.LINES;
  44258. else if ( object.isLine ) renderer.mode = gl.LINE_STRIP;
  44259. else if ( object.isLineLoop ) renderer.mode = gl.LINE_LOOP;
  44260. else {
  44261. if ( material.wireframe === true ) {
  44262. state.setLineWidth( material.wireframeLinewidth * this.renderer.getPixelRatio() );
  44263. renderer.mode = gl.LINES;
  44264. } else {
  44265. renderer.mode = gl.TRIANGLES;
  44266. }
  44267. }
  44268. //
  44269. const { vertexCount, instanceCount } = drawParams;
  44270. let { firstVertex } = drawParams;
  44271. renderer.object = object;
  44272. if ( index !== null ) {
  44273. firstVertex *= index.array.BYTES_PER_ELEMENT;
  44274. const indexData = this.get( index );
  44275. renderer.index = index.count;
  44276. renderer.type = indexData.type;
  44277. } else {
  44278. renderer.index = 0;
  44279. }
  44280. const draw = () => {
  44281. if ( object.isBatchedMesh ) {
  44282. if ( object._multiDrawInstances !== null ) {
  44283. // @deprecated, r174
  44284. warnOnce( 'THREE.WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  44285. renderer.renderMultiDrawInstances( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount, object._multiDrawInstances );
  44286. } else if ( ! this.hasFeature( 'WEBGL_multi_draw' ) ) {
  44287. warnOnce( 'THREE.WebGLRenderer: WEBGL_multi_draw not supported.' );
  44288. } else {
  44289. renderer.renderMultiDraw( object._multiDrawStarts, object._multiDrawCounts, object._multiDrawCount );
  44290. }
  44291. } else if ( instanceCount > 1 ) {
  44292. renderer.renderInstances( firstVertex, vertexCount, instanceCount );
  44293. } else {
  44294. renderer.render( firstVertex, vertexCount );
  44295. }
  44296. };
  44297. if ( renderObject.camera.isArrayCamera === true && renderObject.camera.cameras.length > 0 && renderObject.camera.isMultiViewCamera === false ) {
  44298. const cameraData = this.get( renderObject.camera );
  44299. const cameras = renderObject.camera.cameras;
  44300. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' ).bindings[ 0 ];
  44301. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  44302. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  44303. const indexesGPU = [];
  44304. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  44305. const bufferGPU = gl.createBuffer();
  44306. data[ 0 ] = i;
  44307. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  44308. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.STATIC_DRAW );
  44309. indexesGPU.push( bufferGPU );
  44310. }
  44311. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  44312. }
  44313. const cameraIndexData = this.get( cameraIndex );
  44314. const pixelRatio = this.renderer.getPixelRatio();
  44315. const renderTarget = this._currentContext.renderTarget;
  44316. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( this._currentContext );
  44317. const prevActiveCubeFace = this._currentContext.activeCubeFace;
  44318. if ( isRenderCameraDepthArray ) {
  44319. // Clear the depth texture
  44320. const textureData = this.get( renderTarget.depthTexture );
  44321. if ( textureData.clearedRenderId !== this.renderer._nodes.nodeFrame.renderId ) {
  44322. textureData.clearedRenderId = this.renderer._nodes.nodeFrame.renderId;
  44323. const { stencilBuffer } = renderTarget;
  44324. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  44325. this.renderer._activeCubeFace = i;
  44326. this._currentContext.activeCubeFace = i;
  44327. this._setFramebuffer( this._currentContext );
  44328. this.clear( false, true, stencilBuffer, this._currentContext, false );
  44329. }
  44330. this.renderer._activeCubeFace = prevActiveCubeFace;
  44331. this._currentContext.activeCubeFace = prevActiveCubeFace;
  44332. }
  44333. }
  44334. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  44335. const subCamera = cameras[ i ];
  44336. if ( object.layers.test( subCamera.layers ) ) {
  44337. if ( isRenderCameraDepthArray ) {
  44338. // Update the active layer
  44339. this.renderer._activeCubeFace = i;
  44340. this._currentContext.activeCubeFace = i;
  44341. this._setFramebuffer( this._currentContext );
  44342. }
  44343. const vp = subCamera.viewport;
  44344. if ( vp !== undefined ) {
  44345. const x = vp.x * pixelRatio;
  44346. const y = vp.y * pixelRatio;
  44347. const width = vp.width * pixelRatio;
  44348. const height = vp.height * pixelRatio;
  44349. state.viewport(
  44350. Math.floor( x ),
  44351. Math.floor( renderObject.context.height - height - y ),
  44352. Math.floor( width ),
  44353. Math.floor( height )
  44354. );
  44355. }
  44356. state.bindBufferBase( gl.UNIFORM_BUFFER, cameraIndexData.index, cameraData.indexesGPU[ i ] );
  44357. draw();
  44358. }
  44359. this._currentContext.activeCubeFace = prevActiveCubeFace;
  44360. this.renderer._activeCubeFace = prevActiveCubeFace;
  44361. }
  44362. } else {
  44363. draw();
  44364. }
  44365. }
  44366. /**
  44367. * Explain why always null is returned.
  44368. *
  44369. * @param {RenderObject} renderObject - The render object.
  44370. * @return {boolean} Whether the render pipeline requires an update or not.
  44371. */
  44372. needsRenderUpdate( /*renderObject*/ ) {
  44373. return false;
  44374. }
  44375. /**
  44376. * Explain why no cache key is computed.
  44377. *
  44378. * @param {RenderObject} renderObject - The render object.
  44379. * @return {string} The cache key.
  44380. */
  44381. getRenderCacheKey( /*renderObject*/ ) {
  44382. return '';
  44383. }
  44384. // textures
  44385. /**
  44386. * Creates a default texture for the given texture that can be used
  44387. * as a placeholder until the actual texture is ready for usage.
  44388. *
  44389. * @param {Texture} texture - The texture to create a default texture for.
  44390. */
  44391. createDefaultTexture( texture ) {
  44392. this.textureUtils.createDefaultTexture( texture );
  44393. }
  44394. /**
  44395. * Defines a texture on the GPU for the given texture object.
  44396. *
  44397. * @param {Texture} texture - The texture.
  44398. * @param {Object} [options={}] - Optional configuration parameter.
  44399. */
  44400. createTexture( texture, options ) {
  44401. this.textureUtils.createTexture( texture, options );
  44402. }
  44403. /**
  44404. * Uploads the updated texture data to the GPU.
  44405. *
  44406. * @param {Texture} texture - The texture.
  44407. * @param {Object} [options={}] - Optional configuration parameter.
  44408. */
  44409. updateTexture( texture, options ) {
  44410. this.textureUtils.updateTexture( texture, options );
  44411. }
  44412. /**
  44413. * Generates mipmaps for the given texture.
  44414. *
  44415. * @param {Texture} texture - The texture.
  44416. */
  44417. generateMipmaps( texture ) {
  44418. this.textureUtils.generateMipmaps( texture );
  44419. }
  44420. /**
  44421. * Destroys the GPU data for the given texture object.
  44422. *
  44423. * @param {Texture} texture - The texture.
  44424. */
  44425. destroyTexture( texture ) {
  44426. this.textureUtils.destroyTexture( texture );
  44427. }
  44428. /**
  44429. * Returns texture data as a typed array.
  44430. *
  44431. * @async
  44432. * @param {Texture} texture - The texture to copy.
  44433. * @param {number} x - The x coordinate of the copy origin.
  44434. * @param {number} y - The y coordinate of the copy origin.
  44435. * @param {number} width - The width of the copy.
  44436. * @param {number} height - The height of the copy.
  44437. * @param {number} faceIndex - The face index.
  44438. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  44439. */
  44440. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  44441. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  44442. }
  44443. /**
  44444. * This method does nothing since WebGL 2 has no concept of samplers.
  44445. *
  44446. * @param {Texture} texture - The texture to create the sampler for.
  44447. */
  44448. createSampler( /*texture*/ ) {
  44449. //console.warn( 'Abstract class.' );
  44450. }
  44451. /**
  44452. * This method does nothing since WebGL 2 has no concept of samplers.
  44453. *
  44454. * @param {Texture} texture - The texture to destroy the sampler for.
  44455. */
  44456. destroySampler( /*texture*/ ) {}
  44457. // node builder
  44458. /**
  44459. * Returns a node builder for the given render object.
  44460. *
  44461. * @param {RenderObject} object - The render object.
  44462. * @param {Renderer} renderer - The renderer.
  44463. * @return {GLSLNodeBuilder} The node builder.
  44464. */
  44465. createNodeBuilder( object, renderer ) {
  44466. return new GLSLNodeBuilder( object, renderer );
  44467. }
  44468. // program
  44469. /**
  44470. * Creates a shader program from the given programmable stage.
  44471. *
  44472. * @param {ProgrammableStage} program - The programmable stage.
  44473. */
  44474. createProgram( program ) {
  44475. const gl = this.gl;
  44476. const { stage, code } = program;
  44477. const shader = stage === 'fragment' ? gl.createShader( gl.FRAGMENT_SHADER ) : gl.createShader( gl.VERTEX_SHADER );
  44478. gl.shaderSource( shader, code );
  44479. gl.compileShader( shader );
  44480. this.set( program, {
  44481. shaderGPU: shader
  44482. } );
  44483. }
  44484. /**
  44485. * Destroys the shader program of the given programmable stage.
  44486. *
  44487. * @param {ProgrammableStage} program - The programmable stage.
  44488. */
  44489. destroyProgram( program ) {
  44490. this.delete( program );
  44491. }
  44492. /**
  44493. * Creates a render pipeline for the given render object.
  44494. *
  44495. * @param {RenderObject} renderObject - The render object.
  44496. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  44497. */
  44498. createRenderPipeline( renderObject, promises ) {
  44499. const gl = this.gl;
  44500. const pipeline = renderObject.pipeline;
  44501. // Program
  44502. const { fragmentProgram, vertexProgram } = pipeline;
  44503. const programGPU = gl.createProgram();
  44504. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  44505. const vertexShader = this.get( vertexProgram ).shaderGPU;
  44506. gl.attachShader( programGPU, fragmentShader );
  44507. gl.attachShader( programGPU, vertexShader );
  44508. gl.linkProgram( programGPU );
  44509. this.set( pipeline, {
  44510. programGPU,
  44511. fragmentShader,
  44512. vertexShader
  44513. } );
  44514. if ( promises !== null && this.parallel ) {
  44515. const p = new Promise( ( resolve /*, reject*/ ) => {
  44516. const parallel = this.parallel;
  44517. const checkStatus = () => {
  44518. if ( gl.getProgramParameter( programGPU, parallel.COMPLETION_STATUS_KHR ) ) {
  44519. this._completeCompile( renderObject, pipeline );
  44520. resolve();
  44521. } else {
  44522. requestAnimationFrame( checkStatus );
  44523. }
  44524. };
  44525. checkStatus();
  44526. } );
  44527. promises.push( p );
  44528. return;
  44529. }
  44530. this._completeCompile( renderObject, pipeline );
  44531. }
  44532. /**
  44533. * Formats the source code of error messages.
  44534. *
  44535. * @private
  44536. * @param {string} string - The code.
  44537. * @param {number} errorLine - The error line.
  44538. * @return {string} The formatted code.
  44539. */
  44540. _handleSource( string, errorLine ) {
  44541. const lines = string.split( '\n' );
  44542. const lines2 = [];
  44543. const from = Math.max( errorLine - 6, 0 );
  44544. const to = Math.min( errorLine + 6, lines.length );
  44545. for ( let i = from; i < to; i ++ ) {
  44546. const line = i + 1;
  44547. lines2.push( `${line === errorLine ? '>' : ' '} ${line}: ${lines[ i ]}` );
  44548. }
  44549. return lines2.join( '\n' );
  44550. }
  44551. /**
  44552. * Gets the shader compilation errors from the info log.
  44553. *
  44554. * @private
  44555. * @param {WebGL2RenderingContext} gl - The rendering context.
  44556. * @param {WebGLShader} shader - The WebGL shader object.
  44557. * @param {string} type - The shader type.
  44558. * @return {string} The shader errors.
  44559. */
  44560. _getShaderErrors( gl, shader, type ) {
  44561. const status = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
  44562. const errors = gl.getShaderInfoLog( shader ).trim();
  44563. if ( status && errors === '' ) return '';
  44564. const errorMatches = /ERROR: 0:(\d+)/.exec( errors );
  44565. if ( errorMatches ) {
  44566. const errorLine = parseInt( errorMatches[ 1 ] );
  44567. return type.toUpperCase() + '\n\n' + errors + '\n\n' + this._handleSource( gl.getShaderSource( shader ), errorLine );
  44568. } else {
  44569. return errors;
  44570. }
  44571. }
  44572. /**
  44573. * Logs shader compilation errors.
  44574. *
  44575. * @private
  44576. * @param {WebGLProgram} programGPU - The WebGL program.
  44577. * @param {WebGLShader} glFragmentShader - The fragment shader as a native WebGL shader object.
  44578. * @param {WebGLShader} glVertexShader - The vertex shader as a native WebGL shader object.
  44579. */
  44580. _logProgramError( programGPU, glFragmentShader, glVertexShader ) {
  44581. if ( this.renderer.debug.checkShaderErrors ) {
  44582. const gl = this.gl;
  44583. const programLog = gl.getProgramInfoLog( programGPU ).trim();
  44584. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44585. if ( typeof this.renderer.debug.onShaderError === 'function' ) {
  44586. this.renderer.debug.onShaderError( gl, programGPU, glVertexShader, glFragmentShader );
  44587. } else {
  44588. // default error reporting
  44589. const vertexErrors = this._getShaderErrors( gl, glVertexShader, 'vertex' );
  44590. const fragmentErrors = this._getShaderErrors( gl, glFragmentShader, 'fragment' );
  44591. console.error(
  44592. 'THREE.WebGLProgram: Shader Error ' + gl.getError() + ' - ' +
  44593. 'VALIDATE_STATUS ' + gl.getProgramParameter( programGPU, gl.VALIDATE_STATUS ) + '\n\n' +
  44594. 'Program Info Log: ' + programLog + '\n' +
  44595. vertexErrors + '\n' +
  44596. fragmentErrors
  44597. );
  44598. }
  44599. } else if ( programLog !== '' ) {
  44600. console.warn( 'THREE.WebGLProgram: Program Info Log:', programLog );
  44601. }
  44602. }
  44603. }
  44604. /**
  44605. * Completes the shader program setup for the given render object.
  44606. *
  44607. * @private
  44608. * @param {RenderObject} renderObject - The render object.
  44609. * @param {RenderPipeline} pipeline - The render pipeline.
  44610. */
  44611. _completeCompile( renderObject, pipeline ) {
  44612. const { state, gl } = this;
  44613. const pipelineData = this.get( pipeline );
  44614. const { programGPU, fragmentShader, vertexShader } = pipelineData;
  44615. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44616. this._logProgramError( programGPU, fragmentShader, vertexShader );
  44617. }
  44618. state.useProgram( programGPU );
  44619. // Bindings
  44620. const bindings = renderObject.getBindings();
  44621. this._setupBindings( bindings, programGPU );
  44622. //
  44623. this.set( pipeline, {
  44624. programGPU
  44625. } );
  44626. }
  44627. /**
  44628. * Creates a compute pipeline for the given compute node.
  44629. *
  44630. * @param {ComputePipeline} computePipeline - The compute pipeline.
  44631. * @param {Array<BindGroup>} bindings - The bindings.
  44632. */
  44633. createComputePipeline( computePipeline, bindings ) {
  44634. const { state, gl } = this;
  44635. // Program
  44636. const fragmentProgram = {
  44637. stage: 'fragment',
  44638. code: '#version 300 es\nprecision highp float;\nvoid main() {}'
  44639. };
  44640. this.createProgram( fragmentProgram );
  44641. const { computeProgram } = computePipeline;
  44642. const programGPU = gl.createProgram();
  44643. const fragmentShader = this.get( fragmentProgram ).shaderGPU;
  44644. const vertexShader = this.get( computeProgram ).shaderGPU;
  44645. const transforms = computeProgram.transforms;
  44646. const transformVaryingNames = [];
  44647. const transformAttributeNodes = [];
  44648. for ( let i = 0; i < transforms.length; i ++ ) {
  44649. const transform = transforms[ i ];
  44650. transformVaryingNames.push( transform.varyingName );
  44651. transformAttributeNodes.push( transform.attributeNode );
  44652. }
  44653. gl.attachShader( programGPU, fragmentShader );
  44654. gl.attachShader( programGPU, vertexShader );
  44655. gl.transformFeedbackVaryings(
  44656. programGPU,
  44657. transformVaryingNames,
  44658. gl.SEPARATE_ATTRIBS
  44659. );
  44660. gl.linkProgram( programGPU );
  44661. if ( gl.getProgramParameter( programGPU, gl.LINK_STATUS ) === false ) {
  44662. this._logProgramError( programGPU, fragmentShader, vertexShader );
  44663. }
  44664. state.useProgram( programGPU );
  44665. // Bindings
  44666. this._setupBindings( bindings, programGPU );
  44667. const attributeNodes = computeProgram.attributes;
  44668. const attributes = [];
  44669. const transformBuffers = [];
  44670. for ( let i = 0; i < attributeNodes.length; i ++ ) {
  44671. const attribute = attributeNodes[ i ].node.attribute;
  44672. attributes.push( attribute );
  44673. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44674. }
  44675. for ( let i = 0; i < transformAttributeNodes.length; i ++ ) {
  44676. const attribute = transformAttributeNodes[ i ].attribute;
  44677. if ( ! this.has( attribute ) ) this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44678. const attributeData = this.get( attribute );
  44679. transformBuffers.push( attributeData );
  44680. }
  44681. //
  44682. this.set( computePipeline, {
  44683. programGPU,
  44684. transformBuffers,
  44685. attributes
  44686. } );
  44687. }
  44688. /**
  44689. * Creates bindings from the given bind group definition.
  44690. *
  44691. * @param {BindGroup} bindGroup - The bind group.
  44692. * @param {Array<BindGroup>} bindings - Array of bind groups.
  44693. * @param {number} cacheIndex - The cache index.
  44694. * @param {number} version - The version.
  44695. */
  44696. createBindings( bindGroup, bindings /*, cacheIndex, version*/ ) {
  44697. if ( this._knownBindings.has( bindings ) === false ) {
  44698. this._knownBindings.add( bindings );
  44699. let uniformBuffers = 0;
  44700. let textures = 0;
  44701. for ( const bindGroup of bindings ) {
  44702. this.set( bindGroup, {
  44703. textures: textures,
  44704. uniformBuffers: uniformBuffers
  44705. } );
  44706. for ( const binding of bindGroup.bindings ) {
  44707. if ( binding.isUniformBuffer ) uniformBuffers ++;
  44708. if ( binding.isSampledTexture ) textures ++;
  44709. }
  44710. }
  44711. }
  44712. this.updateBindings( bindGroup, bindings );
  44713. }
  44714. /**
  44715. * Updates the given bind group definition.
  44716. *
  44717. * @param {BindGroup} bindGroup - The bind group.
  44718. * @param {Array<BindGroup>} bindings - Array of bind groups.
  44719. * @param {number} cacheIndex - The cache index.
  44720. * @param {number} version - The version.
  44721. */
  44722. updateBindings( bindGroup /*, bindings, cacheIndex, version*/ ) {
  44723. const { gl } = this;
  44724. const bindGroupData = this.get( bindGroup );
  44725. let i = bindGroupData.uniformBuffers;
  44726. let t = bindGroupData.textures;
  44727. for ( const binding of bindGroup.bindings ) {
  44728. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  44729. const data = binding.buffer;
  44730. const bufferGPU = gl.createBuffer();
  44731. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  44732. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  44733. this.set( binding, {
  44734. index: i ++,
  44735. bufferGPU
  44736. } );
  44737. } else if ( binding.isSampledTexture ) {
  44738. const { textureGPU, glTextureType } = this.get( binding.texture );
  44739. this.set( binding, {
  44740. index: t ++,
  44741. textureGPU,
  44742. glTextureType
  44743. } );
  44744. }
  44745. }
  44746. }
  44747. /**
  44748. * Updates a buffer binding.
  44749. *
  44750. * @param {Buffer} binding - The buffer binding to update.
  44751. */
  44752. updateBinding( binding ) {
  44753. const gl = this.gl;
  44754. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  44755. const bindingData = this.get( binding );
  44756. const bufferGPU = bindingData.bufferGPU;
  44757. const data = binding.buffer;
  44758. gl.bindBuffer( gl.UNIFORM_BUFFER, bufferGPU );
  44759. gl.bufferData( gl.UNIFORM_BUFFER, data, gl.DYNAMIC_DRAW );
  44760. }
  44761. }
  44762. // attributes
  44763. /**
  44764. * Creates the GPU buffer of an indexed shader attribute.
  44765. *
  44766. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  44767. */
  44768. createIndexAttribute( attribute ) {
  44769. const gl = this.gl;
  44770. this.attributeUtils.createAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  44771. }
  44772. /**
  44773. * Creates the GPU buffer of a shader attribute.
  44774. *
  44775. * @param {BufferAttribute} attribute - The buffer attribute.
  44776. */
  44777. createAttribute( attribute ) {
  44778. if ( this.has( attribute ) ) return;
  44779. const gl = this.gl;
  44780. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44781. }
  44782. /**
  44783. * Creates the GPU buffer of a storage attribute.
  44784. *
  44785. * @param {BufferAttribute} attribute - The buffer attribute.
  44786. */
  44787. createStorageAttribute( attribute ) {
  44788. if ( this.has( attribute ) ) return;
  44789. const gl = this.gl;
  44790. this.attributeUtils.createAttribute( attribute, gl.ARRAY_BUFFER );
  44791. }
  44792. /**
  44793. * Updates the GPU buffer of a shader attribute.
  44794. *
  44795. * @param {BufferAttribute} attribute - The buffer attribute to update.
  44796. */
  44797. updateAttribute( attribute ) {
  44798. this.attributeUtils.updateAttribute( attribute );
  44799. }
  44800. /**
  44801. * Destroys the GPU buffer of a shader attribute.
  44802. *
  44803. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  44804. */
  44805. destroyAttribute( attribute ) {
  44806. this.attributeUtils.destroyAttribute( attribute );
  44807. }
  44808. /**
  44809. * Checks if the given feature is supported by the backend.
  44810. *
  44811. * @param {string} name - The feature's name.
  44812. * @return {boolean} Whether the feature is supported or not.
  44813. */
  44814. hasFeature( name ) {
  44815. const keysMatching = Object.keys( GLFeatureName ).filter( key => GLFeatureName[ key ] === name );
  44816. const extensions = this.extensions;
  44817. for ( let i = 0; i < keysMatching.length; i ++ ) {
  44818. if ( extensions.has( keysMatching[ i ] ) ) return true;
  44819. }
  44820. return false;
  44821. }
  44822. /**
  44823. * Returns the maximum anisotropy texture filtering value.
  44824. *
  44825. * @return {number} The maximum anisotropy texture filtering value.
  44826. */
  44827. getMaxAnisotropy() {
  44828. return this.capabilities.getMaxAnisotropy();
  44829. }
  44830. /**
  44831. * Copies data of the given source texture to the given destination texture.
  44832. *
  44833. * @param {Texture} srcTexture - The source texture.
  44834. * @param {Texture} dstTexture - The destination texture.
  44835. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  44836. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  44837. * @param {number} [srcLevel=0] - The source mip level to copy from.
  44838. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  44839. */
  44840. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  44841. this.textureUtils.copyTextureToTexture( srcTexture, dstTexture, srcRegion, dstPosition, srcLevel, dstLevel );
  44842. }
  44843. /**
  44844. * Copies the current bound framebuffer to the given texture.
  44845. *
  44846. * @param {Texture} texture - The destination texture.
  44847. * @param {RenderContext} renderContext - The render context.
  44848. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  44849. */
  44850. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  44851. this.textureUtils.copyFramebufferToTexture( texture, renderContext, rectangle );
  44852. }
  44853. /**
  44854. * Configures the active framebuffer from the given render context.
  44855. *
  44856. * @private
  44857. * @param {RenderContext} descriptor - The render context.
  44858. */
  44859. _setFramebuffer( descriptor ) {
  44860. const { gl, state } = this;
  44861. let currentFrameBuffer = null;
  44862. if ( descriptor.textures !== null ) {
  44863. const renderTarget = descriptor.renderTarget;
  44864. const renderTargetContextData = this.get( renderTarget );
  44865. const { samples, depthBuffer, stencilBuffer } = renderTarget;
  44866. const isCube = renderTarget.isWebGLCubeRenderTarget === true;
  44867. const isRenderTarget3D = renderTarget.isRenderTarget3D === true;
  44868. const isRenderTargetArray = renderTarget.depth > 1;
  44869. const isXRRenderTarget = renderTarget.isXRRenderTarget === true;
  44870. const _hasExternalTextures = ( isXRRenderTarget === true && renderTarget._hasExternalTextures === true );
  44871. let msaaFb = renderTargetContextData.msaaFrameBuffer;
  44872. let depthRenderbuffer = renderTargetContextData.depthRenderbuffer;
  44873. const multisampledRTTExt = this.extensions.get( 'WEBGL_multisampled_render_to_texture' );
  44874. const multiviewExt = this.extensions.get( 'OVR_multiview2' );
  44875. const useMultisampledRTT = this._useMultisampledExtension( renderTarget );
  44876. const cacheKey = getCacheKey( descriptor );
  44877. let fb;
  44878. if ( isCube ) {
  44879. renderTargetContextData.cubeFramebuffers || ( renderTargetContextData.cubeFramebuffers = {} );
  44880. fb = renderTargetContextData.cubeFramebuffers[ cacheKey ];
  44881. } else if ( isXRRenderTarget && _hasExternalTextures === false ) {
  44882. fb = this._xrFramebuffer;
  44883. } else {
  44884. renderTargetContextData.framebuffers || ( renderTargetContextData.framebuffers = {} );
  44885. fb = renderTargetContextData.framebuffers[ cacheKey ];
  44886. }
  44887. if ( fb === undefined ) {
  44888. fb = gl.createFramebuffer();
  44889. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  44890. const textures = descriptor.textures;
  44891. const depthInvalidationArray = [];
  44892. if ( isCube ) {
  44893. renderTargetContextData.cubeFramebuffers[ cacheKey ] = fb;
  44894. const { textureGPU } = this.get( textures[ 0 ] );
  44895. const cubeFace = this.renderer._activeCubeFace;
  44896. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + cubeFace, textureGPU, 0 );
  44897. } else {
  44898. renderTargetContextData.framebuffers[ cacheKey ] = fb;
  44899. for ( let i = 0; i < textures.length; i ++ ) {
  44900. const texture = textures[ i ];
  44901. const textureData = this.get( texture );
  44902. textureData.renderTarget = descriptor.renderTarget;
  44903. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  44904. const attachment = gl.COLOR_ATTACHMENT0 + i;
  44905. if ( renderTarget.multiview ) {
  44906. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, samples, 0, 2 );
  44907. } else if ( isRenderTarget3D || isRenderTargetArray ) {
  44908. const layer = this.renderer._activeCubeFace;
  44909. gl.framebufferTextureLayer( gl.FRAMEBUFFER, attachment, textureData.textureGPU, 0, layer );
  44910. } else {
  44911. if ( useMultisampledRTT ) {
  44912. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44913. } else {
  44914. gl.framebufferTexture2D( gl.FRAMEBUFFER, attachment, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44915. }
  44916. }
  44917. }
  44918. }
  44919. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44920. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  44921. const renderbuffer = gl.createRenderbuffer();
  44922. this.textureUtils.setupRenderBufferStorage( renderbuffer, descriptor, 0, useMultisampledRTT );
  44923. renderTargetContextData.xrDepthRenderbuffer = renderbuffer;
  44924. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  44925. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  44926. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  44927. } else {
  44928. if ( descriptor.depthTexture !== null ) {
  44929. depthInvalidationArray.push( stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT );
  44930. const textureData = this.get( descriptor.depthTexture );
  44931. textureData.renderTarget = descriptor.renderTarget;
  44932. textureData.cacheKey = cacheKey; // required for copyTextureToTexture()
  44933. if ( renderTarget.multiview ) {
  44934. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  44935. } else if ( _hasExternalTextures && useMultisampledRTT ) {
  44936. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44937. } else {
  44938. if ( descriptor.depthTexture.isArrayTexture ) {
  44939. const layer = this.renderer._activeCubeFace;
  44940. gl.framebufferTextureLayer( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, layer );
  44941. } else {
  44942. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44943. }
  44944. }
  44945. }
  44946. }
  44947. renderTargetContextData.depthInvalidationArray = depthInvalidationArray;
  44948. } else {
  44949. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( descriptor );
  44950. if ( isRenderCameraDepthArray ) {
  44951. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  44952. const layer = this.renderer._activeCubeFace;
  44953. const depthData = this.get( descriptor.depthTexture );
  44954. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44955. gl.framebufferTextureLayer(
  44956. gl.FRAMEBUFFER,
  44957. depthStyle,
  44958. depthData.textureGPU,
  44959. 0,
  44960. layer
  44961. );
  44962. }
  44963. // rebind external XR textures
  44964. if ( ( isXRRenderTarget || useMultisampledRTT || renderTarget.multiview ) && ( renderTarget._isOpaqueFramebuffer !== true ) ) {
  44965. state.bindFramebuffer( gl.FRAMEBUFFER, fb );
  44966. // rebind color
  44967. const textureData = this.get( descriptor.textures[ 0 ] );
  44968. if ( renderTarget.multiview ) {
  44969. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, textureData.textureGPU, 0, samples, 0, 2 );
  44970. } else if ( useMultisampledRTT ) {
  44971. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44972. } else {
  44973. gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44974. }
  44975. // rebind depth
  44976. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  44977. if ( renderTarget._autoAllocateDepthBuffer === true ) {
  44978. const renderbuffer = renderTargetContextData.xrDepthRenderbuffer;
  44979. gl.bindRenderbuffer( gl.RENDERBUFFER, renderbuffer );
  44980. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, depthStyle, gl.RENDERBUFFER, renderbuffer );
  44981. } else {
  44982. const textureData = this.get( descriptor.depthTexture );
  44983. if ( renderTarget.multiview ) {
  44984. multiviewExt.framebufferTextureMultisampleMultiviewOVR( gl.FRAMEBUFFER, depthStyle, textureData.textureGPU, 0, samples, 0, 2 );
  44985. } else if ( useMultisampledRTT ) {
  44986. multisampledRTTExt.framebufferTexture2DMultisampleEXT( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0, samples );
  44987. } else {
  44988. gl.framebufferTexture2D( gl.FRAMEBUFFER, depthStyle, gl.TEXTURE_2D, textureData.textureGPU, 0 );
  44989. }
  44990. }
  44991. }
  44992. }
  44993. if ( samples > 0 && useMultisampledRTT === false && ! renderTarget.multiview ) {
  44994. if ( msaaFb === undefined ) {
  44995. const invalidationArray = [];
  44996. msaaFb = gl.createFramebuffer();
  44997. state.bindFramebuffer( gl.FRAMEBUFFER, msaaFb );
  44998. const msaaRenderbuffers = [];
  44999. const textures = descriptor.textures;
  45000. for ( let i = 0; i < textures.length; i ++ ) {
  45001. msaaRenderbuffers[ i ] = gl.createRenderbuffer();
  45002. gl.bindRenderbuffer( gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  45003. invalidationArray.push( gl.COLOR_ATTACHMENT0 + i );
  45004. if ( depthBuffer ) {
  45005. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  45006. invalidationArray.push( depthStyle );
  45007. }
  45008. const texture = descriptor.textures[ i ];
  45009. const textureData = this.get( texture );
  45010. gl.renderbufferStorageMultisample( gl.RENDERBUFFER, samples, textureData.glInternalFormat, descriptor.width, descriptor.height );
  45011. gl.framebufferRenderbuffer( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, gl.RENDERBUFFER, msaaRenderbuffers[ i ] );
  45012. }
  45013. gl.bindRenderbuffer( gl.RENDERBUFFER, null );
  45014. renderTargetContextData.msaaFrameBuffer = msaaFb;
  45015. renderTargetContextData.msaaRenderbuffers = msaaRenderbuffers;
  45016. if ( depthRenderbuffer === undefined ) {
  45017. depthRenderbuffer = gl.createRenderbuffer();
  45018. this.textureUtils.setupRenderBufferStorage( depthRenderbuffer, descriptor, samples );
  45019. renderTargetContextData.depthRenderbuffer = depthRenderbuffer;
  45020. const depthStyle = stencilBuffer ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
  45021. invalidationArray.push( depthStyle );
  45022. }
  45023. renderTargetContextData.invalidationArray = invalidationArray;
  45024. }
  45025. currentFrameBuffer = renderTargetContextData.msaaFrameBuffer;
  45026. } else {
  45027. currentFrameBuffer = fb;
  45028. }
  45029. state.drawBuffers( descriptor, fb );
  45030. }
  45031. state.bindFramebuffer( gl.FRAMEBUFFER, currentFrameBuffer );
  45032. }
  45033. /**
  45034. * Computes the VAO key for the given index and attributes.
  45035. *
  45036. * @private
  45037. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  45038. * @return {string} The VAO key.
  45039. */
  45040. _getVaoKey( attributes ) {
  45041. let key = '';
  45042. for ( let i = 0; i < attributes.length; i ++ ) {
  45043. const attributeData = this.get( attributes[ i ] );
  45044. key += ':' + attributeData.id;
  45045. }
  45046. return key;
  45047. }
  45048. /**
  45049. * Creates a VAO from the index and attributes.
  45050. *
  45051. * @private
  45052. * @param {Array<BufferAttribute>} attributes - An array of buffer attributes.
  45053. * @return {Object} The VAO data.
  45054. */
  45055. _createVao( attributes ) {
  45056. const { gl } = this;
  45057. const vaoGPU = gl.createVertexArray();
  45058. gl.bindVertexArray( vaoGPU );
  45059. for ( let i = 0; i < attributes.length; i ++ ) {
  45060. const attribute = attributes[ i ];
  45061. const attributeData = this.get( attribute );
  45062. gl.bindBuffer( gl.ARRAY_BUFFER, attributeData.bufferGPU );
  45063. gl.enableVertexAttribArray( i );
  45064. let stride, offset;
  45065. if ( attribute.isInterleavedBufferAttribute === true ) {
  45066. stride = attribute.data.stride * attributeData.bytesPerElement;
  45067. offset = attribute.offset * attributeData.bytesPerElement;
  45068. } else {
  45069. stride = 0;
  45070. offset = 0;
  45071. }
  45072. if ( attributeData.isInteger ) {
  45073. gl.vertexAttribIPointer( i, attribute.itemSize, attributeData.type, stride, offset );
  45074. } else {
  45075. gl.vertexAttribPointer( i, attribute.itemSize, attributeData.type, attribute.normalized, stride, offset );
  45076. }
  45077. if ( attribute.isInstancedBufferAttribute && ! attribute.isInterleavedBufferAttribute ) {
  45078. gl.vertexAttribDivisor( i, attribute.meshPerAttribute );
  45079. } else if ( attribute.isInterleavedBufferAttribute && attribute.data.isInstancedInterleavedBuffer ) {
  45080. gl.vertexAttribDivisor( i, attribute.data.meshPerAttribute );
  45081. }
  45082. }
  45083. gl.bindBuffer( gl.ARRAY_BUFFER, null );
  45084. return vaoGPU;
  45085. }
  45086. /**
  45087. * Creates a transform feedback from the given transform buffers.
  45088. *
  45089. * @private
  45090. * @param {Array<DualAttributeData>} transformBuffers - The transform buffers.
  45091. * @return {WebGLTransformFeedback} The transform feedback.
  45092. */
  45093. _getTransformFeedback( transformBuffers ) {
  45094. let key = '';
  45095. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  45096. key += ':' + transformBuffers[ i ].id;
  45097. }
  45098. let transformFeedbackGPU = this.transformFeedbackCache[ key ];
  45099. if ( transformFeedbackGPU !== undefined ) {
  45100. return transformFeedbackGPU;
  45101. }
  45102. const { gl } = this;
  45103. transformFeedbackGPU = gl.createTransformFeedback();
  45104. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, transformFeedbackGPU );
  45105. for ( let i = 0; i < transformBuffers.length; i ++ ) {
  45106. const attributeData = transformBuffers[ i ];
  45107. gl.bindBufferBase( gl.TRANSFORM_FEEDBACK_BUFFER, i, attributeData.transformBuffer );
  45108. }
  45109. gl.bindTransformFeedback( gl.TRANSFORM_FEEDBACK, null );
  45110. this.transformFeedbackCache[ key ] = transformFeedbackGPU;
  45111. return transformFeedbackGPU;
  45112. }
  45113. /**
  45114. * Setups the given bindings.
  45115. *
  45116. * @private
  45117. * @param {Array<BindGroup>} bindings - The bindings.
  45118. * @param {WebGLProgram} programGPU - The WebGL program.
  45119. */
  45120. _setupBindings( bindings, programGPU ) {
  45121. const gl = this.gl;
  45122. for ( const bindGroup of bindings ) {
  45123. for ( const binding of bindGroup.bindings ) {
  45124. const bindingData = this.get( binding );
  45125. const index = bindingData.index;
  45126. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  45127. const location = gl.getUniformBlockIndex( programGPU, binding.name );
  45128. gl.uniformBlockBinding( programGPU, location, index );
  45129. } else if ( binding.isSampledTexture ) {
  45130. const location = gl.getUniformLocation( programGPU, binding.name );
  45131. gl.uniform1i( location, index );
  45132. }
  45133. }
  45134. }
  45135. }
  45136. /**
  45137. * Binds the given uniforms.
  45138. *
  45139. * @private
  45140. * @param {Array<BindGroup>} bindings - The bindings.
  45141. */
  45142. _bindUniforms( bindings ) {
  45143. const { gl, state } = this;
  45144. for ( const bindGroup of bindings ) {
  45145. for ( const binding of bindGroup.bindings ) {
  45146. const bindingData = this.get( binding );
  45147. const index = bindingData.index;
  45148. if ( binding.isUniformsGroup || binding.isUniformBuffer ) {
  45149. // TODO USE bindBufferRange to group multiple uniform buffers
  45150. state.bindBufferBase( gl.UNIFORM_BUFFER, index, bindingData.bufferGPU );
  45151. } else if ( binding.isSampledTexture ) {
  45152. state.bindTexture( bindingData.glTextureType, bindingData.textureGPU, gl.TEXTURE0 + index );
  45153. }
  45154. }
  45155. }
  45156. }
  45157. /**
  45158. * Returns `true` if the `WEBGL_multisampled_render_to_texture` extension
  45159. * should be used when MSAA is enabled.
  45160. *
  45161. * @private
  45162. * @param {RenderTarget} renderTarget - The render target that should be multisampled.
  45163. * @return {boolean} Whether to use the `WEBGL_multisampled_render_to_texture` extension for MSAA or not.
  45164. */
  45165. _useMultisampledExtension( renderTarget ) {
  45166. if ( renderTarget.multiview === true ) {
  45167. return true;
  45168. }
  45169. return renderTarget.samples > 0 && this.extensions.has( 'WEBGL_multisampled_render_to_texture' ) === true && renderTarget._autoAllocateDepthBuffer !== false;
  45170. }
  45171. /**
  45172. * Frees internal resources.
  45173. */
  45174. dispose() {
  45175. const extension = this.extensions.get( 'WEBGL_lose_context' );
  45176. if ( extension ) extension.loseContext();
  45177. this.renderer.domElement.removeEventListener( 'webglcontextlost', this._onContextLost );
  45178. }
  45179. }
  45180. const GPUPrimitiveTopology = {
  45181. PointList: 'point-list',
  45182. LineList: 'line-list',
  45183. LineStrip: 'line-strip',
  45184. TriangleList: 'triangle-list',
  45185. TriangleStrip: 'triangle-strip',
  45186. };
  45187. const GPUCompareFunction = {
  45188. Never: 'never',
  45189. Less: 'less',
  45190. Equal: 'equal',
  45191. LessEqual: 'less-equal',
  45192. Greater: 'greater',
  45193. NotEqual: 'not-equal',
  45194. GreaterEqual: 'greater-equal',
  45195. Always: 'always'
  45196. };
  45197. const GPUStoreOp = {
  45198. Store: 'store'};
  45199. const GPULoadOp = {
  45200. Load: 'load',
  45201. Clear: 'clear'
  45202. };
  45203. const GPUFrontFace = {
  45204. CCW: 'ccw'};
  45205. const GPUCullMode = {
  45206. None: 'none',
  45207. Front: 'front',
  45208. Back: 'back'
  45209. };
  45210. const GPUIndexFormat = {
  45211. Uint16: 'uint16',
  45212. Uint32: 'uint32'
  45213. };
  45214. const GPUTextureFormat = {
  45215. // 8-bit formats
  45216. R8Unorm: 'r8unorm',
  45217. R8Snorm: 'r8snorm',
  45218. R8Uint: 'r8uint',
  45219. R8Sint: 'r8sint',
  45220. // 16-bit formats
  45221. R16Uint: 'r16uint',
  45222. R16Sint: 'r16sint',
  45223. R16Float: 'r16float',
  45224. RG8Unorm: 'rg8unorm',
  45225. RG8Snorm: 'rg8snorm',
  45226. RG8Uint: 'rg8uint',
  45227. RG8Sint: 'rg8sint',
  45228. // 32-bit formats
  45229. R32Uint: 'r32uint',
  45230. R32Sint: 'r32sint',
  45231. R32Float: 'r32float',
  45232. RG16Uint: 'rg16uint',
  45233. RG16Sint: 'rg16sint',
  45234. RG16Float: 'rg16float',
  45235. RGBA8Unorm: 'rgba8unorm',
  45236. RGBA8UnormSRGB: 'rgba8unorm-srgb',
  45237. RGBA8Snorm: 'rgba8snorm',
  45238. RGBA8Uint: 'rgba8uint',
  45239. RGBA8Sint: 'rgba8sint',
  45240. BGRA8Unorm: 'bgra8unorm',
  45241. BGRA8UnormSRGB: 'bgra8unorm-srgb',
  45242. // Packed 32-bit formats
  45243. RGB9E5UFloat: 'rgb9e5ufloat',
  45244. RGB10A2Unorm: 'rgb10a2unorm',
  45245. RG11B10UFloat: 'rgb10a2unorm',
  45246. // 64-bit formats
  45247. RG32Uint: 'rg32uint',
  45248. RG32Sint: 'rg32sint',
  45249. RG32Float: 'rg32float',
  45250. RGBA16Uint: 'rgba16uint',
  45251. RGBA16Sint: 'rgba16sint',
  45252. RGBA16Float: 'rgba16float',
  45253. // 128-bit formats
  45254. RGBA32Uint: 'rgba32uint',
  45255. RGBA32Sint: 'rgba32sint',
  45256. RGBA32Float: 'rgba32float',
  45257. Depth16Unorm: 'depth16unorm',
  45258. Depth24Plus: 'depth24plus',
  45259. Depth24PlusStencil8: 'depth24plus-stencil8',
  45260. Depth32Float: 'depth32float',
  45261. // 'depth32float-stencil8' extension
  45262. Depth32FloatStencil8: 'depth32float-stencil8',
  45263. // BC compressed formats usable if 'texture-compression-bc' is both
  45264. // supported by the device/user agent and enabled in requestDevice.
  45265. BC1RGBAUnorm: 'bc1-rgba-unorm',
  45266. BC1RGBAUnormSRGB: 'bc1-rgba-unorm-srgb',
  45267. BC2RGBAUnorm: 'bc2-rgba-unorm',
  45268. BC2RGBAUnormSRGB: 'bc2-rgba-unorm-srgb',
  45269. BC3RGBAUnorm: 'bc3-rgba-unorm',
  45270. BC3RGBAUnormSRGB: 'bc3-rgba-unorm-srgb',
  45271. BC4RUnorm: 'bc4-r-unorm',
  45272. BC4RSnorm: 'bc4-r-snorm',
  45273. BC5RGUnorm: 'bc5-rg-unorm',
  45274. BC5RGSnorm: 'bc5-rg-snorm',
  45275. BC6HRGBUFloat: 'bc6h-rgb-ufloat',
  45276. BC6HRGBFloat: 'bc6h-rgb-float',
  45277. BC7RGBAUnorm: 'bc7-rgba-unorm',
  45278. BC7RGBAUnormSRGB: 'bc7-rgba-srgb',
  45279. // ETC2 compressed formats usable if 'texture-compression-etc2' is both
  45280. // supported by the device/user agent and enabled in requestDevice.
  45281. ETC2RGB8Unorm: 'etc2-rgb8unorm',
  45282. ETC2RGB8UnormSRGB: 'etc2-rgb8unorm-srgb',
  45283. ETC2RGB8A1Unorm: 'etc2-rgb8a1unorm',
  45284. ETC2RGB8A1UnormSRGB: 'etc2-rgb8a1unorm-srgb',
  45285. ETC2RGBA8Unorm: 'etc2-rgba8unorm',
  45286. ETC2RGBA8UnormSRGB: 'etc2-rgba8unorm-srgb',
  45287. EACR11Unorm: 'eac-r11unorm',
  45288. EACR11Snorm: 'eac-r11snorm',
  45289. EACRG11Unorm: 'eac-rg11unorm',
  45290. EACRG11Snorm: 'eac-rg11snorm',
  45291. // ASTC compressed formats usable if 'texture-compression-astc' is both
  45292. // supported by the device/user agent and enabled in requestDevice.
  45293. ASTC4x4Unorm: 'astc-4x4-unorm',
  45294. ASTC4x4UnormSRGB: 'astc-4x4-unorm-srgb',
  45295. ASTC5x4Unorm: 'astc-5x4-unorm',
  45296. ASTC5x4UnormSRGB: 'astc-5x4-unorm-srgb',
  45297. ASTC5x5Unorm: 'astc-5x5-unorm',
  45298. ASTC5x5UnormSRGB: 'astc-5x5-unorm-srgb',
  45299. ASTC6x5Unorm: 'astc-6x5-unorm',
  45300. ASTC6x5UnormSRGB: 'astc-6x5-unorm-srgb',
  45301. ASTC6x6Unorm: 'astc-6x6-unorm',
  45302. ASTC6x6UnormSRGB: 'astc-6x6-unorm-srgb',
  45303. ASTC8x5Unorm: 'astc-8x5-unorm',
  45304. ASTC8x5UnormSRGB: 'astc-8x5-unorm-srgb',
  45305. ASTC8x6Unorm: 'astc-8x6-unorm',
  45306. ASTC8x6UnormSRGB: 'astc-8x6-unorm-srgb',
  45307. ASTC8x8Unorm: 'astc-8x8-unorm',
  45308. ASTC8x8UnormSRGB: 'astc-8x8-unorm-srgb',
  45309. ASTC10x5Unorm: 'astc-10x5-unorm',
  45310. ASTC10x5UnormSRGB: 'astc-10x5-unorm-srgb',
  45311. ASTC10x6Unorm: 'astc-10x6-unorm',
  45312. ASTC10x6UnormSRGB: 'astc-10x6-unorm-srgb',
  45313. ASTC10x8Unorm: 'astc-10x8-unorm',
  45314. ASTC10x8UnormSRGB: 'astc-10x8-unorm-srgb',
  45315. ASTC10x10Unorm: 'astc-10x10-unorm',
  45316. ASTC10x10UnormSRGB: 'astc-10x10-unorm-srgb',
  45317. ASTC12x10Unorm: 'astc-12x10-unorm',
  45318. ASTC12x10UnormSRGB: 'astc-12x10-unorm-srgb',
  45319. ASTC12x12Unorm: 'astc-12x12-unorm',
  45320. ASTC12x12UnormSRGB: 'astc-12x12-unorm-srgb',
  45321. };
  45322. const GPUAddressMode = {
  45323. ClampToEdge: 'clamp-to-edge',
  45324. Repeat: 'repeat',
  45325. MirrorRepeat: 'mirror-repeat'
  45326. };
  45327. const GPUFilterMode = {
  45328. Linear: 'linear',
  45329. Nearest: 'nearest'
  45330. };
  45331. const GPUBlendFactor = {
  45332. Zero: 'zero',
  45333. One: 'one',
  45334. Src: 'src',
  45335. OneMinusSrc: 'one-minus-src',
  45336. SrcAlpha: 'src-alpha',
  45337. OneMinusSrcAlpha: 'one-minus-src-alpha',
  45338. Dst: 'dst',
  45339. OneMinusDst: 'one-minus-dst',
  45340. DstAlpha: 'dst-alpha',
  45341. OneMinusDstAlpha: 'one-minus-dst-alpha',
  45342. SrcAlphaSaturated: 'src-alpha-saturated',
  45343. Constant: 'constant',
  45344. OneMinusConstant: 'one-minus-constant'
  45345. };
  45346. const GPUBlendOperation = {
  45347. Add: 'add',
  45348. Subtract: 'subtract',
  45349. ReverseSubtract: 'reverse-subtract',
  45350. Min: 'min',
  45351. Max: 'max'
  45352. };
  45353. const GPUColorWriteFlags = {
  45354. None: 0,
  45355. All: 0xF
  45356. };
  45357. const GPUStencilOperation = {
  45358. Keep: 'keep',
  45359. Zero: 'zero',
  45360. Replace: 'replace',
  45361. Invert: 'invert',
  45362. IncrementClamp: 'increment-clamp',
  45363. DecrementClamp: 'decrement-clamp',
  45364. IncrementWrap: 'increment-wrap',
  45365. DecrementWrap: 'decrement-wrap'
  45366. };
  45367. const GPUBufferBindingType = {
  45368. Storage: 'storage',
  45369. ReadOnlyStorage: 'read-only-storage'
  45370. };
  45371. const GPUStorageTextureAccess = {
  45372. WriteOnly: 'write-only',
  45373. ReadOnly: 'read-only',
  45374. ReadWrite: 'read-write',
  45375. };
  45376. const GPUSamplerBindingType = {
  45377. NonFiltering: 'non-filtering',
  45378. Comparison: 'comparison'
  45379. };
  45380. const GPUTextureSampleType = {
  45381. Float: 'float',
  45382. UnfilterableFloat: 'unfilterable-float',
  45383. Depth: 'depth',
  45384. SInt: 'sint',
  45385. UInt: 'uint'
  45386. };
  45387. const GPUTextureDimension = {
  45388. TwoD: '2d',
  45389. ThreeD: '3d'
  45390. };
  45391. const GPUTextureViewDimension = {
  45392. TwoD: '2d',
  45393. TwoDArray: '2d-array',
  45394. Cube: 'cube',
  45395. ThreeD: '3d'
  45396. };
  45397. const GPUTextureAspect = {
  45398. All: 'all'};
  45399. const GPUInputStepMode = {
  45400. Vertex: 'vertex',
  45401. Instance: 'instance'
  45402. };
  45403. const GPUFeatureName = {
  45404. DepthClipControl: 'depth-clip-control',
  45405. Depth32FloatStencil8: 'depth32float-stencil8',
  45406. TextureCompressionBC: 'texture-compression-bc',
  45407. TextureCompressionETC2: 'texture-compression-etc2',
  45408. TextureCompressionASTC: 'texture-compression-astc',
  45409. TimestampQuery: 'timestamp-query',
  45410. IndirectFirstInstance: 'indirect-first-instance',
  45411. ShaderF16: 'shader-f16',
  45412. RG11B10UFloat: 'rg11b10ufloat-renderable',
  45413. BGRA8UNormStorage: 'bgra8unorm-storage',
  45414. Float32Filterable: 'float32-filterable',
  45415. ClipDistances: 'clip-distances',
  45416. DualSourceBlending: 'dual-source-blending',
  45417. Subgroups: 'subgroups'
  45418. };
  45419. /**
  45420. * Represents a sampler binding type.
  45421. *
  45422. * @private
  45423. * @augments Binding
  45424. */
  45425. class Sampler extends Binding {
  45426. /**
  45427. * Constructs a new sampler.
  45428. *
  45429. * @param {string} name - The samplers's name.
  45430. * @param {?Texture} texture - The texture this binding is referring to.
  45431. */
  45432. constructor( name, texture ) {
  45433. super( name );
  45434. /**
  45435. * The texture the sampler is referring to.
  45436. *
  45437. * @type {?Texture}
  45438. */
  45439. this.texture = texture;
  45440. /**
  45441. * The binding's version.
  45442. *
  45443. * @type {number}
  45444. */
  45445. this.version = texture ? texture.version : 0;
  45446. /**
  45447. * This flag can be used for type testing.
  45448. *
  45449. * @type {boolean}
  45450. * @readonly
  45451. * @default true
  45452. */
  45453. this.isSampler = true;
  45454. }
  45455. }
  45456. /**
  45457. * A special form of sampler binding type.
  45458. * It's texture value is managed by a node object.
  45459. *
  45460. * @private
  45461. * @augments Sampler
  45462. */
  45463. class NodeSampler extends Sampler {
  45464. /**
  45465. * Constructs a new node-based sampler.
  45466. *
  45467. * @param {string} name - The samplers's name.
  45468. * @param {TextureNode} textureNode - The texture node.
  45469. * @param {UniformGroupNode} groupNode - The uniform group node.
  45470. */
  45471. constructor( name, textureNode, groupNode ) {
  45472. super( name, textureNode ? textureNode.value : null );
  45473. /**
  45474. * The texture node.
  45475. *
  45476. * @type {TextureNode}
  45477. */
  45478. this.textureNode = textureNode;
  45479. /**
  45480. * The uniform group node.
  45481. *
  45482. * @type {UniformGroupNode}
  45483. */
  45484. this.groupNode = groupNode;
  45485. }
  45486. /**
  45487. * Updates the texture value of this sampler.
  45488. */
  45489. update() {
  45490. this.texture = this.textureNode.value;
  45491. }
  45492. }
  45493. /**
  45494. * Represents a storage buffer binding type.
  45495. *
  45496. * @private
  45497. * @augments Buffer
  45498. */
  45499. class StorageBuffer extends Buffer {
  45500. /**
  45501. * Constructs a new uniform buffer.
  45502. *
  45503. * @param {string} name - The buffer's name.
  45504. * @param {BufferAttribute} attribute - The buffer attribute.
  45505. */
  45506. constructor( name, attribute ) {
  45507. super( name, attribute ? attribute.array : null );
  45508. /**
  45509. * This flag can be used for type testing.
  45510. *
  45511. * @type {BufferAttribute}
  45512. */
  45513. this.attribute = attribute;
  45514. /**
  45515. * This flag can be used for type testing.
  45516. *
  45517. * @type {boolean}
  45518. * @readonly
  45519. * @default true
  45520. */
  45521. this.isStorageBuffer = true;
  45522. }
  45523. }
  45524. let _id = 0;
  45525. /**
  45526. * A special form of storage buffer binding type.
  45527. * It's buffer value is managed by a node object.
  45528. *
  45529. * @private
  45530. * @augments StorageBuffer
  45531. */
  45532. class NodeStorageBuffer extends StorageBuffer {
  45533. /**
  45534. * Constructs a new node-based storage buffer.
  45535. *
  45536. * @param {StorageBufferNode} nodeUniform - The storage buffer node.
  45537. * @param {UniformGroupNode} groupNode - The uniform group node.
  45538. */
  45539. constructor( nodeUniform, groupNode ) {
  45540. super( 'StorageBuffer_' + _id ++, nodeUniform ? nodeUniform.value : null );
  45541. /**
  45542. * The node uniform.
  45543. *
  45544. * @type {StorageBufferNode}
  45545. */
  45546. this.nodeUniform = nodeUniform;
  45547. /**
  45548. * The access type.
  45549. *
  45550. * @type {string}
  45551. */
  45552. this.access = nodeUniform ? nodeUniform.access : NodeAccess.READ_WRITE;
  45553. /**
  45554. * The uniform group node.
  45555. *
  45556. * @type {UniformGroupNode}
  45557. */
  45558. this.groupNode = groupNode;
  45559. }
  45560. /**
  45561. * The storage buffer.
  45562. *
  45563. * @type {BufferAttribute}
  45564. */
  45565. get buffer() {
  45566. return this.nodeUniform.value;
  45567. }
  45568. }
  45569. /**
  45570. * A WebGPU backend utility module used by {@link WebGPUTextureUtils}.
  45571. *
  45572. * @private
  45573. */
  45574. class WebGPUTexturePassUtils extends DataMap {
  45575. /**
  45576. * Constructs a new utility object.
  45577. *
  45578. * @param {GPUDevice} device - The WebGPU device.
  45579. */
  45580. constructor( device ) {
  45581. super();
  45582. /**
  45583. * The WebGPU device.
  45584. *
  45585. * @type {GPUDevice}
  45586. */
  45587. this.device = device;
  45588. const mipmapVertexSource = `
  45589. struct VarysStruct {
  45590. @builtin( position ) Position: vec4<f32>,
  45591. @location( 0 ) vTex : vec2<f32>
  45592. };
  45593. @vertex
  45594. fn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {
  45595. var Varys : VarysStruct;
  45596. var pos = array< vec2<f32>, 4 >(
  45597. vec2<f32>( -1.0, 1.0 ),
  45598. vec2<f32>( 1.0, 1.0 ),
  45599. vec2<f32>( -1.0, -1.0 ),
  45600. vec2<f32>( 1.0, -1.0 )
  45601. );
  45602. var tex = array< vec2<f32>, 4 >(
  45603. vec2<f32>( 0.0, 0.0 ),
  45604. vec2<f32>( 1.0, 0.0 ),
  45605. vec2<f32>( 0.0, 1.0 ),
  45606. vec2<f32>( 1.0, 1.0 )
  45607. );
  45608. Varys.vTex = tex[ vertexIndex ];
  45609. Varys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );
  45610. return Varys;
  45611. }
  45612. `;
  45613. const mipmapFragmentSource = `
  45614. @group( 0 ) @binding( 0 )
  45615. var imgSampler : sampler;
  45616. @group( 0 ) @binding( 1 )
  45617. var img : texture_2d<f32>;
  45618. @fragment
  45619. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  45620. return textureSample( img, imgSampler, vTex );
  45621. }
  45622. `;
  45623. const flipYFragmentSource = `
  45624. @group( 0 ) @binding( 0 )
  45625. var imgSampler : sampler;
  45626. @group( 0 ) @binding( 1 )
  45627. var img : texture_2d<f32>;
  45628. @fragment
  45629. fn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {
  45630. return textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );
  45631. }
  45632. `;
  45633. /**
  45634. * The mipmap GPU sampler.
  45635. *
  45636. * @type {GPUSampler}
  45637. */
  45638. this.mipmapSampler = device.createSampler( { minFilter: GPUFilterMode.Linear } );
  45639. /**
  45640. * The flipY GPU sampler.
  45641. *
  45642. * @type {GPUSampler}
  45643. */
  45644. this.flipYSampler = device.createSampler( { minFilter: GPUFilterMode.Nearest } ); //@TODO?: Consider using textureLoad()
  45645. /**
  45646. * A cache for GPU render pipelines used for copy/transfer passes.
  45647. * Every texture format requires a unique pipeline.
  45648. *
  45649. * @type {Object<string,GPURenderPipeline>}
  45650. */
  45651. this.transferPipelines = {};
  45652. /**
  45653. * A cache for GPU render pipelines used for flipY passes.
  45654. * Every texture format requires a unique pipeline.
  45655. *
  45656. * @type {Object<string,GPURenderPipeline>}
  45657. */
  45658. this.flipYPipelines = {};
  45659. /**
  45660. * The mipmap vertex shader module.
  45661. *
  45662. * @type {GPUShaderModule}
  45663. */
  45664. this.mipmapVertexShaderModule = device.createShaderModule( {
  45665. label: 'mipmapVertex',
  45666. code: mipmapVertexSource
  45667. } );
  45668. /**
  45669. * The mipmap fragment shader module.
  45670. *
  45671. * @type {GPUShaderModule}
  45672. */
  45673. this.mipmapFragmentShaderModule = device.createShaderModule( {
  45674. label: 'mipmapFragment',
  45675. code: mipmapFragmentSource
  45676. } );
  45677. /**
  45678. * The flipY fragment shader module.
  45679. *
  45680. * @type {GPUShaderModule}
  45681. */
  45682. this.flipYFragmentShaderModule = device.createShaderModule( {
  45683. label: 'flipYFragment',
  45684. code: flipYFragmentSource
  45685. } );
  45686. }
  45687. /**
  45688. * Returns a render pipeline for the internal copy render pass. The pass
  45689. * requires a unique render pipeline for each texture format.
  45690. *
  45691. * @param {string} format - The GPU texture format
  45692. * @return {GPURenderPipeline} The GPU render pipeline.
  45693. */
  45694. getTransferPipeline( format ) {
  45695. let pipeline = this.transferPipelines[ format ];
  45696. if ( pipeline === undefined ) {
  45697. pipeline = this.device.createRenderPipeline( {
  45698. label: `mipmap-${ format }`,
  45699. vertex: {
  45700. module: this.mipmapVertexShaderModule,
  45701. entryPoint: 'main'
  45702. },
  45703. fragment: {
  45704. module: this.mipmapFragmentShaderModule,
  45705. entryPoint: 'main',
  45706. targets: [ { format } ]
  45707. },
  45708. primitive: {
  45709. topology: GPUPrimitiveTopology.TriangleStrip,
  45710. stripIndexFormat: GPUIndexFormat.Uint32
  45711. },
  45712. layout: 'auto'
  45713. } );
  45714. this.transferPipelines[ format ] = pipeline;
  45715. }
  45716. return pipeline;
  45717. }
  45718. /**
  45719. * Returns a render pipeline for the flipY render pass. The pass
  45720. * requires a unique render pipeline for each texture format.
  45721. *
  45722. * @param {string} format - The GPU texture format
  45723. * @return {GPURenderPipeline} The GPU render pipeline.
  45724. */
  45725. getFlipYPipeline( format ) {
  45726. let pipeline = this.flipYPipelines[ format ];
  45727. if ( pipeline === undefined ) {
  45728. pipeline = this.device.createRenderPipeline( {
  45729. label: `flipY-${ format }`,
  45730. vertex: {
  45731. module: this.mipmapVertexShaderModule,
  45732. entryPoint: 'main'
  45733. },
  45734. fragment: {
  45735. module: this.flipYFragmentShaderModule,
  45736. entryPoint: 'main',
  45737. targets: [ { format } ]
  45738. },
  45739. primitive: {
  45740. topology: GPUPrimitiveTopology.TriangleStrip,
  45741. stripIndexFormat: GPUIndexFormat.Uint32
  45742. },
  45743. layout: 'auto'
  45744. } );
  45745. this.flipYPipelines[ format ] = pipeline;
  45746. }
  45747. return pipeline;
  45748. }
  45749. /**
  45750. * Flip the contents of the given GPU texture along its vertical axis.
  45751. *
  45752. * @param {GPUTexture} textureGPU - The GPU texture object.
  45753. * @param {Object} textureGPUDescriptor - The texture descriptor.
  45754. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  45755. */
  45756. flipY( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  45757. const format = textureGPUDescriptor.format;
  45758. const { width, height } = textureGPUDescriptor.size;
  45759. const transferPipeline = this.getTransferPipeline( format );
  45760. const flipYPipeline = this.getFlipYPipeline( format );
  45761. const tempTexture = this.device.createTexture( {
  45762. size: { width, height, depthOrArrayLayers: 1 },
  45763. format,
  45764. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING
  45765. } );
  45766. const srcView = textureGPU.createView( {
  45767. baseMipLevel: 0,
  45768. mipLevelCount: 1,
  45769. dimension: GPUTextureViewDimension.TwoD,
  45770. baseArrayLayer
  45771. } );
  45772. const dstView = tempTexture.createView( {
  45773. baseMipLevel: 0,
  45774. mipLevelCount: 1,
  45775. dimension: GPUTextureViewDimension.TwoD,
  45776. baseArrayLayer: 0
  45777. } );
  45778. const commandEncoder = this.device.createCommandEncoder( {} );
  45779. const pass = ( pipeline, sourceView, destinationView ) => {
  45780. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  45781. const bindGroup = this.device.createBindGroup( {
  45782. layout: bindGroupLayout,
  45783. entries: [ {
  45784. binding: 0,
  45785. resource: this.flipYSampler
  45786. }, {
  45787. binding: 1,
  45788. resource: sourceView
  45789. } ]
  45790. } );
  45791. const passEncoder = commandEncoder.beginRenderPass( {
  45792. colorAttachments: [ {
  45793. view: destinationView,
  45794. loadOp: GPULoadOp.Clear,
  45795. storeOp: GPUStoreOp.Store,
  45796. clearValue: [ 0, 0, 0, 0 ]
  45797. } ]
  45798. } );
  45799. passEncoder.setPipeline( pipeline );
  45800. passEncoder.setBindGroup( 0, bindGroup );
  45801. passEncoder.draw( 4, 1, 0, 0 );
  45802. passEncoder.end();
  45803. };
  45804. pass( transferPipeline, srcView, dstView );
  45805. pass( flipYPipeline, dstView, srcView );
  45806. this.device.queue.submit( [ commandEncoder.finish() ] );
  45807. tempTexture.destroy();
  45808. }
  45809. /**
  45810. * Generates mipmaps for the given GPU texture.
  45811. *
  45812. * @param {GPUTexture} textureGPU - The GPU texture object.
  45813. * @param {Object} textureGPUDescriptor - The texture descriptor.
  45814. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  45815. */
  45816. generateMipmaps( textureGPU, textureGPUDescriptor, baseArrayLayer = 0 ) {
  45817. const textureData = this.get( textureGPU );
  45818. if ( textureData.useCount === undefined ) {
  45819. textureData.useCount = 0;
  45820. textureData.layers = [];
  45821. }
  45822. const passes = textureData.layers[ baseArrayLayer ] || this._mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer );
  45823. const commandEncoder = this.device.createCommandEncoder( {} );
  45824. this._mipmapRunBundles( commandEncoder, passes );
  45825. this.device.queue.submit( [ commandEncoder.finish() ] );
  45826. if ( textureData.useCount !== 0 ) textureData.layers[ baseArrayLayer ] = passes;
  45827. textureData.useCount ++;
  45828. }
  45829. /**
  45830. * Since multiple copy render passes are required to generate mipmaps, the passes
  45831. * are managed as render bundles to improve performance.
  45832. *
  45833. * @param {GPUTexture} textureGPU - The GPU texture object.
  45834. * @param {Object} textureGPUDescriptor - The texture descriptor.
  45835. * @param {number} baseArrayLayer - The index of the first array layer accessible to the texture view.
  45836. * @return {Array<Object>} An array of render bundles.
  45837. */
  45838. _mipmapCreateBundles( textureGPU, textureGPUDescriptor, baseArrayLayer ) {
  45839. const pipeline = this.getTransferPipeline( textureGPUDescriptor.format );
  45840. const bindGroupLayout = pipeline.getBindGroupLayout( 0 ); // @TODO: Consider making this static.
  45841. let srcView = textureGPU.createView( {
  45842. baseMipLevel: 0,
  45843. mipLevelCount: 1,
  45844. dimension: GPUTextureViewDimension.TwoD,
  45845. baseArrayLayer
  45846. } );
  45847. const passes = [];
  45848. for ( let i = 1; i < textureGPUDescriptor.mipLevelCount; i ++ ) {
  45849. const bindGroup = this.device.createBindGroup( {
  45850. layout: bindGroupLayout,
  45851. entries: [ {
  45852. binding: 0,
  45853. resource: this.mipmapSampler
  45854. }, {
  45855. binding: 1,
  45856. resource: srcView
  45857. } ]
  45858. } );
  45859. const dstView = textureGPU.createView( {
  45860. baseMipLevel: i,
  45861. mipLevelCount: 1,
  45862. dimension: GPUTextureViewDimension.TwoD,
  45863. baseArrayLayer
  45864. } );
  45865. const passDescriptor = {
  45866. colorAttachments: [ {
  45867. view: dstView,
  45868. loadOp: GPULoadOp.Clear,
  45869. storeOp: GPUStoreOp.Store,
  45870. clearValue: [ 0, 0, 0, 0 ]
  45871. } ]
  45872. };
  45873. const passEncoder = this.device.createRenderBundleEncoder( {
  45874. colorFormats: [ textureGPUDescriptor.format ]
  45875. } );
  45876. passEncoder.setPipeline( pipeline );
  45877. passEncoder.setBindGroup( 0, bindGroup );
  45878. passEncoder.draw( 4, 1, 0, 0 );
  45879. passes.push( {
  45880. renderBundles: [ passEncoder.finish() ],
  45881. passDescriptor
  45882. } );
  45883. srcView = dstView;
  45884. }
  45885. return passes;
  45886. }
  45887. /**
  45888. * Executes the render bundles.
  45889. *
  45890. * @param {GPUCommandEncoder} commandEncoder - The GPU command encoder.
  45891. * @param {Array<Object>} passes - An array of render bundles.
  45892. */
  45893. _mipmapRunBundles( commandEncoder, passes ) {
  45894. const levels = passes.length;
  45895. for ( let i = 0; i < levels; i ++ ) {
  45896. const pass = passes[ i ];
  45897. const passEncoder = commandEncoder.beginRenderPass( pass.passDescriptor );
  45898. passEncoder.executeBundles( pass.renderBundles );
  45899. passEncoder.end();
  45900. }
  45901. }
  45902. }
  45903. const _compareToWebGPU = {
  45904. [ NeverCompare ]: 'never',
  45905. [ LessCompare ]: 'less',
  45906. [ EqualCompare ]: 'equal',
  45907. [ LessEqualCompare ]: 'less-equal',
  45908. [ GreaterCompare ]: 'greater',
  45909. [ GreaterEqualCompare ]: 'greater-equal',
  45910. [ AlwaysCompare ]: 'always',
  45911. [ NotEqualCompare ]: 'not-equal'
  45912. };
  45913. const _flipMap = [ 0, 1, 3, 2, 4, 5 ];
  45914. /**
  45915. * A WebGPU backend utility module for managing textures.
  45916. *
  45917. * @private
  45918. */
  45919. class WebGPUTextureUtils {
  45920. /**
  45921. * Constructs a new utility object.
  45922. *
  45923. * @param {WebGPUBackend} backend - The WebGPU backend.
  45924. */
  45925. constructor( backend ) {
  45926. /**
  45927. * A reference to the WebGPU backend.
  45928. *
  45929. * @type {WebGPUBackend}
  45930. */
  45931. this.backend = backend;
  45932. /**
  45933. * A reference to the pass utils.
  45934. *
  45935. * @type {?WebGPUTexturePassUtils}
  45936. * @default null
  45937. */
  45938. this._passUtils = null;
  45939. /**
  45940. * A dictionary for managing default textures. The key
  45941. * is the texture format, the value the texture object.
  45942. *
  45943. * @type {Object<string,Texture>}
  45944. */
  45945. this.defaultTexture = {};
  45946. /**
  45947. * A dictionary for managing default cube textures. The key
  45948. * is the texture format, the value the texture object.
  45949. *
  45950. * @type {Object<string,CubeTexture>}
  45951. */
  45952. this.defaultCubeTexture = {};
  45953. /**
  45954. * A default video frame.
  45955. *
  45956. * @type {?VideoFrame}
  45957. * @default null
  45958. */
  45959. this.defaultVideoFrame = null;
  45960. /**
  45961. * Represents the color attachment of the default framebuffer.
  45962. *
  45963. * @type {?GPUTexture}
  45964. * @default null
  45965. */
  45966. this.colorBuffer = null;
  45967. /**
  45968. * Represents the depth attachment of the default framebuffer.
  45969. *
  45970. * @type {DepthTexture}
  45971. */
  45972. this.depthTexture = new DepthTexture();
  45973. this.depthTexture.name = 'depthBuffer';
  45974. }
  45975. /**
  45976. * Creates a GPU sampler for the given texture.
  45977. *
  45978. * @param {Texture} texture - The texture to create the sampler for.
  45979. */
  45980. createSampler( texture ) {
  45981. const backend = this.backend;
  45982. const device = backend.device;
  45983. const textureGPU = backend.get( texture );
  45984. const samplerDescriptorGPU = {
  45985. addressModeU: this._convertAddressMode( texture.wrapS ),
  45986. addressModeV: this._convertAddressMode( texture.wrapT ),
  45987. addressModeW: this._convertAddressMode( texture.wrapR ),
  45988. magFilter: this._convertFilterMode( texture.magFilter ),
  45989. minFilter: this._convertFilterMode( texture.minFilter ),
  45990. mipmapFilter: this._convertFilterMode( texture.minFilter ),
  45991. maxAnisotropy: 1
  45992. };
  45993. // anisotropy can only be used when all filter modes are set to linear.
  45994. if ( samplerDescriptorGPU.magFilter === GPUFilterMode.Linear && samplerDescriptorGPU.minFilter === GPUFilterMode.Linear && samplerDescriptorGPU.mipmapFilter === GPUFilterMode.Linear ) {
  45995. samplerDescriptorGPU.maxAnisotropy = texture.anisotropy;
  45996. }
  45997. if ( texture.isDepthTexture && texture.compareFunction !== null ) {
  45998. samplerDescriptorGPU.compare = _compareToWebGPU[ texture.compareFunction ];
  45999. }
  46000. textureGPU.sampler = device.createSampler( samplerDescriptorGPU );
  46001. }
  46002. /**
  46003. * Creates a default texture for the given texture that can be used
  46004. * as a placeholder until the actual texture is ready for usage.
  46005. *
  46006. * @param {Texture} texture - The texture to create a default texture for.
  46007. */
  46008. createDefaultTexture( texture ) {
  46009. let textureGPU;
  46010. const format = getFormat( texture );
  46011. if ( texture.isCubeTexture ) {
  46012. textureGPU = this._getDefaultCubeTextureGPU( format );
  46013. } else if ( texture.isVideoTexture ) {
  46014. this.backend.get( texture ).externalTexture = this._getDefaultVideoFrame();
  46015. } else {
  46016. textureGPU = this._getDefaultTextureGPU( format );
  46017. }
  46018. this.backend.get( texture ).texture = textureGPU;
  46019. }
  46020. /**
  46021. * Defines a texture on the GPU for the given texture object.
  46022. *
  46023. * @param {Texture} texture - The texture.
  46024. * @param {Object} [options={}] - Optional configuration parameter.
  46025. */
  46026. createTexture( texture, options = {} ) {
  46027. const backend = this.backend;
  46028. const textureData = backend.get( texture );
  46029. if ( textureData.initialized ) {
  46030. throw new Error( 'WebGPUTextureUtils: Texture already initialized.' );
  46031. }
  46032. if ( options.needsMipmaps === undefined ) options.needsMipmaps = false;
  46033. if ( options.levels === undefined ) options.levels = 1;
  46034. if ( options.depth === undefined ) options.depth = 1;
  46035. const { width, height, depth, levels } = options;
  46036. if ( texture.isFramebufferTexture ) {
  46037. if ( options.renderTarget ) {
  46038. options.format = this.backend.utils.getCurrentColorFormat( options.renderTarget );
  46039. } else {
  46040. options.format = this.backend.utils.getPreferredCanvasFormat();
  46041. }
  46042. }
  46043. const dimension = this._getDimension( texture );
  46044. const format = texture.internalFormat || options.format || getFormat( texture, backend.device );
  46045. textureData.format = format;
  46046. const { samples, primarySamples, isMSAA } = backend.utils.getTextureSampleData( texture );
  46047. let usage = GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST | GPUTextureUsage.COPY_SRC;
  46048. if ( texture.isStorageTexture === true ) {
  46049. usage |= GPUTextureUsage.STORAGE_BINDING;
  46050. }
  46051. if ( texture.isCompressedTexture !== true && texture.isCompressedArrayTexture !== true ) {
  46052. usage |= GPUTextureUsage.RENDER_ATTACHMENT;
  46053. }
  46054. const textureDescriptorGPU = {
  46055. label: texture.name,
  46056. size: {
  46057. width: width,
  46058. height: height,
  46059. depthOrArrayLayers: depth,
  46060. },
  46061. mipLevelCount: levels,
  46062. sampleCount: primarySamples,
  46063. dimension: dimension,
  46064. format: format,
  46065. usage: usage
  46066. };
  46067. // texture creation
  46068. if ( texture.isVideoTexture ) {
  46069. const video = texture.source.data;
  46070. const videoFrame = new VideoFrame( video );
  46071. textureDescriptorGPU.size.width = videoFrame.displayWidth;
  46072. textureDescriptorGPU.size.height = videoFrame.displayHeight;
  46073. videoFrame.close();
  46074. textureData.externalTexture = video;
  46075. } else {
  46076. if ( format === undefined ) {
  46077. console.warn( 'WebGPURenderer: Texture format not supported.' );
  46078. this.createDefaultTexture( texture );
  46079. return;
  46080. }
  46081. if ( texture.isCubeTexture ) {
  46082. textureDescriptorGPU.textureBindingViewDimension = GPUTextureViewDimension.Cube;
  46083. }
  46084. textureData.texture = backend.device.createTexture( textureDescriptorGPU );
  46085. }
  46086. if ( isMSAA ) {
  46087. const msaaTextureDescriptorGPU = Object.assign( {}, textureDescriptorGPU );
  46088. msaaTextureDescriptorGPU.label = msaaTextureDescriptorGPU.label + '-msaa';
  46089. msaaTextureDescriptorGPU.sampleCount = samples;
  46090. textureData.msaaTexture = backend.device.createTexture( msaaTextureDescriptorGPU );
  46091. }
  46092. textureData.initialized = true;
  46093. textureData.textureDescriptorGPU = textureDescriptorGPU;
  46094. }
  46095. /**
  46096. * Destroys the GPU data for the given texture object.
  46097. *
  46098. * @param {Texture} texture - The texture.
  46099. */
  46100. destroyTexture( texture ) {
  46101. const backend = this.backend;
  46102. const textureData = backend.get( texture );
  46103. if ( textureData.texture !== undefined ) textureData.texture.destroy();
  46104. if ( textureData.msaaTexture !== undefined ) textureData.msaaTexture.destroy();
  46105. backend.delete( texture );
  46106. }
  46107. /**
  46108. * Destroys the GPU sampler for the given texture.
  46109. *
  46110. * @param {Texture} texture - The texture to destroy the sampler for.
  46111. */
  46112. destroySampler( texture ) {
  46113. const backend = this.backend;
  46114. const textureData = backend.get( texture );
  46115. delete textureData.sampler;
  46116. }
  46117. /**
  46118. * Generates mipmaps for the given texture.
  46119. *
  46120. * @param {Texture} texture - The texture.
  46121. */
  46122. generateMipmaps( texture ) {
  46123. const textureData = this.backend.get( texture );
  46124. if ( texture.isCubeTexture ) {
  46125. for ( let i = 0; i < 6; i ++ ) {
  46126. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  46127. }
  46128. } else {
  46129. const depth = texture.image.depth || 1;
  46130. for ( let i = 0; i < depth; i ++ ) {
  46131. this._generateMipmaps( textureData.texture, textureData.textureDescriptorGPU, i );
  46132. }
  46133. }
  46134. }
  46135. /**
  46136. * Returns the color buffer representing the color
  46137. * attachment of the default framebuffer.
  46138. *
  46139. * @return {GPUTexture} The color buffer.
  46140. */
  46141. getColorBuffer() {
  46142. if ( this.colorBuffer ) this.colorBuffer.destroy();
  46143. const backend = this.backend;
  46144. const { width, height } = backend.getDrawingBufferSize();
  46145. this.colorBuffer = backend.device.createTexture( {
  46146. label: 'colorBuffer',
  46147. size: {
  46148. width: width,
  46149. height: height,
  46150. depthOrArrayLayers: 1
  46151. },
  46152. sampleCount: backend.utils.getSampleCount( backend.renderer.samples ),
  46153. format: backend.utils.getPreferredCanvasFormat(),
  46154. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC
  46155. } );
  46156. return this.colorBuffer;
  46157. }
  46158. /**
  46159. * Returns the depth buffer representing the depth
  46160. * attachment of the default framebuffer.
  46161. *
  46162. * @param {boolean} [depth=true] - Whether depth is enabled or not.
  46163. * @param {boolean} [stencil=false] - Whether stencil is enabled or not.
  46164. * @return {GPUTexture} The depth buffer.
  46165. */
  46166. getDepthBuffer( depth = true, stencil = false ) {
  46167. const backend = this.backend;
  46168. const { width, height } = backend.getDrawingBufferSize();
  46169. const depthTexture = this.depthTexture;
  46170. const depthTextureGPU = backend.get( depthTexture ).texture;
  46171. let format, type;
  46172. if ( stencil ) {
  46173. format = DepthStencilFormat;
  46174. type = UnsignedInt248Type;
  46175. } else if ( depth ) {
  46176. format = DepthFormat;
  46177. type = UnsignedIntType;
  46178. }
  46179. if ( depthTextureGPU !== undefined ) {
  46180. if ( depthTexture.image.width === width && depthTexture.image.height === height && depthTexture.format === format && depthTexture.type === type ) {
  46181. return depthTextureGPU;
  46182. }
  46183. this.destroyTexture( depthTexture );
  46184. }
  46185. depthTexture.name = 'depthBuffer';
  46186. depthTexture.format = format;
  46187. depthTexture.type = type;
  46188. depthTexture.image.width = width;
  46189. depthTexture.image.height = height;
  46190. this.createTexture( depthTexture, { width, height } );
  46191. return backend.get( depthTexture ).texture;
  46192. }
  46193. /**
  46194. * Uploads the updated texture data to the GPU.
  46195. *
  46196. * @param {Texture} texture - The texture.
  46197. * @param {Object} [options={}] - Optional configuration parameter.
  46198. */
  46199. updateTexture( texture, options ) {
  46200. const textureData = this.backend.get( texture );
  46201. const { textureDescriptorGPU } = textureData;
  46202. if ( texture.isRenderTargetTexture || ( textureDescriptorGPU === undefined /* unsupported texture format */ ) )
  46203. return;
  46204. // transfer texture data
  46205. if ( texture.isDataTexture ) {
  46206. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY );
  46207. } else if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  46208. for ( let i = 0; i < options.image.depth; i ++ ) {
  46209. this._copyBufferToTexture( options.image, textureData.texture, textureDescriptorGPU, i, texture.flipY, i );
  46210. }
  46211. } else if ( texture.isCompressedTexture || texture.isCompressedArrayTexture ) {
  46212. this._copyCompressedBufferToTexture( texture.mipmaps, textureData.texture, textureDescriptorGPU );
  46213. } else if ( texture.isCubeTexture ) {
  46214. this._copyCubeMapToTexture( options.images, textureData.texture, textureDescriptorGPU, texture.flipY, texture.premultiplyAlpha );
  46215. } else if ( texture.isVideoTexture ) {
  46216. const video = texture.source.data;
  46217. textureData.externalTexture = video;
  46218. } else {
  46219. this._copyImageToTexture( options.image, textureData.texture, textureDescriptorGPU, 0, texture.flipY, texture.premultiplyAlpha );
  46220. }
  46221. //
  46222. textureData.version = texture.version;
  46223. if ( texture.onUpdate ) texture.onUpdate( texture );
  46224. }
  46225. /**
  46226. * Returns texture data as a typed array.
  46227. *
  46228. * @async
  46229. * @param {Texture} texture - The texture to copy.
  46230. * @param {number} x - The x coordinate of the copy origin.
  46231. * @param {number} y - The y coordinate of the copy origin.
  46232. * @param {number} width - The width of the copy.
  46233. * @param {number} height - The height of the copy.
  46234. * @param {number} faceIndex - The face index.
  46235. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  46236. */
  46237. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  46238. const device = this.backend.device;
  46239. const textureData = this.backend.get( texture );
  46240. const textureGPU = textureData.texture;
  46241. const format = textureData.textureDescriptorGPU.format;
  46242. const bytesPerTexel = this._getBytesPerTexel( format );
  46243. let bytesPerRow = width * bytesPerTexel;
  46244. bytesPerRow = Math.ceil( bytesPerRow / 256 ) * 256; // Align to 256 bytes
  46245. const readBuffer = device.createBuffer(
  46246. {
  46247. size: width * height * bytesPerTexel,
  46248. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  46249. }
  46250. );
  46251. const encoder = device.createCommandEncoder();
  46252. encoder.copyTextureToBuffer(
  46253. {
  46254. texture: textureGPU,
  46255. origin: { x, y, z: faceIndex },
  46256. },
  46257. {
  46258. buffer: readBuffer,
  46259. bytesPerRow: bytesPerRow
  46260. },
  46261. {
  46262. width: width,
  46263. height: height
  46264. }
  46265. );
  46266. const typedArrayType = this._getTypedArrayType( format );
  46267. device.queue.submit( [ encoder.finish() ] );
  46268. await readBuffer.mapAsync( GPUMapMode.READ );
  46269. const buffer = readBuffer.getMappedRange();
  46270. return new typedArrayType( buffer );
  46271. }
  46272. /**
  46273. * Returns the default GPU texture for the given format.
  46274. *
  46275. * @private
  46276. * @param {string} format - The GPU format.
  46277. * @return {GPUTexture} The GPU texture.
  46278. */
  46279. _getDefaultTextureGPU( format ) {
  46280. let defaultTexture = this.defaultTexture[ format ];
  46281. if ( defaultTexture === undefined ) {
  46282. const texture = new Texture();
  46283. texture.minFilter = NearestFilter;
  46284. texture.magFilter = NearestFilter;
  46285. this.createTexture( texture, { width: 1, height: 1, format } );
  46286. this.defaultTexture[ format ] = defaultTexture = texture;
  46287. }
  46288. return this.backend.get( defaultTexture ).texture;
  46289. }
  46290. /**
  46291. * Returns the default GPU cube texture for the given format.
  46292. *
  46293. * @private
  46294. * @param {string} format - The GPU format.
  46295. * @return {GPUTexture} The GPU texture.
  46296. */
  46297. _getDefaultCubeTextureGPU( format ) {
  46298. let defaultCubeTexture = this.defaultTexture[ format ];
  46299. if ( defaultCubeTexture === undefined ) {
  46300. const texture = new CubeTexture();
  46301. texture.minFilter = NearestFilter;
  46302. texture.magFilter = NearestFilter;
  46303. this.createTexture( texture, { width: 1, height: 1, depth: 6 } );
  46304. this.defaultCubeTexture[ format ] = defaultCubeTexture = texture;
  46305. }
  46306. return this.backend.get( defaultCubeTexture ).texture;
  46307. }
  46308. /**
  46309. * Returns the default video frame used as default data in context of video textures.
  46310. *
  46311. * @private
  46312. * @return {VideoFrame} The video frame.
  46313. */
  46314. _getDefaultVideoFrame() {
  46315. let defaultVideoFrame = this.defaultVideoFrame;
  46316. if ( defaultVideoFrame === null ) {
  46317. const init = {
  46318. timestamp: 0,
  46319. codedWidth: 1,
  46320. codedHeight: 1,
  46321. format: 'RGBA',
  46322. };
  46323. this.defaultVideoFrame = defaultVideoFrame = new VideoFrame( new Uint8Array( [ 0, 0, 0, 0xff ] ), init );
  46324. }
  46325. return defaultVideoFrame;
  46326. }
  46327. /**
  46328. * Uploads cube texture image data to the GPU memory.
  46329. *
  46330. * @private
  46331. * @param {Array} images - The cube image data.
  46332. * @param {GPUTexture} textureGPU - The GPU texture.
  46333. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  46334. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  46335. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  46336. */
  46337. _copyCubeMapToTexture( images, textureGPU, textureDescriptorGPU, flipY, premultiplyAlpha ) {
  46338. for ( let i = 0; i < 6; i ++ ) {
  46339. const image = images[ i ];
  46340. const flipIndex = flipY === true ? _flipMap[ i ] : i;
  46341. if ( image.isDataTexture ) {
  46342. this._copyBufferToTexture( image.image, textureGPU, textureDescriptorGPU, flipIndex, flipY );
  46343. } else {
  46344. this._copyImageToTexture( image, textureGPU, textureDescriptorGPU, flipIndex, flipY, premultiplyAlpha );
  46345. }
  46346. }
  46347. }
  46348. /**
  46349. * Uploads texture image data to the GPU memory.
  46350. *
  46351. * @private
  46352. * @param {HTMLImageElement|ImageBitmap|HTMLCanvasElement} image - The image data.
  46353. * @param {GPUTexture} textureGPU - The GPU texture.
  46354. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  46355. * @param {number} originDepth - The origin depth.
  46356. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  46357. * @param {boolean} premultiplyAlpha - Whether the texture should have its RGB channels premultiplied by the alpha channel or not.
  46358. */
  46359. _copyImageToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, premultiplyAlpha ) {
  46360. const device = this.backend.device;
  46361. device.queue.copyExternalImageToTexture(
  46362. {
  46363. source: image,
  46364. flipY: flipY
  46365. }, {
  46366. texture: textureGPU,
  46367. mipLevel: 0,
  46368. origin: { x: 0, y: 0, z: originDepth },
  46369. premultipliedAlpha: premultiplyAlpha
  46370. }, {
  46371. width: image.width,
  46372. height: image.height,
  46373. depthOrArrayLayers: 1
  46374. }
  46375. );
  46376. }
  46377. /**
  46378. * Returns the pass utils singleton.
  46379. *
  46380. * @private
  46381. * @return {WebGPUTexturePassUtils} The utils instance.
  46382. */
  46383. _getPassUtils() {
  46384. let passUtils = this._passUtils;
  46385. if ( passUtils === null ) {
  46386. this._passUtils = passUtils = new WebGPUTexturePassUtils( this.backend.device );
  46387. }
  46388. return passUtils;
  46389. }
  46390. /**
  46391. * Generates mipmaps for the given GPU texture.
  46392. *
  46393. * @private
  46394. * @param {GPUTexture} textureGPU - The GPU texture object.
  46395. * @param {Object} textureDescriptorGPU - The texture descriptor.
  46396. * @param {number} [baseArrayLayer=0] - The index of the first array layer accessible to the texture view.
  46397. */
  46398. _generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer = 0 ) {
  46399. this._getPassUtils().generateMipmaps( textureGPU, textureDescriptorGPU, baseArrayLayer );
  46400. }
  46401. /**
  46402. * Flip the contents of the given GPU texture along its vertical axis.
  46403. *
  46404. * @private
  46405. * @param {GPUTexture} textureGPU - The GPU texture object.
  46406. * @param {Object} textureDescriptorGPU - The texture descriptor.
  46407. * @param {number} [originDepth=0] - The origin depth.
  46408. */
  46409. _flipY( textureGPU, textureDescriptorGPU, originDepth = 0 ) {
  46410. this._getPassUtils().flipY( textureGPU, textureDescriptorGPU, originDepth );
  46411. }
  46412. /**
  46413. * Uploads texture buffer data to the GPU memory.
  46414. *
  46415. * @private
  46416. * @param {Object} image - An object defining the image buffer data.
  46417. * @param {GPUTexture} textureGPU - The GPU texture.
  46418. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  46419. * @param {number} originDepth - The origin depth.
  46420. * @param {boolean} flipY - Whether to flip texture data along their vertical axis or not.
  46421. * @param {number} [depth=0] - TODO.
  46422. */
  46423. _copyBufferToTexture( image, textureGPU, textureDescriptorGPU, originDepth, flipY, depth = 0 ) {
  46424. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  46425. // @TODO: Consider to support valid buffer layouts with other formats like RGB
  46426. const device = this.backend.device;
  46427. const data = image.data;
  46428. const bytesPerTexel = this._getBytesPerTexel( textureDescriptorGPU.format );
  46429. const bytesPerRow = image.width * bytesPerTexel;
  46430. device.queue.writeTexture(
  46431. {
  46432. texture: textureGPU,
  46433. mipLevel: 0,
  46434. origin: { x: 0, y: 0, z: originDepth }
  46435. },
  46436. data,
  46437. {
  46438. offset: image.width * image.height * bytesPerTexel * depth,
  46439. bytesPerRow
  46440. },
  46441. {
  46442. width: image.width,
  46443. height: image.height,
  46444. depthOrArrayLayers: 1
  46445. } );
  46446. if ( flipY === true ) {
  46447. this._flipY( textureGPU, textureDescriptorGPU, originDepth );
  46448. }
  46449. }
  46450. /**
  46451. * Uploads compressed texture data to the GPU memory.
  46452. *
  46453. * @private
  46454. * @param {Array<Object>} mipmaps - An array with mipmap data.
  46455. * @param {GPUTexture} textureGPU - The GPU texture.
  46456. * @param {Object} textureDescriptorGPU - The GPU texture descriptor.
  46457. */
  46458. _copyCompressedBufferToTexture( mipmaps, textureGPU, textureDescriptorGPU ) {
  46459. // @TODO: Consider to use GPUCommandEncoder.copyBufferToTexture()
  46460. const device = this.backend.device;
  46461. const blockData = this._getBlockData( textureDescriptorGPU.format );
  46462. const isArrayTexture = textureDescriptorGPU.size.depthOrArrayLayers > 1;
  46463. for ( let i = 0; i < mipmaps.length; i ++ ) {
  46464. const mipmap = mipmaps[ i ];
  46465. const width = mipmap.width;
  46466. const height = mipmap.height;
  46467. const depth = isArrayTexture ? textureDescriptorGPU.size.depthOrArrayLayers : 1;
  46468. const bytesPerRow = Math.ceil( width / blockData.width ) * blockData.byteLength;
  46469. const bytesPerImage = bytesPerRow * Math.ceil( height / blockData.height );
  46470. for ( let j = 0; j < depth; j ++ ) {
  46471. device.queue.writeTexture(
  46472. {
  46473. texture: textureGPU,
  46474. mipLevel: i,
  46475. origin: { x: 0, y: 0, z: j }
  46476. },
  46477. mipmap.data,
  46478. {
  46479. offset: j * bytesPerImage,
  46480. bytesPerRow,
  46481. rowsPerImage: Math.ceil( height / blockData.height )
  46482. },
  46483. {
  46484. width: Math.ceil( width / blockData.width ) * blockData.width,
  46485. height: Math.ceil( height / blockData.height ) * blockData.height,
  46486. depthOrArrayLayers: 1
  46487. }
  46488. );
  46489. }
  46490. }
  46491. }
  46492. /**
  46493. * This method is only relevant for compressed texture formats. It returns a block
  46494. * data descriptor for the given GPU compressed texture format.
  46495. *
  46496. * @private
  46497. * @param {string} format - The GPU compressed texture format.
  46498. * @return {Object} The block data descriptor.
  46499. */
  46500. _getBlockData( format ) {
  46501. if ( format === GPUTextureFormat.BC1RGBAUnorm || format === GPUTextureFormat.BC1RGBAUnormSRGB ) return { byteLength: 8, width: 4, height: 4 }; // DXT1
  46502. if ( format === GPUTextureFormat.BC2RGBAUnorm || format === GPUTextureFormat.BC2RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT3
  46503. if ( format === GPUTextureFormat.BC3RGBAUnorm || format === GPUTextureFormat.BC3RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // DXT5
  46504. if ( format === GPUTextureFormat.BC4RUnorm || format === GPUTextureFormat.BC4RSnorm ) return { byteLength: 8, width: 4, height: 4 }; // RGTC1
  46505. if ( format === GPUTextureFormat.BC5RGUnorm || format === GPUTextureFormat.BC5RGSnorm ) return { byteLength: 16, width: 4, height: 4 }; // RGTC2
  46506. if ( format === GPUTextureFormat.BC6HRGBUFloat || format === GPUTextureFormat.BC6HRGBFloat ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (float)
  46507. if ( format === GPUTextureFormat.BC7RGBAUnorm || format === GPUTextureFormat.BC7RGBAUnormSRGB ) return { byteLength: 16, width: 4, height: 4 }; // BPTC (unorm)
  46508. if ( format === GPUTextureFormat.ETC2RGB8Unorm || format === GPUTextureFormat.ETC2RGB8UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  46509. if ( format === GPUTextureFormat.ETC2RGB8A1Unorm || format === GPUTextureFormat.ETC2RGB8A1UnormSRGB ) return { byteLength: 8, width: 4, height: 4 };
  46510. if ( format === GPUTextureFormat.ETC2RGBA8Unorm || format === GPUTextureFormat.ETC2RGBA8UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  46511. if ( format === GPUTextureFormat.EACR11Unorm ) return { byteLength: 8, width: 4, height: 4 };
  46512. if ( format === GPUTextureFormat.EACR11Snorm ) return { byteLength: 8, width: 4, height: 4 };
  46513. if ( format === GPUTextureFormat.EACRG11Unorm ) return { byteLength: 16, width: 4, height: 4 };
  46514. if ( format === GPUTextureFormat.EACRG11Snorm ) return { byteLength: 16, width: 4, height: 4 };
  46515. if ( format === GPUTextureFormat.ASTC4x4Unorm || format === GPUTextureFormat.ASTC4x4UnormSRGB ) return { byteLength: 16, width: 4, height: 4 };
  46516. if ( format === GPUTextureFormat.ASTC5x4Unorm || format === GPUTextureFormat.ASTC5x4UnormSRGB ) return { byteLength: 16, width: 5, height: 4 };
  46517. if ( format === GPUTextureFormat.ASTC5x5Unorm || format === GPUTextureFormat.ASTC5x5UnormSRGB ) return { byteLength: 16, width: 5, height: 5 };
  46518. if ( format === GPUTextureFormat.ASTC6x5Unorm || format === GPUTextureFormat.ASTC6x5UnormSRGB ) return { byteLength: 16, width: 6, height: 5 };
  46519. if ( format === GPUTextureFormat.ASTC6x6Unorm || format === GPUTextureFormat.ASTC6x6UnormSRGB ) return { byteLength: 16, width: 6, height: 6 };
  46520. if ( format === GPUTextureFormat.ASTC8x5Unorm || format === GPUTextureFormat.ASTC8x5UnormSRGB ) return { byteLength: 16, width: 8, height: 5 };
  46521. if ( format === GPUTextureFormat.ASTC8x6Unorm || format === GPUTextureFormat.ASTC8x6UnormSRGB ) return { byteLength: 16, width: 8, height: 6 };
  46522. if ( format === GPUTextureFormat.ASTC8x8Unorm || format === GPUTextureFormat.ASTC8x8UnormSRGB ) return { byteLength: 16, width: 8, height: 8 };
  46523. if ( format === GPUTextureFormat.ASTC10x5Unorm || format === GPUTextureFormat.ASTC10x5UnormSRGB ) return { byteLength: 16, width: 10, height: 5 };
  46524. if ( format === GPUTextureFormat.ASTC10x6Unorm || format === GPUTextureFormat.ASTC10x6UnormSRGB ) return { byteLength: 16, width: 10, height: 6 };
  46525. if ( format === GPUTextureFormat.ASTC10x8Unorm || format === GPUTextureFormat.ASTC10x8UnormSRGB ) return { byteLength: 16, width: 10, height: 8 };
  46526. if ( format === GPUTextureFormat.ASTC10x10Unorm || format === GPUTextureFormat.ASTC10x10UnormSRGB ) return { byteLength: 16, width: 10, height: 10 };
  46527. if ( format === GPUTextureFormat.ASTC12x10Unorm || format === GPUTextureFormat.ASTC12x10UnormSRGB ) return { byteLength: 16, width: 12, height: 10 };
  46528. if ( format === GPUTextureFormat.ASTC12x12Unorm || format === GPUTextureFormat.ASTC12x12UnormSRGB ) return { byteLength: 16, width: 12, height: 12 };
  46529. }
  46530. /**
  46531. * Converts the three.js uv wrapping constants to GPU address mode constants.
  46532. *
  46533. * @private
  46534. * @param {number} value - The three.js constant defining a uv wrapping mode.
  46535. * @return {string} The GPU address mode.
  46536. */
  46537. _convertAddressMode( value ) {
  46538. let addressMode = GPUAddressMode.ClampToEdge;
  46539. if ( value === RepeatWrapping ) {
  46540. addressMode = GPUAddressMode.Repeat;
  46541. } else if ( value === MirroredRepeatWrapping ) {
  46542. addressMode = GPUAddressMode.MirrorRepeat;
  46543. }
  46544. return addressMode;
  46545. }
  46546. /**
  46547. * Converts the three.js filter constants to GPU filter constants.
  46548. *
  46549. * @private
  46550. * @param {number} value - The three.js constant defining a filter mode.
  46551. * @return {string} The GPU filter mode.
  46552. */
  46553. _convertFilterMode( value ) {
  46554. let filterMode = GPUFilterMode.Linear;
  46555. if ( value === NearestFilter || value === NearestMipmapNearestFilter || value === NearestMipmapLinearFilter ) {
  46556. filterMode = GPUFilterMode.Nearest;
  46557. }
  46558. return filterMode;
  46559. }
  46560. /**
  46561. * Returns the bytes-per-texel value for the given GPU texture format.
  46562. *
  46563. * @private
  46564. * @param {string} format - The GPU texture format.
  46565. * @return {number} The bytes-per-texel.
  46566. */
  46567. _getBytesPerTexel( format ) {
  46568. // 8-bit formats
  46569. if ( format === GPUTextureFormat.R8Unorm ||
  46570. format === GPUTextureFormat.R8Snorm ||
  46571. format === GPUTextureFormat.R8Uint ||
  46572. format === GPUTextureFormat.R8Sint ) return 1;
  46573. // 16-bit formats
  46574. if ( format === GPUTextureFormat.R16Uint ||
  46575. format === GPUTextureFormat.R16Sint ||
  46576. format === GPUTextureFormat.R16Float ||
  46577. format === GPUTextureFormat.RG8Unorm ||
  46578. format === GPUTextureFormat.RG8Snorm ||
  46579. format === GPUTextureFormat.RG8Uint ||
  46580. format === GPUTextureFormat.RG8Sint ) return 2;
  46581. // 32-bit formats
  46582. if ( format === GPUTextureFormat.R32Uint ||
  46583. format === GPUTextureFormat.R32Sint ||
  46584. format === GPUTextureFormat.R32Float ||
  46585. format === GPUTextureFormat.RG16Uint ||
  46586. format === GPUTextureFormat.RG16Sint ||
  46587. format === GPUTextureFormat.RG16Float ||
  46588. format === GPUTextureFormat.RGBA8Unorm ||
  46589. format === GPUTextureFormat.RGBA8UnormSRGB ||
  46590. format === GPUTextureFormat.RGBA8Snorm ||
  46591. format === GPUTextureFormat.RGBA8Uint ||
  46592. format === GPUTextureFormat.RGBA8Sint ||
  46593. format === GPUTextureFormat.BGRA8Unorm ||
  46594. format === GPUTextureFormat.BGRA8UnormSRGB ||
  46595. // Packed 32-bit formats
  46596. format === GPUTextureFormat.RGB9E5UFloat ||
  46597. format === GPUTextureFormat.RGB10A2Unorm ||
  46598. format === GPUTextureFormat.RG11B10UFloat ||
  46599. format === GPUTextureFormat.Depth32Float ||
  46600. format === GPUTextureFormat.Depth24Plus ||
  46601. format === GPUTextureFormat.Depth24PlusStencil8 ||
  46602. format === GPUTextureFormat.Depth32FloatStencil8 ) return 4;
  46603. // 64-bit formats
  46604. if ( format === GPUTextureFormat.RG32Uint ||
  46605. format === GPUTextureFormat.RG32Sint ||
  46606. format === GPUTextureFormat.RG32Float ||
  46607. format === GPUTextureFormat.RGBA16Uint ||
  46608. format === GPUTextureFormat.RGBA16Sint ||
  46609. format === GPUTextureFormat.RGBA16Float ) return 8;
  46610. // 128-bit formats
  46611. if ( format === GPUTextureFormat.RGBA32Uint ||
  46612. format === GPUTextureFormat.RGBA32Sint ||
  46613. format === GPUTextureFormat.RGBA32Float ) return 16;
  46614. }
  46615. /**
  46616. * Returns the corresponding typed array type for the given GPU texture format.
  46617. *
  46618. * @private
  46619. * @param {string} format - The GPU texture format.
  46620. * @return {TypedArray.constructor} The typed array type.
  46621. */
  46622. _getTypedArrayType( format ) {
  46623. if ( format === GPUTextureFormat.R8Uint ) return Uint8Array;
  46624. if ( format === GPUTextureFormat.R8Sint ) return Int8Array;
  46625. if ( format === GPUTextureFormat.R8Unorm ) return Uint8Array;
  46626. if ( format === GPUTextureFormat.R8Snorm ) return Int8Array;
  46627. if ( format === GPUTextureFormat.RG8Uint ) return Uint8Array;
  46628. if ( format === GPUTextureFormat.RG8Sint ) return Int8Array;
  46629. if ( format === GPUTextureFormat.RG8Unorm ) return Uint8Array;
  46630. if ( format === GPUTextureFormat.RG8Snorm ) return Int8Array;
  46631. if ( format === GPUTextureFormat.RGBA8Uint ) return Uint8Array;
  46632. if ( format === GPUTextureFormat.RGBA8Sint ) return Int8Array;
  46633. if ( format === GPUTextureFormat.RGBA8Unorm ) return Uint8Array;
  46634. if ( format === GPUTextureFormat.RGBA8Snorm ) return Int8Array;
  46635. if ( format === GPUTextureFormat.R16Uint ) return Uint16Array;
  46636. if ( format === GPUTextureFormat.R16Sint ) return Int16Array;
  46637. if ( format === GPUTextureFormat.RG16Uint ) return Uint16Array;
  46638. if ( format === GPUTextureFormat.RG16Sint ) return Int16Array;
  46639. if ( format === GPUTextureFormat.RGBA16Uint ) return Uint16Array;
  46640. if ( format === GPUTextureFormat.RGBA16Sint ) return Int16Array;
  46641. if ( format === GPUTextureFormat.R16Float ) return Uint16Array;
  46642. if ( format === GPUTextureFormat.RG16Float ) return Uint16Array;
  46643. if ( format === GPUTextureFormat.RGBA16Float ) return Uint16Array;
  46644. if ( format === GPUTextureFormat.R32Uint ) return Uint32Array;
  46645. if ( format === GPUTextureFormat.R32Sint ) return Int32Array;
  46646. if ( format === GPUTextureFormat.R32Float ) return Float32Array;
  46647. if ( format === GPUTextureFormat.RG32Uint ) return Uint32Array;
  46648. if ( format === GPUTextureFormat.RG32Sint ) return Int32Array;
  46649. if ( format === GPUTextureFormat.RG32Float ) return Float32Array;
  46650. if ( format === GPUTextureFormat.RGBA32Uint ) return Uint32Array;
  46651. if ( format === GPUTextureFormat.RGBA32Sint ) return Int32Array;
  46652. if ( format === GPUTextureFormat.RGBA32Float ) return Float32Array;
  46653. if ( format === GPUTextureFormat.BGRA8Unorm ) return Uint8Array;
  46654. if ( format === GPUTextureFormat.BGRA8UnormSRGB ) return Uint8Array;
  46655. if ( format === GPUTextureFormat.RGB10A2Unorm ) return Uint32Array;
  46656. if ( format === GPUTextureFormat.RGB9E5UFloat ) return Uint32Array;
  46657. if ( format === GPUTextureFormat.RG11B10UFloat ) return Uint32Array;
  46658. if ( format === GPUTextureFormat.Depth32Float ) return Float32Array;
  46659. if ( format === GPUTextureFormat.Depth24Plus ) return Uint32Array;
  46660. if ( format === GPUTextureFormat.Depth24PlusStencil8 ) return Uint32Array;
  46661. if ( format === GPUTextureFormat.Depth32FloatStencil8 ) return Float32Array;
  46662. }
  46663. /**
  46664. * Returns the GPU dimensions for the given texture.
  46665. *
  46666. * @private
  46667. * @param {Texture} texture - The texture.
  46668. * @return {string} The GPU dimension.
  46669. */
  46670. _getDimension( texture ) {
  46671. let dimension;
  46672. if ( texture.isData3DTexture ) {
  46673. dimension = GPUTextureDimension.ThreeD;
  46674. } else {
  46675. dimension = GPUTextureDimension.TwoD;
  46676. }
  46677. return dimension;
  46678. }
  46679. }
  46680. /**
  46681. * Returns the GPU format for the given texture.
  46682. *
  46683. * @param {Texture} texture - The texture.
  46684. * @param {?GPUDevice} [device=null] - The GPU device which is used for feature detection.
  46685. * It is not necessary to apply the device for most formats.
  46686. * @return {string} The GPU format.
  46687. */
  46688. function getFormat( texture, device = null ) {
  46689. const format = texture.format;
  46690. const type = texture.type;
  46691. const colorSpace = texture.colorSpace;
  46692. const transfer = ColorManagement.getTransfer( colorSpace );
  46693. let formatGPU;
  46694. if ( texture.isCompressedTexture === true || texture.isCompressedArrayTexture === true ) {
  46695. switch ( format ) {
  46696. case RGBA_S3TC_DXT1_Format:
  46697. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC1RGBAUnormSRGB : GPUTextureFormat.BC1RGBAUnorm;
  46698. break;
  46699. case RGBA_S3TC_DXT3_Format:
  46700. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC2RGBAUnormSRGB : GPUTextureFormat.BC2RGBAUnorm;
  46701. break;
  46702. case RGBA_S3TC_DXT5_Format:
  46703. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.BC3RGBAUnormSRGB : GPUTextureFormat.BC3RGBAUnorm;
  46704. break;
  46705. case RGB_ETC2_Format:
  46706. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGB8UnormSRGB : GPUTextureFormat.ETC2RGB8Unorm;
  46707. break;
  46708. case RGBA_ETC2_EAC_Format:
  46709. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ETC2RGBA8UnormSRGB : GPUTextureFormat.ETC2RGBA8Unorm;
  46710. break;
  46711. case RGBA_ASTC_4x4_Format:
  46712. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC4x4UnormSRGB : GPUTextureFormat.ASTC4x4Unorm;
  46713. break;
  46714. case RGBA_ASTC_5x4_Format:
  46715. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x4UnormSRGB : GPUTextureFormat.ASTC5x4Unorm;
  46716. break;
  46717. case RGBA_ASTC_5x5_Format:
  46718. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC5x5UnormSRGB : GPUTextureFormat.ASTC5x5Unorm;
  46719. break;
  46720. case RGBA_ASTC_6x5_Format:
  46721. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x5UnormSRGB : GPUTextureFormat.ASTC6x5Unorm;
  46722. break;
  46723. case RGBA_ASTC_6x6_Format:
  46724. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC6x6UnormSRGB : GPUTextureFormat.ASTC6x6Unorm;
  46725. break;
  46726. case RGBA_ASTC_8x5_Format:
  46727. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x5UnormSRGB : GPUTextureFormat.ASTC8x5Unorm;
  46728. break;
  46729. case RGBA_ASTC_8x6_Format:
  46730. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x6UnormSRGB : GPUTextureFormat.ASTC8x6Unorm;
  46731. break;
  46732. case RGBA_ASTC_8x8_Format:
  46733. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC8x8UnormSRGB : GPUTextureFormat.ASTC8x8Unorm;
  46734. break;
  46735. case RGBA_ASTC_10x5_Format:
  46736. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x5UnormSRGB : GPUTextureFormat.ASTC10x5Unorm;
  46737. break;
  46738. case RGBA_ASTC_10x6_Format:
  46739. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x6UnormSRGB : GPUTextureFormat.ASTC10x6Unorm;
  46740. break;
  46741. case RGBA_ASTC_10x8_Format:
  46742. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x8UnormSRGB : GPUTextureFormat.ASTC10x8Unorm;
  46743. break;
  46744. case RGBA_ASTC_10x10_Format:
  46745. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC10x10UnormSRGB : GPUTextureFormat.ASTC10x10Unorm;
  46746. break;
  46747. case RGBA_ASTC_12x10_Format:
  46748. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x10UnormSRGB : GPUTextureFormat.ASTC12x10Unorm;
  46749. break;
  46750. case RGBA_ASTC_12x12_Format:
  46751. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.ASTC12x12UnormSRGB : GPUTextureFormat.ASTC12x12Unorm;
  46752. break;
  46753. case RGBAFormat:
  46754. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  46755. break;
  46756. default:
  46757. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  46758. }
  46759. } else {
  46760. switch ( format ) {
  46761. case RGBAFormat:
  46762. switch ( type ) {
  46763. case ByteType:
  46764. formatGPU = GPUTextureFormat.RGBA8Snorm;
  46765. break;
  46766. case ShortType:
  46767. formatGPU = GPUTextureFormat.RGBA16Sint;
  46768. break;
  46769. case UnsignedShortType:
  46770. formatGPU = GPUTextureFormat.RGBA16Uint;
  46771. break;
  46772. case UnsignedIntType:
  46773. formatGPU = GPUTextureFormat.RGBA32Uint;
  46774. break;
  46775. case IntType:
  46776. formatGPU = GPUTextureFormat.RGBA32Sint;
  46777. break;
  46778. case UnsignedByteType:
  46779. formatGPU = ( transfer === SRGBTransfer ) ? GPUTextureFormat.RGBA8UnormSRGB : GPUTextureFormat.RGBA8Unorm;
  46780. break;
  46781. case HalfFloatType:
  46782. formatGPU = GPUTextureFormat.RGBA16Float;
  46783. break;
  46784. case FloatType:
  46785. formatGPU = GPUTextureFormat.RGBA32Float;
  46786. break;
  46787. default:
  46788. console.error( 'WebGPURenderer: Unsupported texture type with RGBAFormat.', type );
  46789. }
  46790. break;
  46791. case RGBFormat:
  46792. switch ( type ) {
  46793. case UnsignedInt5999Type:
  46794. formatGPU = GPUTextureFormat.RGB9E5UFloat;
  46795. break;
  46796. default:
  46797. console.error( 'WebGPURenderer: Unsupported texture type with RGBFormat.', type );
  46798. }
  46799. break;
  46800. case RedFormat:
  46801. switch ( type ) {
  46802. case ByteType:
  46803. formatGPU = GPUTextureFormat.R8Snorm;
  46804. break;
  46805. case ShortType:
  46806. formatGPU = GPUTextureFormat.R16Sint;
  46807. break;
  46808. case UnsignedShortType:
  46809. formatGPU = GPUTextureFormat.R16Uint;
  46810. break;
  46811. case UnsignedIntType:
  46812. formatGPU = GPUTextureFormat.R32Uint;
  46813. break;
  46814. case IntType:
  46815. formatGPU = GPUTextureFormat.R32Sint;
  46816. break;
  46817. case UnsignedByteType:
  46818. formatGPU = GPUTextureFormat.R8Unorm;
  46819. break;
  46820. case HalfFloatType:
  46821. formatGPU = GPUTextureFormat.R16Float;
  46822. break;
  46823. case FloatType:
  46824. formatGPU = GPUTextureFormat.R32Float;
  46825. break;
  46826. default:
  46827. console.error( 'WebGPURenderer: Unsupported texture type with RedFormat.', type );
  46828. }
  46829. break;
  46830. case RGFormat:
  46831. switch ( type ) {
  46832. case ByteType:
  46833. formatGPU = GPUTextureFormat.RG8Snorm;
  46834. break;
  46835. case ShortType:
  46836. formatGPU = GPUTextureFormat.RG16Sint;
  46837. break;
  46838. case UnsignedShortType:
  46839. formatGPU = GPUTextureFormat.RG16Uint;
  46840. break;
  46841. case UnsignedIntType:
  46842. formatGPU = GPUTextureFormat.RG32Uint;
  46843. break;
  46844. case IntType:
  46845. formatGPU = GPUTextureFormat.RG32Sint;
  46846. break;
  46847. case UnsignedByteType:
  46848. formatGPU = GPUTextureFormat.RG8Unorm;
  46849. break;
  46850. case HalfFloatType:
  46851. formatGPU = GPUTextureFormat.RG16Float;
  46852. break;
  46853. case FloatType:
  46854. formatGPU = GPUTextureFormat.RG32Float;
  46855. break;
  46856. default:
  46857. console.error( 'WebGPURenderer: Unsupported texture type with RGFormat.', type );
  46858. }
  46859. break;
  46860. case DepthFormat:
  46861. switch ( type ) {
  46862. case UnsignedShortType:
  46863. formatGPU = GPUTextureFormat.Depth16Unorm;
  46864. break;
  46865. case UnsignedIntType:
  46866. formatGPU = GPUTextureFormat.Depth24Plus;
  46867. break;
  46868. case FloatType:
  46869. formatGPU = GPUTextureFormat.Depth32Float;
  46870. break;
  46871. default:
  46872. console.error( 'WebGPURenderer: Unsupported texture type with DepthFormat.', type );
  46873. }
  46874. break;
  46875. case DepthStencilFormat:
  46876. switch ( type ) {
  46877. case UnsignedInt248Type:
  46878. formatGPU = GPUTextureFormat.Depth24PlusStencil8;
  46879. break;
  46880. case FloatType:
  46881. if ( device && device.features.has( GPUFeatureName.Depth32FloatStencil8 ) === false ) {
  46882. console.error( 'WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.' );
  46883. }
  46884. formatGPU = GPUTextureFormat.Depth32FloatStencil8;
  46885. break;
  46886. default:
  46887. console.error( 'WebGPURenderer: Unsupported texture type with DepthStencilFormat.', type );
  46888. }
  46889. break;
  46890. case RedIntegerFormat:
  46891. switch ( type ) {
  46892. case IntType:
  46893. formatGPU = GPUTextureFormat.R32Sint;
  46894. break;
  46895. case UnsignedIntType:
  46896. formatGPU = GPUTextureFormat.R32Uint;
  46897. break;
  46898. default:
  46899. console.error( 'WebGPURenderer: Unsupported texture type with RedIntegerFormat.', type );
  46900. }
  46901. break;
  46902. case RGIntegerFormat:
  46903. switch ( type ) {
  46904. case IntType:
  46905. formatGPU = GPUTextureFormat.RG32Sint;
  46906. break;
  46907. case UnsignedIntType:
  46908. formatGPU = GPUTextureFormat.RG32Uint;
  46909. break;
  46910. default:
  46911. console.error( 'WebGPURenderer: Unsupported texture type with RGIntegerFormat.', type );
  46912. }
  46913. break;
  46914. case RGBAIntegerFormat:
  46915. switch ( type ) {
  46916. case IntType:
  46917. formatGPU = GPUTextureFormat.RGBA32Sint;
  46918. break;
  46919. case UnsignedIntType:
  46920. formatGPU = GPUTextureFormat.RGBA32Uint;
  46921. break;
  46922. default:
  46923. console.error( 'WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.', type );
  46924. }
  46925. break;
  46926. default:
  46927. console.error( 'WebGPURenderer: Unsupported texture format.', format );
  46928. }
  46929. }
  46930. return formatGPU;
  46931. }
  46932. const declarationRegexp = /^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i;
  46933. const propertiesRegexp = /([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/ig;
  46934. const wgslTypeLib$1 = {
  46935. 'f32': 'float',
  46936. 'i32': 'int',
  46937. 'u32': 'uint',
  46938. 'bool': 'bool',
  46939. 'vec2<f32>': 'vec2',
  46940. 'vec2<i32>': 'ivec2',
  46941. 'vec2<u32>': 'uvec2',
  46942. 'vec2<bool>': 'bvec2',
  46943. 'vec2f': 'vec2',
  46944. 'vec2i': 'ivec2',
  46945. 'vec2u': 'uvec2',
  46946. 'vec2b': 'bvec2',
  46947. 'vec3<f32>': 'vec3',
  46948. 'vec3<i32>': 'ivec3',
  46949. 'vec3<u32>': 'uvec3',
  46950. 'vec3<bool>': 'bvec3',
  46951. 'vec3f': 'vec3',
  46952. 'vec3i': 'ivec3',
  46953. 'vec3u': 'uvec3',
  46954. 'vec3b': 'bvec3',
  46955. 'vec4<f32>': 'vec4',
  46956. 'vec4<i32>': 'ivec4',
  46957. 'vec4<u32>': 'uvec4',
  46958. 'vec4<bool>': 'bvec4',
  46959. 'vec4f': 'vec4',
  46960. 'vec4i': 'ivec4',
  46961. 'vec4u': 'uvec4',
  46962. 'vec4b': 'bvec4',
  46963. 'mat2x2<f32>': 'mat2',
  46964. 'mat2x2f': 'mat2',
  46965. 'mat3x3<f32>': 'mat3',
  46966. 'mat3x3f': 'mat3',
  46967. 'mat4x4<f32>': 'mat4',
  46968. 'mat4x4f': 'mat4',
  46969. 'sampler': 'sampler',
  46970. 'texture_1d': 'texture',
  46971. 'texture_2d': 'texture',
  46972. 'texture_2d_array': 'texture',
  46973. 'texture_multisampled_2d': 'cubeTexture',
  46974. 'texture_depth_2d': 'depthTexture',
  46975. 'texture_depth_2d_array': 'depthTexture',
  46976. 'texture_depth_multisampled_2d': 'depthTexture',
  46977. 'texture_depth_cube': 'depthTexture',
  46978. 'texture_depth_cube_array': 'depthTexture',
  46979. 'texture_3d': 'texture3D',
  46980. 'texture_cube': 'cubeTexture',
  46981. 'texture_cube_array': 'cubeTexture',
  46982. 'texture_storage_1d': 'storageTexture',
  46983. 'texture_storage_2d': 'storageTexture',
  46984. 'texture_storage_2d_array': 'storageTexture',
  46985. 'texture_storage_3d': 'storageTexture'
  46986. };
  46987. const parse = ( source ) => {
  46988. source = source.trim();
  46989. const declaration = source.match( declarationRegexp );
  46990. if ( declaration !== null && declaration.length === 4 ) {
  46991. const inputsCode = declaration[ 2 ];
  46992. const propsMatches = [];
  46993. let match = null;
  46994. while ( ( match = propertiesRegexp.exec( inputsCode ) ) !== null ) {
  46995. propsMatches.push( { name: match[ 1 ], type: match[ 2 ] } );
  46996. }
  46997. // Process matches to correctly pair names and types
  46998. const inputs = [];
  46999. for ( let i = 0; i < propsMatches.length; i ++ ) {
  47000. const { name, type } = propsMatches[ i ];
  47001. let resolvedType = type;
  47002. if ( resolvedType.startsWith( 'ptr' ) ) {
  47003. resolvedType = 'pointer';
  47004. } else {
  47005. if ( resolvedType.startsWith( 'texture' ) ) {
  47006. resolvedType = type.split( '<' )[ 0 ];
  47007. }
  47008. resolvedType = wgslTypeLib$1[ resolvedType ];
  47009. }
  47010. inputs.push( new NodeFunctionInput( resolvedType, name ) );
  47011. }
  47012. const blockCode = source.substring( declaration[ 0 ].length );
  47013. const outputType = declaration[ 3 ] || 'void';
  47014. const name = declaration[ 1 ] !== undefined ? declaration[ 1 ] : '';
  47015. const type = wgslTypeLib$1[ outputType ] || outputType;
  47016. return {
  47017. type,
  47018. inputs,
  47019. name,
  47020. inputsCode,
  47021. blockCode,
  47022. outputType
  47023. };
  47024. } else {
  47025. throw new Error( 'FunctionNode: Function is not a WGSL code.' );
  47026. }
  47027. };
  47028. /**
  47029. * This class represents a WSL node function.
  47030. *
  47031. * @augments NodeFunction
  47032. */
  47033. class WGSLNodeFunction extends NodeFunction {
  47034. /**
  47035. * Constructs a new WGSL node function.
  47036. *
  47037. * @param {string} source - The WGSL source.
  47038. */
  47039. constructor( source ) {
  47040. const { type, inputs, name, inputsCode, blockCode, outputType } = parse( source );
  47041. super( type, inputs, name );
  47042. this.inputsCode = inputsCode;
  47043. this.blockCode = blockCode;
  47044. this.outputType = outputType;
  47045. }
  47046. /**
  47047. * This method returns the WGSL code of the node function.
  47048. *
  47049. * @param {string} [name=this.name] - The function's name.
  47050. * @return {string} The shader code.
  47051. */
  47052. getCode( name = this.name ) {
  47053. const outputType = this.outputType !== 'void' ? '-> ' + this.outputType : '';
  47054. return `fn ${ name } ( ${ this.inputsCode.trim() } ) ${ outputType }` + this.blockCode;
  47055. }
  47056. }
  47057. /**
  47058. * A WGSL node parser.
  47059. *
  47060. * @augments NodeParser
  47061. */
  47062. class WGSLNodeParser extends NodeParser {
  47063. /**
  47064. * The method parses the given WGSL code an returns a node function.
  47065. *
  47066. * @param {string} source - The WGSL code.
  47067. * @return {WGSLNodeFunction} A node function.
  47068. */
  47069. parseFunction( source ) {
  47070. return new WGSLNodeFunction( source );
  47071. }
  47072. }
  47073. // GPUShaderStage is not defined in browsers not supporting WebGPU
  47074. const GPUShaderStage = ( typeof self !== 'undefined' ) ? self.GPUShaderStage : { VERTEX: 1, FRAGMENT: 2, COMPUTE: 4 };
  47075. const accessNames = {
  47076. [ NodeAccess.READ_ONLY ]: 'read',
  47077. [ NodeAccess.WRITE_ONLY ]: 'write',
  47078. [ NodeAccess.READ_WRITE ]: 'read_write'
  47079. };
  47080. const wrapNames = {
  47081. [ RepeatWrapping ]: 'repeat',
  47082. [ ClampToEdgeWrapping ]: 'clamp',
  47083. [ MirroredRepeatWrapping ]: 'mirror'
  47084. };
  47085. const gpuShaderStageLib = {
  47086. 'vertex': GPUShaderStage ? GPUShaderStage.VERTEX : 1,
  47087. 'fragment': GPUShaderStage ? GPUShaderStage.FRAGMENT : 2,
  47088. 'compute': GPUShaderStage ? GPUShaderStage.COMPUTE : 4
  47089. };
  47090. const supports = {
  47091. instance: true,
  47092. swizzleAssign: false,
  47093. storageBuffer: true
  47094. };
  47095. const wgslFnOpLib = {
  47096. '^^': 'tsl_xor'
  47097. };
  47098. const wgslTypeLib = {
  47099. float: 'f32',
  47100. int: 'i32',
  47101. uint: 'u32',
  47102. bool: 'bool',
  47103. color: 'vec3<f32>',
  47104. vec2: 'vec2<f32>',
  47105. ivec2: 'vec2<i32>',
  47106. uvec2: 'vec2<u32>',
  47107. bvec2: 'vec2<bool>',
  47108. vec3: 'vec3<f32>',
  47109. ivec3: 'vec3<i32>',
  47110. uvec3: 'vec3<u32>',
  47111. bvec3: 'vec3<bool>',
  47112. vec4: 'vec4<f32>',
  47113. ivec4: 'vec4<i32>',
  47114. uvec4: 'vec4<u32>',
  47115. bvec4: 'vec4<bool>',
  47116. mat2: 'mat2x2<f32>',
  47117. mat3: 'mat3x3<f32>',
  47118. mat4: 'mat4x4<f32>'
  47119. };
  47120. const wgslCodeCache = {};
  47121. const wgslPolyfill = {
  47122. tsl_xor: new CodeNode( 'fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }' ),
  47123. mod_float: new CodeNode( 'fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }' ),
  47124. mod_vec2: new CodeNode( 'fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }' ),
  47125. mod_vec3: new CodeNode( 'fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }' ),
  47126. mod_vec4: new CodeNode( 'fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }' ),
  47127. equals_bool: new CodeNode( 'fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }' ),
  47128. 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 ); }' ),
  47129. 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 ); }' ),
  47130. 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 ); }' ),
  47131. repeatWrapping_float: new CodeNode( 'fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }' ),
  47132. 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 ); }' ),
  47133. clampWrapping_float: new CodeNode( 'fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }' ),
  47134. biquadraticTexture: new CodeNode( /* wgsl */`
  47135. fn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {
  47136. let res = vec2f( iRes );
  47137. let uvScaled = coord * res;
  47138. let uvWrapping = ( ( uvScaled % res ) + res ) % res;
  47139. // https://www.shadertoy.com/view/WtyXRy
  47140. let uv = uvWrapping - 0.5;
  47141. let iuv = floor( uv );
  47142. let f = fract( uv );
  47143. let rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );
  47144. let rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );
  47145. let rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );
  47146. let rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );
  47147. return mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );
  47148. }
  47149. ` )
  47150. };
  47151. const wgslMethods = {
  47152. dFdx: 'dpdx',
  47153. dFdy: '- dpdy',
  47154. mod_float: 'tsl_mod_float',
  47155. mod_vec2: 'tsl_mod_vec2',
  47156. mod_vec3: 'tsl_mod_vec3',
  47157. mod_vec4: 'tsl_mod_vec4',
  47158. equals_bool: 'tsl_equals_bool',
  47159. equals_bvec2: 'tsl_equals_bvec2',
  47160. equals_bvec3: 'tsl_equals_bvec3',
  47161. equals_bvec4: 'tsl_equals_bvec4',
  47162. inversesqrt: 'inverseSqrt',
  47163. bitcast: 'bitcast<f32>'
  47164. };
  47165. // WebGPU issue: does not support pow() with negative base on Windows
  47166. if ( typeof navigator !== 'undefined' && /Windows/g.test( navigator.userAgent ) ) {
  47167. wgslPolyfill.pow_float = new CodeNode( 'fn tsl_pow_float( a : f32, b : f32 ) -> f32 { return select( -pow( -a, b ), pow( a, b ), a > 0.0 ); }' );
  47168. wgslPolyfill.pow_vec2 = new CodeNode( 'fn tsl_pow_vec2( a : vec2f, b : vec2f ) -> vec2f { return vec2f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ) ); }', [ wgslPolyfill.pow_float ] );
  47169. wgslPolyfill.pow_vec3 = new CodeNode( 'fn tsl_pow_vec3( a : vec3f, b : vec3f ) -> vec3f { return vec3f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ) ); }', [ wgslPolyfill.pow_float ] );
  47170. wgslPolyfill.pow_vec4 = new CodeNode( 'fn tsl_pow_vec4( a : vec4f, b : vec4f ) -> vec4f { return vec4f( tsl_pow_float( a.x, b.x ), tsl_pow_float( a.y, b.y ), tsl_pow_float( a.z, b.z ), tsl_pow_float( a.w, b.w ) ); }', [ wgslPolyfill.pow_float ] );
  47171. wgslMethods.pow_float = 'tsl_pow_float';
  47172. wgslMethods.pow_vec2 = 'tsl_pow_vec2';
  47173. wgslMethods.pow_vec3 = 'tsl_pow_vec3';
  47174. wgslMethods.pow_vec4 = 'tsl_pow_vec4';
  47175. }
  47176. //
  47177. let diagnostics = '';
  47178. if ( ( typeof navigator !== 'undefined' && /Firefox|Deno/g.test( navigator.userAgent ) ) !== true ) {
  47179. diagnostics += 'diagnostic( off, derivative_uniformity );\n';
  47180. }
  47181. /**
  47182. * A node builder targeting WGSL.
  47183. *
  47184. * This module generates WGSL shader code from node materials and also
  47185. * generates the respective bindings and vertex buffer definitions. These
  47186. * data are later used by the renderer to create render and compute pipelines
  47187. * for render objects.
  47188. *
  47189. * @augments NodeBuilder
  47190. */
  47191. class WGSLNodeBuilder extends NodeBuilder {
  47192. /**
  47193. * Constructs a new WGSL node builder renderer.
  47194. *
  47195. * @param {Object3D} object - The 3D object.
  47196. * @param {Renderer} renderer - The renderer.
  47197. */
  47198. constructor( object, renderer ) {
  47199. super( object, renderer, new WGSLNodeParser() );
  47200. /**
  47201. * A dictionary that holds for each shader stage ('vertex', 'fragment', 'compute')
  47202. * another dictionary which manages UBOs per group ('render','frame','object').
  47203. *
  47204. * @type {Object<string,Object<string,NodeUniformsGroup>>}
  47205. */
  47206. this.uniformGroups = {};
  47207. /**
  47208. * A dictionary that holds for each shader stage a Map of builtins.
  47209. *
  47210. * @type {Object<string,Map<string,Object>>}
  47211. */
  47212. this.builtins = {};
  47213. /**
  47214. * A dictionary that holds for each shader stage a Set of directives.
  47215. *
  47216. * @type {Object<string,Set<string>>}
  47217. */
  47218. this.directives = {};
  47219. /**
  47220. * A map for managing scope arrays. Only relevant for when using
  47221. * {@link WorkgroupInfoNode} in context of compute shaders.
  47222. *
  47223. * @type {Map<string,Object>}
  47224. */
  47225. this.scopedArrays = new Map();
  47226. }
  47227. /**
  47228. * Checks if the given texture requires a manual conversion to the working color space.
  47229. *
  47230. * @param {Texture} texture - The texture to check.
  47231. * @return {boolean} Whether the given texture requires a conversion to working color space or not.
  47232. */
  47233. needsToWorkingColorSpace( texture ) {
  47234. return texture.isVideoTexture === true && texture.colorSpace !== NoColorSpace;
  47235. }
  47236. /**
  47237. * Generates the WGSL snippet for sampled textures.
  47238. *
  47239. * @private
  47240. * @param {Texture} texture - The texture.
  47241. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47242. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47243. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47244. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47245. * @return {string} The WGSL snippet.
  47246. */
  47247. _generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47248. if ( shaderStage === 'fragment' ) {
  47249. if ( depthSnippet ) {
  47250. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet } )`;
  47251. } else {
  47252. return `textureSample( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet } )`;
  47253. }
  47254. } else {
  47255. return this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, '0', depthSnippet );
  47256. }
  47257. }
  47258. /**
  47259. * Generates the WGSL snippet when sampling video textures.
  47260. *
  47261. * @private
  47262. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  47263. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47264. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47265. * @return {string} The WGSL snippet.
  47266. */
  47267. _generateVideoSample( textureProperty, uvSnippet, shaderStage = this.shaderStage ) {
  47268. if ( shaderStage === 'fragment' ) {
  47269. return `textureSampleBaseClampToEdge( ${ textureProperty }, ${ textureProperty }_sampler, vec2<f32>( ${ uvSnippet }.x, 1.0 - ${ uvSnippet }.y ) )`;
  47270. } else {
  47271. console.error( `WebGPURenderer: THREE.VideoTexture does not support ${ shaderStage } shader.` );
  47272. }
  47273. }
  47274. /**
  47275. * Generates the WGSL snippet when sampling textures with explicit mip level.
  47276. *
  47277. * @private
  47278. * @param {Texture} texture - The texture.
  47279. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47280. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47281. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47282. * @param {string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47283. * @return {string} The WGSL snippet.
  47284. */
  47285. _generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet ) {
  47286. if ( this.isUnfilterable( texture ) === false ) {
  47287. return `textureSampleLevel( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ levelSnippet } )`;
  47288. } else if ( this.isFilteredTexture( texture ) ) {
  47289. return this.generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet );
  47290. } else {
  47291. return this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet );
  47292. }
  47293. }
  47294. /**
  47295. * Generates a wrap function used in context of textures.
  47296. *
  47297. * @param {Texture} texture - The texture to generate the function for.
  47298. * @return {string} The name of the generated function.
  47299. */
  47300. generateWrapFunction( texture ) {
  47301. const functionName = `tsl_coord_${ wrapNames[ texture.wrapS ] }S_${ wrapNames[ texture.wrapT ] }_${ texture.isData3DTexture ? '3d' : '2d' }T`;
  47302. let nodeCode = wgslCodeCache[ functionName ];
  47303. if ( nodeCode === undefined ) {
  47304. const includes = [];
  47305. // For 3D textures, use vec3f; for texture arrays, keep vec2f since array index is separate
  47306. const coordType = texture.isData3DTexture ? 'vec3f' : 'vec2f';
  47307. let code = `fn ${ functionName }( coord : ${ coordType } ) -> ${ coordType } {\n\n\treturn ${ coordType }(\n`;
  47308. const addWrapSnippet = ( wrap, axis ) => {
  47309. if ( wrap === RepeatWrapping ) {
  47310. includes.push( wgslPolyfill.repeatWrapping_float );
  47311. code += `\t\ttsl_repeatWrapping_float( coord.${ axis } )`;
  47312. } else if ( wrap === ClampToEdgeWrapping ) {
  47313. includes.push( wgslPolyfill.clampWrapping_float );
  47314. code += `\t\ttsl_clampWrapping_float( coord.${ axis } )`;
  47315. } else if ( wrap === MirroredRepeatWrapping ) {
  47316. includes.push( wgslPolyfill.mirrorWrapping_float );
  47317. code += `\t\ttsl_mirrorWrapping_float( coord.${ axis } )`;
  47318. } else {
  47319. code += `\t\tcoord.${ axis }`;
  47320. console.warn( `WebGPURenderer: Unsupported texture wrap type "${ wrap }" for vertex shader.` );
  47321. }
  47322. };
  47323. addWrapSnippet( texture.wrapS, 'x' );
  47324. code += ',\n';
  47325. addWrapSnippet( texture.wrapT, 'y' );
  47326. if ( texture.isData3DTexture ) {
  47327. code += ',\n';
  47328. addWrapSnippet( texture.wrapR, 'z' );
  47329. }
  47330. code += '\n\t);\n\n}\n';
  47331. wgslCodeCache[ functionName ] = nodeCode = new CodeNode( code, includes );
  47332. }
  47333. nodeCode.build( this );
  47334. return functionName;
  47335. }
  47336. /**
  47337. * Generates the array declaration string.
  47338. *
  47339. * @param {string} type - The type.
  47340. * @param {?number} [count] - The count.
  47341. * @return {string} The generated value as a shader string.
  47342. */
  47343. generateArrayDeclaration( type, count ) {
  47344. return `array< ${ this.getType( type ) }, ${ count } >`;
  47345. }
  47346. /**
  47347. * Generates a WGSL variable that holds the texture dimension of the given texture.
  47348. * It also returns information about the number of layers (elements) of an arrayed
  47349. * texture as well as the cube face count of cube textures.
  47350. *
  47351. * @param {Texture} texture - The texture to generate the function for.
  47352. * @param {string} textureProperty - The name of the video texture uniform in the shader.
  47353. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47354. * @return {string} The name of the dimension variable.
  47355. */
  47356. generateTextureDimension( texture, textureProperty, levelSnippet ) {
  47357. const textureData = this.getDataFromNode( texture, this.shaderStage, this.globalCache );
  47358. if ( textureData.dimensionsSnippet === undefined ) textureData.dimensionsSnippet = {};
  47359. let textureDimensionNode = textureData.dimensionsSnippet[ levelSnippet ];
  47360. if ( textureData.dimensionsSnippet[ levelSnippet ] === undefined ) {
  47361. let textureDimensionsParams;
  47362. let dimensionType;
  47363. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  47364. const isMultisampled = primarySamples > 1;
  47365. if ( texture.isData3DTexture ) {
  47366. dimensionType = 'vec3<u32>';
  47367. } else {
  47368. // Regular 2D textures, depth textures, etc.
  47369. dimensionType = 'vec2<u32>';
  47370. }
  47371. // Build parameters string based on texture type and multisampling
  47372. if ( isMultisampled || texture.isVideoTexture || texture.isStorageTexture ) {
  47373. textureDimensionsParams = textureProperty;
  47374. } else {
  47375. textureDimensionsParams = `${textureProperty}${levelSnippet ? `, u32( ${ levelSnippet } )` : ''}`;
  47376. }
  47377. textureDimensionNode = new VarNode( new ExpressionNode( `textureDimensions( ${ textureDimensionsParams } )`, dimensionType ) );
  47378. textureData.dimensionsSnippet[ levelSnippet ] = textureDimensionNode;
  47379. if ( texture.isArrayTexture || texture.isDataArrayTexture || texture.isData3DTexture ) {
  47380. textureData.arrayLayerCount = new VarNode(
  47381. new ExpressionNode(
  47382. `textureNumLayers(${textureProperty})`,
  47383. 'u32'
  47384. )
  47385. );
  47386. }
  47387. // For cube textures, we know it's always 6 faces
  47388. if ( texture.isTextureCube ) {
  47389. textureData.cubeFaceCount = new VarNode(
  47390. new ExpressionNode( '6u', 'u32' )
  47391. );
  47392. }
  47393. }
  47394. return textureDimensionNode.build( this );
  47395. }
  47396. /**
  47397. * Generates the WGSL snippet for a manual filtered texture.
  47398. *
  47399. * @param {Texture} texture - The texture.
  47400. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47401. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47402. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47403. * @return {string} The WGSL snippet.
  47404. */
  47405. generateFilteredTexture( texture, textureProperty, uvSnippet, levelSnippet = '0u' ) {
  47406. this._include( 'biquadraticTexture' );
  47407. const wrapFunction = this.generateWrapFunction( texture );
  47408. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  47409. return `tsl_biquadraticTexture( ${ textureProperty }, ${ wrapFunction }( ${ uvSnippet } ), ${ textureDimension }, u32( ${ levelSnippet } ) )`;
  47410. }
  47411. /**
  47412. * Generates the WGSL snippet for a texture lookup with explicit level-of-detail.
  47413. * Since it's a lookup, no sampling or filtering is applied.
  47414. *
  47415. * @param {Texture} texture - The texture.
  47416. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47417. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47418. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47419. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47420. * @return {string} The WGSL snippet.
  47421. */
  47422. generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, levelSnippet = '0u' ) {
  47423. const wrapFunction = this.generateWrapFunction( texture );
  47424. const textureDimension = this.generateTextureDimension( texture, textureProperty, levelSnippet );
  47425. const vecType = texture.isData3DTexture ? 'vec3' : 'vec2';
  47426. const coordSnippet = `${ vecType }<u32>( ${ wrapFunction }( ${ uvSnippet } ) * ${ vecType }<f32>( ${ textureDimension } ) )`;
  47427. return this.generateTextureLoad( texture, textureProperty, coordSnippet, depthSnippet, levelSnippet );
  47428. }
  47429. /**
  47430. * Generates the WGSL snippet that reads a single texel from a texture without sampling or filtering.
  47431. *
  47432. * @param {Texture} texture - The texture.
  47433. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47434. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47435. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47436. * @param {string} [levelSnippet='0u'] - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47437. * @return {string} The WGSL snippet.
  47438. */
  47439. generateTextureLoad( texture, textureProperty, uvIndexSnippet, depthSnippet, levelSnippet = '0u' ) {
  47440. let snippet;
  47441. if ( texture.isVideoTexture === true ) {
  47442. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet } )`;
  47443. } else if ( depthSnippet ) {
  47444. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, u32( ${ levelSnippet } ) )`;
  47445. } else {
  47446. snippet = `textureLoad( ${ textureProperty }, ${ uvIndexSnippet }, u32( ${ levelSnippet } ) )`;
  47447. if ( this.renderer.backend.compatibilityMode && texture.isDepthTexture ) {
  47448. snippet += '.x';
  47449. }
  47450. }
  47451. return snippet;
  47452. }
  47453. /**
  47454. * Generates the WGSL snippet that writes a single texel to a texture.
  47455. *
  47456. * @param {Texture} texture - The texture.
  47457. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47458. * @param {string} uvIndexSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47459. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47460. * @param {string} valueSnippet - A WGSL snippet that represent the new texel value.
  47461. * @return {string} The WGSL snippet.
  47462. */
  47463. generateTextureStore( texture, textureProperty, uvIndexSnippet, depthSnippet, valueSnippet ) {
  47464. let snippet;
  47465. if ( depthSnippet ) {
  47466. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ depthSnippet }, ${ valueSnippet } )`;
  47467. } else {
  47468. snippet = `textureStore( ${ textureProperty }, ${ uvIndexSnippet }, ${ valueSnippet } )`;
  47469. }
  47470. return snippet;
  47471. }
  47472. /**
  47473. * Returns `true` if the sampled values of the given texture should be compared against a reference value.
  47474. *
  47475. * @param {Texture} texture - The texture.
  47476. * @return {boolean} Whether the sampled values of the given texture should be compared against a reference value or not.
  47477. */
  47478. isSampleCompare( texture ) {
  47479. return texture.isDepthTexture === true && texture.compareFunction !== null;
  47480. }
  47481. /**
  47482. * Returns `true` if the given texture is unfilterable.
  47483. *
  47484. * @param {Texture} texture - The texture.
  47485. * @return {boolean} Whether the given texture is unfilterable or not.
  47486. */
  47487. isUnfilterable( texture ) {
  47488. return this.getComponentTypeFromTexture( texture ) !== 'float' ||
  47489. ( ! this.isAvailable( 'float32Filterable' ) && texture.isDataTexture === true && texture.type === FloatType ) ||
  47490. ( this.isSampleCompare( texture ) === false && texture.minFilter === NearestFilter && texture.magFilter === NearestFilter ) ||
  47491. this.renderer.backend.utils.getTextureSampleData( texture ).primarySamples > 1;
  47492. }
  47493. /**
  47494. * Generates the WGSL snippet for sampling/loading the given texture.
  47495. *
  47496. * @param {Texture} texture - The texture.
  47497. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47498. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47499. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47500. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47501. * @return {string} The WGSL snippet.
  47502. */
  47503. generateTexture( texture, textureProperty, uvSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47504. let snippet = null;
  47505. if ( texture.isVideoTexture === true ) {
  47506. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  47507. } else if ( this.isUnfilterable( texture ) ) {
  47508. snippet = this.generateTextureLod( texture, textureProperty, uvSnippet, depthSnippet, '0', shaderStage );
  47509. } else {
  47510. snippet = this._generateTextureSample( texture, textureProperty, uvSnippet, depthSnippet, shaderStage );
  47511. }
  47512. return snippet;
  47513. }
  47514. /**
  47515. * Generates the WGSL snippet for sampling/loading the given texture using explicit gradients.
  47516. *
  47517. * @param {Texture} texture - The texture.
  47518. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47519. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47520. * @param {Array<string>} gradSnippet - An array holding both gradient WGSL snippets.
  47521. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47522. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47523. * @return {string} The WGSL snippet.
  47524. */
  47525. generateTextureGrad( texture, textureProperty, uvSnippet, gradSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47526. if ( shaderStage === 'fragment' ) {
  47527. // TODO handle i32 or u32 --> uvSnippet, array_index: A, ddx, ddy
  47528. return `textureSampleGrad( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ gradSnippet[ 0 ] }, ${ gradSnippet[ 1 ] } )`;
  47529. } else {
  47530. console.error( `WebGPURenderer: THREE.TextureNode.gradient() does not support ${ shaderStage } shader.` );
  47531. }
  47532. }
  47533. /**
  47534. * Generates the WGSL snippet for sampling a depth texture and comparing the sampled depth values
  47535. * against a reference value.
  47536. *
  47537. * @param {Texture} texture - The texture.
  47538. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47539. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47540. * @param {string} compareSnippet - A WGSL snippet that represents the reference value.
  47541. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47542. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47543. * @return {string} The WGSL snippet.
  47544. */
  47545. generateTextureCompare( texture, textureProperty, uvSnippet, compareSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47546. if ( shaderStage === 'fragment' ) {
  47547. if ( texture.isDepthTexture === true && texture.isArrayTexture === true ) {
  47548. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ depthSnippet }, ${ compareSnippet } )`;
  47549. }
  47550. return `textureSampleCompare( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ compareSnippet } )`;
  47551. } else {
  47552. console.error( `WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${ shaderStage } shader.` );
  47553. }
  47554. }
  47555. /**
  47556. * Generates the WGSL snippet when sampling textures with explicit mip level.
  47557. *
  47558. * @param {Texture} texture - The texture.
  47559. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47560. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47561. * @param {string} levelSnippet - A WGSL snippet that represents the mip level, with level 0 containing a full size version of the texture.
  47562. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47563. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47564. * @return {string} The WGSL snippet.
  47565. */
  47566. generateTextureLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47567. let snippet = null;
  47568. if ( texture.isVideoTexture === true ) {
  47569. snippet = this._generateVideoSample( textureProperty, uvSnippet, shaderStage );
  47570. } else {
  47571. snippet = this._generateTextureSampleLevel( texture, textureProperty, uvSnippet, levelSnippet, depthSnippet );
  47572. }
  47573. return snippet;
  47574. }
  47575. /**
  47576. * Generates the WGSL snippet when sampling textures with a bias to the mip level.
  47577. *
  47578. * @param {Texture} texture - The texture.
  47579. * @param {string} textureProperty - The name of the texture uniform in the shader.
  47580. * @param {string} uvSnippet - A WGSL snippet that represents texture coordinates used for sampling.
  47581. * @param {string} biasSnippet - A WGSL snippet that represents the bias to apply to the mip level before sampling.
  47582. * @param {?string} depthSnippet - A WGSL snippet that represents 0-based texture array index to sample.
  47583. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47584. * @return {string} The WGSL snippet.
  47585. */
  47586. generateTextureBias( texture, textureProperty, uvSnippet, biasSnippet, depthSnippet, shaderStage = this.shaderStage ) {
  47587. if ( shaderStage === 'fragment' ) {
  47588. return `textureSampleBias( ${ textureProperty }, ${ textureProperty }_sampler, ${ uvSnippet }, ${ biasSnippet } )`;
  47589. } else {
  47590. console.error( `WebGPURenderer: THREE.TextureNode.biasNode does not support ${ shaderStage } shader.` );
  47591. }
  47592. }
  47593. /**
  47594. * Returns a WGSL snippet that represents the property name of the given node.
  47595. *
  47596. * @param {Node} node - The node.
  47597. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47598. * @return {string} The property name.
  47599. */
  47600. getPropertyName( node, shaderStage = this.shaderStage ) {
  47601. if ( node.isNodeVarying === true && node.needsInterpolation === true ) {
  47602. if ( shaderStage === 'vertex' ) {
  47603. return `varyings.${ node.name }`;
  47604. }
  47605. } else if ( node.isNodeUniform === true ) {
  47606. const name = node.name;
  47607. const type = node.type;
  47608. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  47609. return name;
  47610. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  47611. if ( this.isCustomStruct( node ) ) {
  47612. return name;
  47613. }
  47614. return name + '.value';
  47615. } else {
  47616. return node.groupNode.name + '.' + name;
  47617. }
  47618. }
  47619. return super.getPropertyName( node );
  47620. }
  47621. /**
  47622. * Returns the output struct name.
  47623. *
  47624. * @return {string} The name of the output struct.
  47625. */
  47626. getOutputStructName() {
  47627. return 'output';
  47628. }
  47629. /**
  47630. * Returns the native shader operator name for a given generic name.
  47631. *
  47632. * @param {string} op - The operator name to resolve.
  47633. * @return {?string} The resolved operator name.
  47634. */
  47635. getFunctionOperator( op ) {
  47636. const fnOp = wgslFnOpLib[ op ];
  47637. if ( fnOp !== undefined ) {
  47638. this._include( fnOp );
  47639. return fnOp;
  47640. }
  47641. return null;
  47642. }
  47643. /**
  47644. * Returns the node access for the given node and shader stage.
  47645. *
  47646. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  47647. * @param {string} shaderStage - The shader stage.
  47648. * @return {string} The node access.
  47649. */
  47650. getNodeAccess( node, shaderStage ) {
  47651. if ( shaderStage !== 'compute' )
  47652. return NodeAccess.READ_ONLY;
  47653. return node.access;
  47654. }
  47655. /**
  47656. * Returns A WGSL snippet representing the storage access.
  47657. *
  47658. * @param {StorageTextureNode|StorageBufferNode} node - The storage node.
  47659. * @param {string} shaderStage - The shader stage.
  47660. * @return {string} The WGSL snippet representing the storage access.
  47661. */
  47662. getStorageAccess( node, shaderStage ) {
  47663. return accessNames[ this.getNodeAccess( node, shaderStage ) ];
  47664. }
  47665. /**
  47666. * This method is one of the more important ones since it's responsible
  47667. * for generating a matching binding instance for the given uniform node.
  47668. *
  47669. * These bindings are later used in the renderer to create bind groups
  47670. * and layouts.
  47671. *
  47672. * @param {UniformNode} node - The uniform node.
  47673. * @param {string} type - The node data type.
  47674. * @param {string} shaderStage - The shader stage.
  47675. * @param {?string} [name=null] - An optional uniform name.
  47676. * @return {NodeUniform} The node uniform object.
  47677. */
  47678. getUniformFromNode( node, type, shaderStage, name = null ) {
  47679. const uniformNode = super.getUniformFromNode( node, type, shaderStage, name );
  47680. const nodeData = this.getDataFromNode( node, shaderStage, this.globalCache );
  47681. if ( nodeData.uniformGPU === undefined ) {
  47682. let uniformGPU;
  47683. const group = node.groupNode;
  47684. const groupName = group.name;
  47685. const bindings = this.getBindGroupArray( groupName, shaderStage );
  47686. if ( type === 'texture' || type === 'cubeTexture' || type === 'storageTexture' || type === 'texture3D' ) {
  47687. let texture = null;
  47688. const access = this.getNodeAccess( node, shaderStage );
  47689. if ( type === 'texture' || type === 'storageTexture' ) {
  47690. texture = new NodeSampledTexture( uniformNode.name, uniformNode.node, group, access );
  47691. } else if ( type === 'cubeTexture' ) {
  47692. texture = new NodeSampledCubeTexture( uniformNode.name, uniformNode.node, group, access );
  47693. } else if ( type === 'texture3D' ) {
  47694. texture = new NodeSampledTexture3D( uniformNode.name, uniformNode.node, group, access );
  47695. }
  47696. texture.store = node.isStorageTextureNode === true;
  47697. texture.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47698. if ( this.isUnfilterable( node.value ) === false && texture.store === false ) {
  47699. const sampler = new NodeSampler( `${ uniformNode.name }_sampler`, uniformNode.node, group );
  47700. sampler.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47701. bindings.push( sampler, texture );
  47702. uniformGPU = [ sampler, texture ];
  47703. } else {
  47704. bindings.push( texture );
  47705. uniformGPU = [ texture ];
  47706. }
  47707. } else if ( type === 'buffer' || type === 'storageBuffer' || type === 'indirectStorageBuffer' ) {
  47708. const bufferClass = type === 'buffer' ? NodeUniformBuffer : NodeStorageBuffer;
  47709. const buffer = new bufferClass( node, group );
  47710. buffer.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47711. bindings.push( buffer );
  47712. uniformGPU = buffer;
  47713. uniformNode.name = name ? name : 'NodeBuffer_' + uniformNode.id;
  47714. } else {
  47715. const uniformsStage = this.uniformGroups[ shaderStage ] || ( this.uniformGroups[ shaderStage ] = {} );
  47716. let uniformsGroup = uniformsStage[ groupName ];
  47717. if ( uniformsGroup === undefined ) {
  47718. uniformsGroup = new NodeUniformsGroup( groupName, group );
  47719. uniformsGroup.setVisibility( gpuShaderStageLib[ shaderStage ] );
  47720. uniformsStage[ groupName ] = uniformsGroup;
  47721. bindings.push( uniformsGroup );
  47722. }
  47723. uniformGPU = this.getNodeUniform( uniformNode, type );
  47724. uniformsGroup.addUniform( uniformGPU );
  47725. }
  47726. nodeData.uniformGPU = uniformGPU;
  47727. }
  47728. return uniformNode;
  47729. }
  47730. /**
  47731. * This method should be used whenever builtins are required in nodes.
  47732. * The internal builtins data structure will make sure builtins are
  47733. * defined in the WGSL source.
  47734. *
  47735. * @param {string} name - The builtin name.
  47736. * @param {string} property - The property name.
  47737. * @param {string} type - The node data type.
  47738. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47739. * @return {string} The property name.
  47740. */
  47741. getBuiltin( name, property, type, shaderStage = this.shaderStage ) {
  47742. const map = this.builtins[ shaderStage ] || ( this.builtins[ shaderStage ] = new Map() );
  47743. if ( map.has( name ) === false ) {
  47744. map.set( name, {
  47745. name,
  47746. property,
  47747. type
  47748. } );
  47749. }
  47750. return property;
  47751. }
  47752. /**
  47753. * Returns `true` if the given builtin is defined in the given shader stage.
  47754. *
  47755. * @param {string} name - The builtin name.
  47756. * @param {string} [shaderStage=this.shaderStage] - The shader stage this code snippet is generated for.
  47757. * @return {boolean} Whether the given builtin is defined in the given shader stage or not.
  47758. */
  47759. hasBuiltin( name, shaderStage = this.shaderStage ) {
  47760. return ( this.builtins[ shaderStage ] !== undefined && this.builtins[ shaderStage ].has( name ) );
  47761. }
  47762. /**
  47763. * Returns the vertex index builtin.
  47764. *
  47765. * @return {string} The vertex index.
  47766. */
  47767. getVertexIndex() {
  47768. if ( this.shaderStage === 'vertex' ) {
  47769. return this.getBuiltin( 'vertex_index', 'vertexIndex', 'u32', 'attribute' );
  47770. }
  47771. return 'vertexIndex';
  47772. }
  47773. /**
  47774. * Builds the given shader node.
  47775. *
  47776. * @param {ShaderNodeInternal} shaderNode - The shader node.
  47777. * @return {string} The WGSL function code.
  47778. */
  47779. buildFunctionCode( shaderNode ) {
  47780. const layout = shaderNode.layout;
  47781. const flowData = this.flowShaderNode( shaderNode );
  47782. const parameters = [];
  47783. for ( const input of layout.inputs ) {
  47784. parameters.push( input.name + ' : ' + this.getType( input.type ) );
  47785. }
  47786. //
  47787. let code = `fn ${ layout.name }( ${ parameters.join( ', ' ) } ) -> ${ this.getType( layout.type ) } {
  47788. ${ flowData.vars }
  47789. ${ flowData.code }
  47790. `;
  47791. if ( flowData.result ) {
  47792. code += `\treturn ${ flowData.result };\n`;
  47793. }
  47794. code += '\n}\n';
  47795. //
  47796. return code;
  47797. }
  47798. /**
  47799. * Returns the instance index builtin.
  47800. *
  47801. * @return {string} The instance index.
  47802. */
  47803. getInstanceIndex() {
  47804. if ( this.shaderStage === 'vertex' ) {
  47805. return this.getBuiltin( 'instance_index', 'instanceIndex', 'u32', 'attribute' );
  47806. }
  47807. return 'instanceIndex';
  47808. }
  47809. /**
  47810. * Returns the invocation local index builtin.
  47811. *
  47812. * @return {string} The invocation local index.
  47813. */
  47814. getInvocationLocalIndex() {
  47815. return this.getBuiltin( 'local_invocation_index', 'invocationLocalIndex', 'u32', 'attribute' );
  47816. }
  47817. /**
  47818. * Returns the subgroup size builtin.
  47819. *
  47820. * @return {string} The subgroup size.
  47821. */
  47822. getSubgroupSize() {
  47823. this.enableSubGroups();
  47824. return this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  47825. }
  47826. /**
  47827. * Returns the invocation subgroup index builtin.
  47828. *
  47829. * @return {string} The invocation subgroup index.
  47830. */
  47831. getInvocationSubgroupIndex() {
  47832. this.enableSubGroups();
  47833. return this.getBuiltin( 'subgroup_invocation_id', 'invocationSubgroupIndex', 'u32', 'attribute' );
  47834. }
  47835. /**
  47836. * Returns the subgroup index builtin.
  47837. *
  47838. * @return {string} The subgroup index.
  47839. */
  47840. getSubgroupIndex() {
  47841. this.enableSubGroups();
  47842. return this.getBuiltin( 'subgroup_id', 'subgroupIndex', 'u32', 'attribute' );
  47843. }
  47844. /**
  47845. * Overwritten as a NOP since this method is intended for the WebGL 2 backend.
  47846. *
  47847. * @return {null} Null.
  47848. */
  47849. getDrawIndex() {
  47850. return null;
  47851. }
  47852. /**
  47853. * Returns the front facing builtin.
  47854. *
  47855. * @return {string} The front facing builtin.
  47856. */
  47857. getFrontFacing() {
  47858. return this.getBuiltin( 'front_facing', 'isFront', 'bool' );
  47859. }
  47860. /**
  47861. * Returns the frag coord builtin.
  47862. *
  47863. * @return {string} The frag coord builtin.
  47864. */
  47865. getFragCoord() {
  47866. return this.getBuiltin( 'position', 'fragCoord', 'vec4<f32>' ) + '.xy';
  47867. }
  47868. /**
  47869. * Returns the frag depth builtin.
  47870. *
  47871. * @return {string} The frag depth builtin.
  47872. */
  47873. getFragDepth() {
  47874. return 'output.' + this.getBuiltin( 'frag_depth', 'depth', 'f32', 'output' );
  47875. }
  47876. /**
  47877. * Returns the clip distances builtin.
  47878. *
  47879. * @return {string} The clip distances builtin.
  47880. */
  47881. getClipDistance() {
  47882. return 'varyings.hw_clip_distances';
  47883. }
  47884. /**
  47885. * Whether to flip texture data along its vertical axis or not.
  47886. *
  47887. * @return {boolean} Returns always `false` in context of WGSL.
  47888. */
  47889. isFlipY() {
  47890. return false;
  47891. }
  47892. /**
  47893. * Enables the given directive for the given shader stage.
  47894. *
  47895. * @param {string} name - The directive name.
  47896. * @param {string} [shaderStage=this.shaderStage] - The shader stage to enable the directive for.
  47897. */
  47898. enableDirective( name, shaderStage = this.shaderStage ) {
  47899. const stage = this.directives[ shaderStage ] || ( this.directives[ shaderStage ] = new Set() );
  47900. stage.add( name );
  47901. }
  47902. /**
  47903. * Returns the directives of the given shader stage as a WGSL string.
  47904. *
  47905. * @param {string} shaderStage - The shader stage.
  47906. * @return {string} A WGSL snippet that enables the directives of the given stage.
  47907. */
  47908. getDirectives( shaderStage ) {
  47909. const snippets = [];
  47910. const directives = this.directives[ shaderStage ];
  47911. if ( directives !== undefined ) {
  47912. for ( const directive of directives ) {
  47913. snippets.push( `enable ${directive};` );
  47914. }
  47915. }
  47916. return snippets.join( '\n' );
  47917. }
  47918. /**
  47919. * Enables the 'subgroups' directive.
  47920. */
  47921. enableSubGroups() {
  47922. this.enableDirective( 'subgroups' );
  47923. }
  47924. /**
  47925. * Enables the 'subgroups-f16' directive.
  47926. */
  47927. enableSubgroupsF16() {
  47928. this.enableDirective( 'subgroups-f16' );
  47929. }
  47930. /**
  47931. * Enables the 'clip_distances' directive.
  47932. */
  47933. enableClipDistances() {
  47934. this.enableDirective( 'clip_distances' );
  47935. }
  47936. /**
  47937. * Enables the 'f16' directive.
  47938. */
  47939. enableShaderF16() {
  47940. this.enableDirective( 'f16' );
  47941. }
  47942. /**
  47943. * Enables the 'dual_source_blending' directive.
  47944. */
  47945. enableDualSourceBlending() {
  47946. this.enableDirective( 'dual_source_blending' );
  47947. }
  47948. /**
  47949. * Enables hardware clipping.
  47950. *
  47951. * @param {string} planeCount - The clipping plane count.
  47952. */
  47953. enableHardwareClipping( planeCount ) {
  47954. this.enableClipDistances();
  47955. this.getBuiltin( 'clip_distances', 'hw_clip_distances', `array<f32, ${ planeCount } >`, 'vertex' );
  47956. }
  47957. /**
  47958. * Returns the builtins of the given shader stage as a WGSL string.
  47959. *
  47960. * @param {string} shaderStage - The shader stage.
  47961. * @return {string} A WGSL snippet that represents the builtins of the given stage.
  47962. */
  47963. getBuiltins( shaderStage ) {
  47964. const snippets = [];
  47965. const builtins = this.builtins[ shaderStage ];
  47966. if ( builtins !== undefined ) {
  47967. for ( const { name, property, type } of builtins.values() ) {
  47968. snippets.push( `@builtin( ${name} ) ${property} : ${type}` );
  47969. }
  47970. }
  47971. return snippets.join( ',\n\t' );
  47972. }
  47973. /**
  47974. * This method should be used when a new scoped buffer is used in context of
  47975. * compute shaders. It adds the array to the internal data structure which is
  47976. * later used to generate the respective WGSL.
  47977. *
  47978. * @param {string} name - The array name.
  47979. * @param {string} scope - The scope.
  47980. * @param {string} bufferType - The buffer type.
  47981. * @param {string} bufferCount - The buffer count.
  47982. * @return {string} The array name.
  47983. */
  47984. getScopedArray( name, scope, bufferType, bufferCount ) {
  47985. if ( this.scopedArrays.has( name ) === false ) {
  47986. this.scopedArrays.set( name, {
  47987. name,
  47988. scope,
  47989. bufferType,
  47990. bufferCount
  47991. } );
  47992. }
  47993. return name;
  47994. }
  47995. /**
  47996. * Returns the scoped arrays of the given shader stage as a WGSL string.
  47997. *
  47998. * @param {string} shaderStage - The shader stage.
  47999. * @return {string|undefined} The WGSL snippet that defines the scoped arrays.
  48000. * Returns `undefined` when used in the vertex or fragment stage.
  48001. */
  48002. getScopedArrays( shaderStage ) {
  48003. if ( shaderStage !== 'compute' ) {
  48004. return;
  48005. }
  48006. const snippets = [];
  48007. for ( const { name, scope, bufferType, bufferCount } of this.scopedArrays.values() ) {
  48008. const type = this.getType( bufferType );
  48009. snippets.push( `var<${scope}> ${name}: array< ${type}, ${bufferCount} >;` );
  48010. }
  48011. return snippets.join( '\n' );
  48012. }
  48013. /**
  48014. * Returns the shader attributes of the given shader stage as a WGSL string.
  48015. *
  48016. * @param {string} shaderStage - The shader stage.
  48017. * @return {string} The WGSL snippet that defines the shader attributes.
  48018. */
  48019. getAttributes( shaderStage ) {
  48020. const snippets = [];
  48021. if ( shaderStage === 'compute' ) {
  48022. this.getBuiltin( 'global_invocation_id', 'globalId', 'vec3<u32>', 'attribute' );
  48023. this.getBuiltin( 'workgroup_id', 'workgroupId', 'vec3<u32>', 'attribute' );
  48024. this.getBuiltin( 'local_invocation_id', 'localId', 'vec3<u32>', 'attribute' );
  48025. this.getBuiltin( 'num_workgroups', 'numWorkgroups', 'vec3<u32>', 'attribute' );
  48026. if ( this.renderer.hasFeature( 'subgroups' ) ) {
  48027. this.enableDirective( 'subgroups', shaderStage );
  48028. this.getBuiltin( 'subgroup_size', 'subgroupSize', 'u32', 'attribute' );
  48029. }
  48030. }
  48031. if ( shaderStage === 'vertex' || shaderStage === 'compute' ) {
  48032. const builtins = this.getBuiltins( 'attribute' );
  48033. if ( builtins ) snippets.push( builtins );
  48034. const attributes = this.getAttributesArray();
  48035. for ( let index = 0, length = attributes.length; index < length; index ++ ) {
  48036. const attribute = attributes[ index ];
  48037. const name = attribute.name;
  48038. const type = this.getType( attribute.type );
  48039. snippets.push( `@location( ${index} ) ${ name } : ${ type }` );
  48040. }
  48041. }
  48042. return snippets.join( ',\n\t' );
  48043. }
  48044. /**
  48045. * Returns the members of the given struct type node as a WGSL string.
  48046. *
  48047. * @param {StructTypeNode} struct - The struct type node.
  48048. * @return {string} The WGSL snippet that defines the struct members.
  48049. */
  48050. getStructMembers( struct ) {
  48051. const snippets = [];
  48052. for ( const member of struct.members ) {
  48053. const prefix = struct.output ? '@location( ' + member.index + ' ) ' : '';
  48054. let type = this.getType( member.type );
  48055. if ( member.atomic ) {
  48056. type = 'atomic< ' + type + ' >';
  48057. }
  48058. snippets.push( `\t${ prefix + member.name } : ${ type }` );
  48059. }
  48060. if ( struct.output ) {
  48061. snippets.push( `\t${ this.getBuiltins( 'output' ) }` );
  48062. }
  48063. return snippets.join( ',\n' );
  48064. }
  48065. /**
  48066. * Returns the structs of the given shader stage as a WGSL string.
  48067. *
  48068. * @param {string} shaderStage - The shader stage.
  48069. * @return {string} The WGSL snippet that defines the structs.
  48070. */
  48071. getStructs( shaderStage ) {
  48072. let result = '';
  48073. const structs = this.structs[ shaderStage ];
  48074. if ( structs.length > 0 ) {
  48075. const snippets = [];
  48076. for ( const struct of structs ) {
  48077. let snippet = `struct ${ struct.name } {\n`;
  48078. snippet += this.getStructMembers( struct );
  48079. snippet += '\n};';
  48080. snippets.push( snippet );
  48081. }
  48082. result = '\n' + snippets.join( '\n\n' ) + '\n';
  48083. }
  48084. return result;
  48085. }
  48086. /**
  48087. * Returns a WGSL string representing a variable.
  48088. *
  48089. * @param {string} type - The variable's type.
  48090. * @param {string} name - The variable's name.
  48091. * @param {?number} [count=null] - The array length.
  48092. * @return {string} The WGSL snippet that defines a variable.
  48093. */
  48094. getVar( type, name, count = null ) {
  48095. let snippet = `var ${ name } : `;
  48096. if ( count !== null ) {
  48097. snippet += this.generateArrayDeclaration( type, count );
  48098. } else {
  48099. snippet += this.getType( type );
  48100. }
  48101. return snippet;
  48102. }
  48103. /**
  48104. * Returns the variables of the given shader stage as a WGSL string.
  48105. *
  48106. * @param {string} shaderStage - The shader stage.
  48107. * @return {string} The WGSL snippet that defines the variables.
  48108. */
  48109. getVars( shaderStage ) {
  48110. const snippets = [];
  48111. const vars = this.vars[ shaderStage ];
  48112. if ( vars !== undefined ) {
  48113. for ( const variable of vars ) {
  48114. snippets.push( `\t${ this.getVar( variable.type, variable.name, variable.count ) };` );
  48115. }
  48116. }
  48117. return `\n${ snippets.join( '\n' ) }\n`;
  48118. }
  48119. /**
  48120. * Returns the varyings of the given shader stage as a WGSL string.
  48121. *
  48122. * @param {string} shaderStage - The shader stage.
  48123. * @return {string} The WGSL snippet that defines the varyings.
  48124. */
  48125. getVaryings( shaderStage ) {
  48126. const snippets = [];
  48127. if ( shaderStage === 'vertex' ) {
  48128. this.getBuiltin( 'position', 'Vertex', 'vec4<f32>', 'vertex' );
  48129. }
  48130. if ( shaderStage === 'vertex' || shaderStage === 'fragment' ) {
  48131. const varyings = this.varyings;
  48132. const vars = this.vars[ shaderStage ];
  48133. for ( let index = 0; index < varyings.length; index ++ ) {
  48134. const varying = varyings[ index ];
  48135. if ( varying.needsInterpolation ) {
  48136. let attributesSnippet = `@location( ${index} )`;
  48137. if ( varying.interpolationType ) {
  48138. const samplingSnippet = varying.interpolationSampling !== null ? `, ${ varying.interpolationSampling } )` : ' )';
  48139. attributesSnippet += ` @interpolate( ${ varying.interpolationType }${ samplingSnippet }`;
  48140. // Otherwise, optimize interpolation when sensible
  48141. } else if ( /^(int|uint|ivec|uvec)/.test( varying.type ) ) {
  48142. attributesSnippet += ` @interpolate( ${ this.renderer.backend.compatibilityMode ? 'flat, either' : 'flat' } )`;
  48143. }
  48144. snippets.push( `${ attributesSnippet } ${ varying.name } : ${ this.getType( varying.type ) }` );
  48145. } else if ( shaderStage === 'vertex' && vars.includes( varying ) === false ) {
  48146. vars.push( varying );
  48147. }
  48148. }
  48149. }
  48150. const builtins = this.getBuiltins( shaderStage );
  48151. if ( builtins ) snippets.push( builtins );
  48152. const code = snippets.join( ',\n\t' );
  48153. return shaderStage === 'vertex' ? this._getWGSLStruct( 'VaryingsStruct', '\t' + code ) : code;
  48154. }
  48155. isCustomStruct( nodeUniform ) {
  48156. const attribute = nodeUniform.value;
  48157. const bufferNode = nodeUniform.node;
  48158. const isAttributeStructType = ( attribute.isBufferAttribute || attribute.isInstancedBufferAttribute ) && bufferNode.structTypeNode !== null;
  48159. const isStructArray =
  48160. ( bufferNode.value && bufferNode.value.array ) &&
  48161. ( typeof bufferNode.value.itemSize === 'number' && bufferNode.value.array.length > bufferNode.value.itemSize );
  48162. return isAttributeStructType && ! isStructArray;
  48163. }
  48164. /**
  48165. * Returns the uniforms of the given shader stage as a WGSL string.
  48166. *
  48167. * @param {string} shaderStage - The shader stage.
  48168. * @return {string} The WGSL snippet that defines the uniforms.
  48169. */
  48170. getUniforms( shaderStage ) {
  48171. const uniforms = this.uniforms[ shaderStage ];
  48172. const bindingSnippets = [];
  48173. const bufferSnippets = [];
  48174. const structSnippets = [];
  48175. const uniformGroups = {};
  48176. for ( const uniform of uniforms ) {
  48177. const groupName = uniform.groupNode.name;
  48178. const uniformIndexes = this.bindingsIndexes[ groupName ];
  48179. if ( uniform.type === 'texture' || uniform.type === 'cubeTexture' || uniform.type === 'storageTexture' || uniform.type === 'texture3D' ) {
  48180. const texture = uniform.node.value;
  48181. if ( this.isUnfilterable( texture ) === false && uniform.node.isStorageTextureNode !== true ) {
  48182. if ( this.isSampleCompare( texture ) ) {
  48183. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler_comparison;` );
  48184. } else {
  48185. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name }_sampler : sampler;` );
  48186. }
  48187. }
  48188. let textureType;
  48189. let multisampled = '';
  48190. const { primarySamples } = this.renderer.backend.utils.getTextureSampleData( texture );
  48191. if ( primarySamples > 1 ) {
  48192. multisampled = '_multisampled';
  48193. }
  48194. if ( texture.isCubeTexture === true ) {
  48195. textureType = 'texture_cube<f32>';
  48196. } else if ( texture.isDepthTexture === true ) {
  48197. if ( this.renderer.backend.compatibilityMode && texture.compareFunction === null ) {
  48198. textureType = `texture${ multisampled }_2d<f32>`;
  48199. } else {
  48200. textureType = `texture_depth${ multisampled }_2d${ texture.isArrayTexture === true ? '_array' : '' }`;
  48201. }
  48202. } else if ( texture.isArrayTexture === true || texture.isDataArrayTexture === true || texture.isCompressedArrayTexture === true ) {
  48203. textureType = 'texture_2d_array<f32>';
  48204. } else if ( texture.isVideoTexture === true ) {
  48205. textureType = 'texture_external';
  48206. } else if ( texture.isData3DTexture === true ) {
  48207. textureType = 'texture_3d<f32>';
  48208. } else if ( uniform.node.isStorageTextureNode === true ) {
  48209. const format = getFormat( texture );
  48210. const access = this.getStorageAccess( uniform.node, shaderStage );
  48211. textureType = `texture_storage_2d<${ format }, ${ access }>`;
  48212. } else {
  48213. const componentPrefix = this.getComponentTypeFromTexture( texture ).charAt( 0 );
  48214. textureType = `texture${ multisampled }_2d<${ componentPrefix }32>`;
  48215. }
  48216. bindingSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var ${ uniform.name } : ${ textureType };` );
  48217. } else if ( uniform.type === 'buffer' || uniform.type === 'storageBuffer' || uniform.type === 'indirectStorageBuffer' ) {
  48218. const bufferNode = uniform.node;
  48219. const bufferType = this.getType( bufferNode.getNodeType( this ) );
  48220. const bufferCount = bufferNode.bufferCount;
  48221. const bufferCountSnippet = bufferCount > 0 && uniform.type === 'buffer' ? ', ' + bufferCount : '';
  48222. const bufferAccessMode = bufferNode.isStorageBufferNode ? `storage, ${ this.getStorageAccess( bufferNode, shaderStage ) }` : 'uniform';
  48223. if ( this.isCustomStruct( uniform ) ) {
  48224. bufferSnippets.push( `@binding( ${ uniformIndexes.binding ++ } ) @group( ${ uniformIndexes.group } ) var<${ bufferAccessMode }> ${ uniform.name } : ${ bufferType };` );
  48225. } else {
  48226. const bufferTypeSnippet = bufferNode.isAtomic ? `atomic<${ bufferType }>` : `${ bufferType }`;
  48227. const bufferSnippet = `\tvalue : array< ${ bufferTypeSnippet }${ bufferCountSnippet } >`;
  48228. bufferSnippets.push( this._getWGSLStructBinding( uniform.name, bufferSnippet, bufferAccessMode, uniformIndexes.binding ++, uniformIndexes.group ) );
  48229. }
  48230. } else {
  48231. const vectorType = this.getType( this.getVectorType( uniform.type ) );
  48232. const groupName = uniform.groupNode.name;
  48233. const group = uniformGroups[ groupName ] || ( uniformGroups[ groupName ] = {
  48234. index: uniformIndexes.binding ++,
  48235. id: uniformIndexes.group,
  48236. snippets: []
  48237. } );
  48238. group.snippets.push( `\t${ uniform.name } : ${ vectorType }` );
  48239. }
  48240. }
  48241. for ( const name in uniformGroups ) {
  48242. const group = uniformGroups[ name ];
  48243. structSnippets.push( this._getWGSLStructBinding( name, group.snippets.join( ',\n' ), 'uniform', group.index, group.id ) );
  48244. }
  48245. let code = bindingSnippets.join( '\n' );
  48246. code += bufferSnippets.join( '\n' );
  48247. code += structSnippets.join( '\n' );
  48248. return code;
  48249. }
  48250. /**
  48251. * Controls the code build of the shader stages.
  48252. */
  48253. buildCode() {
  48254. const shadersData = this.material !== null ? { fragment: {}, vertex: {} } : { compute: {} };
  48255. this.sortBindingGroups();
  48256. for ( const shaderStage in shadersData ) {
  48257. this.shaderStage = shaderStage;
  48258. const stageData = shadersData[ shaderStage ];
  48259. stageData.uniforms = this.getUniforms( shaderStage );
  48260. stageData.attributes = this.getAttributes( shaderStage );
  48261. stageData.varyings = this.getVaryings( shaderStage );
  48262. stageData.structs = this.getStructs( shaderStage );
  48263. stageData.vars = this.getVars( shaderStage );
  48264. stageData.codes = this.getCodes( shaderStage );
  48265. stageData.directives = this.getDirectives( shaderStage );
  48266. stageData.scopedArrays = this.getScopedArrays( shaderStage );
  48267. //
  48268. let flow = '// code\n\n';
  48269. flow += this.flowCode[ shaderStage ];
  48270. const flowNodes = this.flowNodes[ shaderStage ];
  48271. const mainNode = flowNodes[ flowNodes.length - 1 ];
  48272. const outputNode = mainNode.outputNode;
  48273. const isOutputStruct = ( outputNode !== undefined && outputNode.isOutputStructNode === true );
  48274. for ( const node of flowNodes ) {
  48275. const flowSlotData = this.getFlowData( node/*, shaderStage*/ );
  48276. const slotName = node.name;
  48277. if ( slotName ) {
  48278. if ( flow.length > 0 ) flow += '\n';
  48279. flow += `\t// flow -> ${ slotName }\n`;
  48280. }
  48281. flow += `${ flowSlotData.code }\n\t`;
  48282. if ( node === mainNode && shaderStage !== 'compute' ) {
  48283. flow += '// result\n\n\t';
  48284. if ( shaderStage === 'vertex' ) {
  48285. flow += `varyings.Vertex = ${ flowSlotData.result };`;
  48286. } else if ( shaderStage === 'fragment' ) {
  48287. if ( isOutputStruct ) {
  48288. stageData.returnType = outputNode.getNodeType( this );
  48289. stageData.structs += 'var<private> output : ' + stageData.returnType + ';';
  48290. flow += `return ${ flowSlotData.result };`;
  48291. } else {
  48292. let structSnippet = '\t@location(0) color: vec4<f32>';
  48293. const builtins = this.getBuiltins( 'output' );
  48294. if ( builtins ) structSnippet += ',\n\t' + builtins;
  48295. stageData.returnType = 'OutputStruct';
  48296. stageData.structs += this._getWGSLStruct( 'OutputStruct', structSnippet );
  48297. stageData.structs += '\nvar<private> output : OutputStruct;';
  48298. flow += `output.color = ${ flowSlotData.result };\n\n\treturn output;`;
  48299. }
  48300. }
  48301. }
  48302. }
  48303. stageData.flow = flow;
  48304. }
  48305. this.shaderStage = null;
  48306. if ( this.material !== null ) {
  48307. this.vertexShader = this._getWGSLVertexCode( shadersData.vertex );
  48308. this.fragmentShader = this._getWGSLFragmentCode( shadersData.fragment );
  48309. } else {
  48310. this.computeShader = this._getWGSLComputeCode( shadersData.compute, ( this.object.workgroupSize || [ 64 ] ).join( ', ' ) );
  48311. }
  48312. }
  48313. /**
  48314. * Returns the native shader method name for a given generic name.
  48315. *
  48316. * @param {string} method - The method name to resolve.
  48317. * @param {?string} [output=null] - An optional output.
  48318. * @return {string} The resolved WGSL method name.
  48319. */
  48320. getMethod( method, output = null ) {
  48321. let wgslMethod;
  48322. if ( output !== null ) {
  48323. wgslMethod = this._getWGSLMethod( method + '_' + output );
  48324. }
  48325. if ( wgslMethod === undefined ) {
  48326. wgslMethod = this._getWGSLMethod( method );
  48327. }
  48328. return wgslMethod || method;
  48329. }
  48330. /**
  48331. * Returns the WGSL type of the given node data type.
  48332. *
  48333. * @param {string} type - The node data type.
  48334. * @return {string} The WGSL type.
  48335. */
  48336. getType( type ) {
  48337. return wgslTypeLib[ type ] || type;
  48338. }
  48339. /**
  48340. * Whether the requested feature is available or not.
  48341. *
  48342. * @param {string} name - The requested feature.
  48343. * @return {boolean} Whether the requested feature is supported or not.
  48344. */
  48345. isAvailable( name ) {
  48346. let result = supports[ name ];
  48347. if ( result === undefined ) {
  48348. if ( name === 'float32Filterable' ) {
  48349. result = this.renderer.hasFeature( 'float32-filterable' );
  48350. } else if ( name === 'clipDistance' ) {
  48351. result = this.renderer.hasFeature( 'clip-distances' );
  48352. }
  48353. supports[ name ] = result;
  48354. }
  48355. return result;
  48356. }
  48357. /**
  48358. * Returns the native shader method name for a given generic name.
  48359. *
  48360. * @private
  48361. * @param {string} method - The method name to resolve.
  48362. * @return {string} The resolved WGSL method name.
  48363. */
  48364. _getWGSLMethod( method ) {
  48365. if ( wgslPolyfill[ method ] !== undefined ) {
  48366. this._include( method );
  48367. }
  48368. return wgslMethods[ method ];
  48369. }
  48370. /**
  48371. * Includes the given method name into the current
  48372. * function node.
  48373. *
  48374. * @private
  48375. * @param {string} name - The method name to include.
  48376. * @return {CodeNode} The respective code node.
  48377. */
  48378. _include( name ) {
  48379. const codeNode = wgslPolyfill[ name ];
  48380. codeNode.build( this );
  48381. if ( this.currentFunctionNode !== null ) {
  48382. this.currentFunctionNode.includes.push( codeNode );
  48383. }
  48384. return codeNode;
  48385. }
  48386. /**
  48387. * Returns a WGSL vertex shader based on the given shader data.
  48388. *
  48389. * @private
  48390. * @param {Object} shaderData - The shader data.
  48391. * @return {string} The vertex shader.
  48392. */
  48393. _getWGSLVertexCode( shaderData ) {
  48394. return `${ this.getSignature() }
  48395. // directives
  48396. ${shaderData.directives}
  48397. // structs
  48398. ${shaderData.structs}
  48399. // uniforms
  48400. ${shaderData.uniforms}
  48401. // varyings
  48402. ${shaderData.varyings}
  48403. var<private> varyings : VaryingsStruct;
  48404. // codes
  48405. ${shaderData.codes}
  48406. @vertex
  48407. fn main( ${shaderData.attributes} ) -> VaryingsStruct {
  48408. // vars
  48409. ${shaderData.vars}
  48410. // flow
  48411. ${shaderData.flow}
  48412. return varyings;
  48413. }
  48414. `;
  48415. }
  48416. /**
  48417. * Returns a WGSL fragment shader based on the given shader data.
  48418. *
  48419. * @private
  48420. * @param {Object} shaderData - The shader data.
  48421. * @return {string} The vertex shader.
  48422. */
  48423. _getWGSLFragmentCode( shaderData ) {
  48424. return `${ this.getSignature() }
  48425. // global
  48426. ${ diagnostics }
  48427. // structs
  48428. ${shaderData.structs}
  48429. // uniforms
  48430. ${shaderData.uniforms}
  48431. // codes
  48432. ${shaderData.codes}
  48433. @fragment
  48434. fn main( ${shaderData.varyings} ) -> ${shaderData.returnType} {
  48435. // vars
  48436. ${shaderData.vars}
  48437. // flow
  48438. ${shaderData.flow}
  48439. }
  48440. `;
  48441. }
  48442. /**
  48443. * Returns a WGSL compute shader based on the given shader data.
  48444. *
  48445. * @private
  48446. * @param {Object} shaderData - The shader data.
  48447. * @param {string} workgroupSize - The workgroup size.
  48448. * @return {string} The vertex shader.
  48449. */
  48450. _getWGSLComputeCode( shaderData, workgroupSize ) {
  48451. return `${ this.getSignature() }
  48452. // directives
  48453. ${shaderData.directives}
  48454. // system
  48455. var<private> instanceIndex : u32;
  48456. // locals
  48457. ${shaderData.scopedArrays}
  48458. // structs
  48459. ${shaderData.structs}
  48460. // uniforms
  48461. ${shaderData.uniforms}
  48462. // codes
  48463. ${shaderData.codes}
  48464. @compute @workgroup_size( ${workgroupSize} )
  48465. fn main( ${shaderData.attributes} ) {
  48466. // system
  48467. instanceIndex = globalId.x + globalId.y * numWorkgroups.x * u32(${workgroupSize}) + globalId.z * numWorkgroups.x * numWorkgroups.y * u32(${workgroupSize});
  48468. // vars
  48469. ${shaderData.vars}
  48470. // flow
  48471. ${shaderData.flow}
  48472. }
  48473. `;
  48474. }
  48475. /**
  48476. * Returns a WGSL struct based on the given name and variables.
  48477. *
  48478. * @private
  48479. * @param {string} name - The struct name.
  48480. * @param {string} vars - The struct variables.
  48481. * @return {string} The WGSL snippet representing a struct.
  48482. */
  48483. _getWGSLStruct( name, vars ) {
  48484. return `
  48485. struct ${name} {
  48486. ${vars}
  48487. };`;
  48488. }
  48489. /**
  48490. * Returns a WGSL struct binding.
  48491. *
  48492. * @private
  48493. * @param {string} name - The struct name.
  48494. * @param {string} vars - The struct variables.
  48495. * @param {string} access - The access.
  48496. * @param {number} [binding=0] - The binding index.
  48497. * @param {number} [group=0] - The group index.
  48498. * @return {string} The WGSL snippet representing a struct binding.
  48499. */
  48500. _getWGSLStructBinding( name, vars, access, binding = 0, group = 0 ) {
  48501. const structName = name + 'Struct';
  48502. const structSnippet = this._getWGSLStruct( structName, vars );
  48503. return `${structSnippet}
  48504. @binding( ${ binding } ) @group( ${ group } )
  48505. var<${access}> ${ name } : ${ structName };`;
  48506. }
  48507. }
  48508. /**
  48509. * A WebGPU backend utility module with common helpers.
  48510. *
  48511. * @private
  48512. */
  48513. class WebGPUUtils {
  48514. /**
  48515. * Constructs a new utility object.
  48516. *
  48517. * @param {WebGPUBackend} backend - The WebGPU backend.
  48518. */
  48519. constructor( backend ) {
  48520. /**
  48521. * A reference to the WebGPU backend.
  48522. *
  48523. * @type {WebGPUBackend}
  48524. */
  48525. this.backend = backend;
  48526. }
  48527. /**
  48528. * Returns the depth/stencil GPU format for the given render context.
  48529. *
  48530. * @param {RenderContext} renderContext - The render context.
  48531. * @return {string} The depth/stencil GPU texture format.
  48532. */
  48533. getCurrentDepthStencilFormat( renderContext ) {
  48534. let format;
  48535. if ( renderContext.depthTexture !== null ) {
  48536. format = this.getTextureFormatGPU( renderContext.depthTexture );
  48537. } else if ( renderContext.depth && renderContext.stencil ) {
  48538. format = GPUTextureFormat.Depth24PlusStencil8;
  48539. } else if ( renderContext.depth ) {
  48540. format = GPUTextureFormat.Depth24Plus;
  48541. }
  48542. return format;
  48543. }
  48544. /**
  48545. * Returns the GPU format for the given texture.
  48546. *
  48547. * @param {Texture} texture - The texture.
  48548. * @return {string} The GPU texture format.
  48549. */
  48550. getTextureFormatGPU( texture ) {
  48551. return this.backend.get( texture ).format;
  48552. }
  48553. /**
  48554. * Returns an object that defines the multi-sampling state of the given texture.
  48555. *
  48556. * @param {Texture} texture - The texture.
  48557. * @return {Object} The multi-sampling state.
  48558. */
  48559. getTextureSampleData( texture ) {
  48560. let samples;
  48561. if ( texture.isFramebufferTexture ) {
  48562. samples = 1;
  48563. } else if ( texture.isDepthTexture && ! texture.renderTarget ) {
  48564. const renderer = this.backend.renderer;
  48565. const renderTarget = renderer.getRenderTarget();
  48566. samples = renderTarget ? renderTarget.samples : renderer.samples;
  48567. } else if ( texture.renderTarget ) {
  48568. samples = texture.renderTarget.samples;
  48569. }
  48570. samples = samples || 1;
  48571. const isMSAA = samples > 1 && texture.renderTarget !== null && ( texture.isDepthTexture !== true && texture.isFramebufferTexture !== true );
  48572. const primarySamples = isMSAA ? 1 : samples;
  48573. return { samples, primarySamples, isMSAA };
  48574. }
  48575. /**
  48576. * Returns the default color attachment's GPU format of the current render context.
  48577. *
  48578. * @param {RenderContext} renderContext - The render context.
  48579. * @return {string} The GPU texture format of the default color attachment.
  48580. */
  48581. getCurrentColorFormat( renderContext ) {
  48582. let format;
  48583. if ( renderContext.textures !== null ) {
  48584. format = this.getTextureFormatGPU( renderContext.textures[ 0 ] );
  48585. } else {
  48586. format = this.getPreferredCanvasFormat(); // default context format
  48587. }
  48588. return format;
  48589. }
  48590. /**
  48591. * Returns the output color space of the current render context.
  48592. *
  48593. * @param {RenderContext} renderContext - The render context.
  48594. * @return {string} The output color space.
  48595. */
  48596. getCurrentColorSpace( renderContext ) {
  48597. if ( renderContext.textures !== null ) {
  48598. return renderContext.textures[ 0 ].colorSpace;
  48599. }
  48600. return this.backend.renderer.outputColorSpace;
  48601. }
  48602. /**
  48603. * Returns GPU primitive topology for the given object and material.
  48604. *
  48605. * @param {Object3D} object - The 3D object.
  48606. * @param {Material} material - The material.
  48607. * @return {string} The GPU primitive topology.
  48608. */
  48609. getPrimitiveTopology( object, material ) {
  48610. if ( object.isPoints ) return GPUPrimitiveTopology.PointList;
  48611. else if ( object.isLineSegments || ( object.isMesh && material.wireframe === true ) ) return GPUPrimitiveTopology.LineList;
  48612. else if ( object.isLine ) return GPUPrimitiveTopology.LineStrip;
  48613. else if ( object.isMesh ) return GPUPrimitiveTopology.TriangleList;
  48614. }
  48615. /**
  48616. * Returns a modified sample count from the given sample count value.
  48617. *
  48618. * That is required since WebGPU does not support arbitrary sample counts.
  48619. *
  48620. * @param {number} sampleCount - The input sample count.
  48621. * @return {number} The (potentially updated) output sample count.
  48622. */
  48623. getSampleCount( sampleCount ) {
  48624. let count = 1;
  48625. if ( sampleCount > 1 ) {
  48626. // WebGPU only supports power-of-two sample counts and 2 is not a valid value
  48627. count = Math.pow( 2, Math.floor( Math.log2( sampleCount ) ) );
  48628. if ( count === 2 ) {
  48629. count = 4;
  48630. }
  48631. }
  48632. return count;
  48633. }
  48634. /**
  48635. * Returns the sample count of the given render context.
  48636. *
  48637. * @param {RenderContext} renderContext - The render context.
  48638. * @return {number} The sample count.
  48639. */
  48640. getSampleCountRenderContext( renderContext ) {
  48641. if ( renderContext.textures !== null ) {
  48642. return this.getSampleCount( renderContext.sampleCount );
  48643. }
  48644. return this.getSampleCount( this.backend.renderer.samples );
  48645. }
  48646. /**
  48647. * Returns the preferred canvas format.
  48648. *
  48649. * There is a separate method for this so it's possible to
  48650. * honor edge cases for specific devices.
  48651. *
  48652. * @return {string} The GPU texture format of the canvas.
  48653. */
  48654. getPreferredCanvasFormat() {
  48655. const outputType = this.backend.parameters.outputType;
  48656. if ( outputType === undefined ) {
  48657. return navigator.gpu.getPreferredCanvasFormat();
  48658. } else if ( outputType === UnsignedByteType ) {
  48659. return GPUTextureFormat.BGRA8Unorm;
  48660. } else if ( outputType === HalfFloatType ) {
  48661. return GPUTextureFormat.RGBA16Float;
  48662. } else {
  48663. throw new Error( 'Unsupported outputType' );
  48664. }
  48665. }
  48666. }
  48667. const typedArraysToVertexFormatPrefix = new Map( [
  48668. [ Int8Array, [ 'sint8', 'snorm8' ]],
  48669. [ Uint8Array, [ 'uint8', 'unorm8' ]],
  48670. [ Int16Array, [ 'sint16', 'snorm16' ]],
  48671. [ Uint16Array, [ 'uint16', 'unorm16' ]],
  48672. [ Int32Array, [ 'sint32', 'snorm32' ]],
  48673. [ Uint32Array, [ 'uint32', 'unorm32' ]],
  48674. [ Float32Array, [ 'float32', ]],
  48675. ] );
  48676. const typedAttributeToVertexFormatPrefix = new Map( [
  48677. [ Float16BufferAttribute, [ 'float16', ]],
  48678. ] );
  48679. const typeArraysToVertexFormatPrefixForItemSize1 = new Map( [
  48680. [ Int32Array, 'sint32' ],
  48681. [ Int16Array, 'sint32' ], // patch for INT16
  48682. [ Uint32Array, 'uint32' ],
  48683. [ Uint16Array, 'uint32' ], // patch for UINT16
  48684. [ Float32Array, 'float32' ]
  48685. ] );
  48686. /**
  48687. * A WebGPU backend utility module for managing shader attributes.
  48688. *
  48689. * @private
  48690. */
  48691. class WebGPUAttributeUtils {
  48692. /**
  48693. * Constructs a new utility object.
  48694. *
  48695. * @param {WebGPUBackend} backend - The WebGPU backend.
  48696. */
  48697. constructor( backend ) {
  48698. /**
  48699. * A reference to the WebGPU backend.
  48700. *
  48701. * @type {WebGPUBackend}
  48702. */
  48703. this.backend = backend;
  48704. }
  48705. /**
  48706. * Creates the GPU buffer for the given buffer attribute.
  48707. *
  48708. * @param {BufferAttribute} attribute - The buffer attribute.
  48709. * @param {GPUBufferUsage} usage - A flag that indicates how the buffer may be used after its creation.
  48710. */
  48711. createAttribute( attribute, usage ) {
  48712. const bufferAttribute = this._getBufferAttribute( attribute );
  48713. const backend = this.backend;
  48714. const bufferData = backend.get( bufferAttribute );
  48715. let buffer = bufferData.buffer;
  48716. if ( buffer === undefined ) {
  48717. const device = backend.device;
  48718. let array = bufferAttribute.array;
  48719. // patch for INT16 and UINT16
  48720. if ( attribute.normalized === false ) {
  48721. if ( array.constructor === Int16Array || array.constructor === Int8Array ) {
  48722. array = new Int32Array( array );
  48723. } else if ( array.constructor === Uint16Array || array.constructor === Uint8Array ) {
  48724. array = new Uint32Array( array );
  48725. if ( usage & GPUBufferUsage.INDEX ) {
  48726. for ( let i = 0; i < array.length; i ++ ) {
  48727. if ( array[ i ] === 0xffff ) array[ i ] = 0xffffffff; // use correct primitive restart index
  48728. }
  48729. }
  48730. }
  48731. }
  48732. bufferAttribute.array = array;
  48733. if ( ( bufferAttribute.isStorageBufferAttribute || bufferAttribute.isStorageInstancedBufferAttribute ) && bufferAttribute.itemSize === 3 ) {
  48734. array = new array.constructor( bufferAttribute.count * 4 );
  48735. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  48736. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  48737. }
  48738. // Update BufferAttribute
  48739. bufferAttribute.itemSize = 4;
  48740. bufferAttribute.array = array;
  48741. bufferData._force3to4BytesAlignment = true;
  48742. }
  48743. // ensure 4 byte alignment
  48744. const byteLength = array.byteLength;
  48745. const size = byteLength + ( ( 4 - ( byteLength % 4 ) ) % 4 );
  48746. buffer = device.createBuffer( {
  48747. label: bufferAttribute.name,
  48748. size: size,
  48749. usage: usage,
  48750. mappedAtCreation: true
  48751. } );
  48752. new array.constructor( buffer.getMappedRange() ).set( array );
  48753. buffer.unmap();
  48754. bufferData.buffer = buffer;
  48755. }
  48756. }
  48757. /**
  48758. * Updates the GPU buffer of the given buffer attribute.
  48759. *
  48760. * @param {BufferAttribute} attribute - The buffer attribute.
  48761. */
  48762. updateAttribute( attribute ) {
  48763. const bufferAttribute = this._getBufferAttribute( attribute );
  48764. const backend = this.backend;
  48765. const device = backend.device;
  48766. const bufferData = backend.get( bufferAttribute );
  48767. const buffer = backend.get( bufferAttribute ).buffer;
  48768. let array = bufferAttribute.array;
  48769. // if storage buffer ensure 4 byte alignment
  48770. if ( bufferData._force3to4BytesAlignment === true ) {
  48771. array = new array.constructor( bufferAttribute.count * 4 );
  48772. for ( let i = 0; i < bufferAttribute.count; i ++ ) {
  48773. array.set( bufferAttribute.array.subarray( i * 3, i * 3 + 3 ), i * 4 );
  48774. }
  48775. bufferAttribute.array = array;
  48776. }
  48777. const isTypedArray = this._isTypedArray( array );
  48778. const updateRanges = bufferAttribute.updateRanges;
  48779. if ( updateRanges.length === 0 ) {
  48780. // Not using update ranges
  48781. device.queue.writeBuffer(
  48782. buffer,
  48783. 0,
  48784. array,
  48785. 0
  48786. );
  48787. } else {
  48788. const byteOffsetFactor = isTypedArray ? 1 : array.BYTES_PER_ELEMENT;
  48789. for ( let i = 0, l = updateRanges.length; i < l; i ++ ) {
  48790. const range = updateRanges[ i ];
  48791. let dataOffset, size;
  48792. if ( bufferData._force3to4BytesAlignment === true ) {
  48793. const vertexStart = Math.floor( range.start / 3 );
  48794. const vertexCount = Math.ceil( range.count / 3 );
  48795. dataOffset = vertexStart * 4 * byteOffsetFactor;
  48796. size = vertexCount * 4 * byteOffsetFactor;
  48797. } else {
  48798. dataOffset = range.start * byteOffsetFactor;
  48799. size = range.count * byteOffsetFactor;
  48800. }
  48801. const bufferOffset = dataOffset * ( isTypedArray ? array.BYTES_PER_ELEMENT : 1 ); // bufferOffset is always in bytes
  48802. device.queue.writeBuffer(
  48803. buffer,
  48804. bufferOffset,
  48805. array,
  48806. dataOffset,
  48807. size
  48808. );
  48809. }
  48810. bufferAttribute.clearUpdateRanges();
  48811. }
  48812. }
  48813. /**
  48814. * This method creates the vertex buffer layout data which are
  48815. * require when creating a render pipeline for the given render object.
  48816. *
  48817. * @param {RenderObject} renderObject - The render object.
  48818. * @return {Array<Object>} An array holding objects which describe the vertex buffer layout.
  48819. */
  48820. createShaderVertexBuffers( renderObject ) {
  48821. const attributes = renderObject.getAttributes();
  48822. const vertexBuffers = new Map();
  48823. for ( let slot = 0; slot < attributes.length; slot ++ ) {
  48824. const geometryAttribute = attributes[ slot ];
  48825. const bytesPerElement = geometryAttribute.array.BYTES_PER_ELEMENT;
  48826. const bufferAttribute = this._getBufferAttribute( geometryAttribute );
  48827. let vertexBufferLayout = vertexBuffers.get( bufferAttribute );
  48828. if ( vertexBufferLayout === undefined ) {
  48829. let arrayStride, stepMode;
  48830. if ( geometryAttribute.isInterleavedBufferAttribute === true ) {
  48831. arrayStride = geometryAttribute.data.stride * bytesPerElement;
  48832. stepMode = geometryAttribute.data.isInstancedInterleavedBuffer ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  48833. } else {
  48834. arrayStride = geometryAttribute.itemSize * bytesPerElement;
  48835. stepMode = geometryAttribute.isInstancedBufferAttribute ? GPUInputStepMode.Instance : GPUInputStepMode.Vertex;
  48836. }
  48837. // patch for INT16 and UINT16
  48838. if ( geometryAttribute.normalized === false && ( geometryAttribute.array.constructor === Int16Array || geometryAttribute.array.constructor === Uint16Array ) ) {
  48839. arrayStride = 4;
  48840. }
  48841. vertexBufferLayout = {
  48842. arrayStride,
  48843. attributes: [],
  48844. stepMode
  48845. };
  48846. vertexBuffers.set( bufferAttribute, vertexBufferLayout );
  48847. }
  48848. const format = this._getVertexFormat( geometryAttribute );
  48849. const offset = ( geometryAttribute.isInterleavedBufferAttribute === true ) ? geometryAttribute.offset * bytesPerElement : 0;
  48850. vertexBufferLayout.attributes.push( {
  48851. shaderLocation: slot,
  48852. offset,
  48853. format
  48854. } );
  48855. }
  48856. return Array.from( vertexBuffers.values() );
  48857. }
  48858. /**
  48859. * Destroys the GPU buffer of the given buffer attribute.
  48860. *
  48861. * @param {BufferAttribute} attribute - The buffer attribute.
  48862. */
  48863. destroyAttribute( attribute ) {
  48864. const backend = this.backend;
  48865. const data = backend.get( this._getBufferAttribute( attribute ) );
  48866. data.buffer.destroy();
  48867. backend.delete( attribute );
  48868. }
  48869. /**
  48870. * This method performs a readback operation by moving buffer data from
  48871. * a storage buffer attribute from the GPU to the CPU.
  48872. *
  48873. * @async
  48874. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  48875. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  48876. */
  48877. async getArrayBufferAsync( attribute ) {
  48878. const backend = this.backend;
  48879. const device = backend.device;
  48880. const data = backend.get( this._getBufferAttribute( attribute ) );
  48881. const bufferGPU = data.buffer;
  48882. const size = bufferGPU.size;
  48883. const readBufferGPU = device.createBuffer( {
  48884. label: `${ attribute.name }_readback`,
  48885. size,
  48886. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  48887. } );
  48888. const cmdEncoder = device.createCommandEncoder( {
  48889. label: `readback_encoder_${ attribute.name }`
  48890. } );
  48891. cmdEncoder.copyBufferToBuffer(
  48892. bufferGPU,
  48893. 0,
  48894. readBufferGPU,
  48895. 0,
  48896. size
  48897. );
  48898. const gpuCommands = cmdEncoder.finish();
  48899. device.queue.submit( [ gpuCommands ] );
  48900. await readBufferGPU.mapAsync( GPUMapMode.READ );
  48901. const arrayBuffer = readBufferGPU.getMappedRange();
  48902. const dstBuffer = new attribute.array.constructor( arrayBuffer.slice( 0 ) );
  48903. readBufferGPU.unmap();
  48904. return dstBuffer.buffer;
  48905. }
  48906. /**
  48907. * Returns the vertex format of the given buffer attribute.
  48908. *
  48909. * @private
  48910. * @param {BufferAttribute} geometryAttribute - The buffer attribute.
  48911. * @return {string|undefined} The vertex format (e.g. 'float32x3').
  48912. */
  48913. _getVertexFormat( geometryAttribute ) {
  48914. const { itemSize, normalized } = geometryAttribute;
  48915. const ArrayType = geometryAttribute.array.constructor;
  48916. const AttributeType = geometryAttribute.constructor;
  48917. let format;
  48918. if ( itemSize === 1 ) {
  48919. format = typeArraysToVertexFormatPrefixForItemSize1.get( ArrayType );
  48920. } else {
  48921. const prefixOptions = typedAttributeToVertexFormatPrefix.get( AttributeType ) || typedArraysToVertexFormatPrefix.get( ArrayType );
  48922. const prefix = prefixOptions[ normalized ? 1 : 0 ];
  48923. if ( prefix ) {
  48924. const bytesPerUnit = ArrayType.BYTES_PER_ELEMENT * itemSize;
  48925. const paddedBytesPerUnit = Math.floor( ( bytesPerUnit + 3 ) / 4 ) * 4;
  48926. const paddedItemSize = paddedBytesPerUnit / ArrayType.BYTES_PER_ELEMENT;
  48927. if ( paddedItemSize % 1 ) {
  48928. throw new Error( 'THREE.WebGPUAttributeUtils: Bad vertex format item size.' );
  48929. }
  48930. format = `${prefix}x${paddedItemSize}`;
  48931. }
  48932. }
  48933. if ( ! format ) {
  48934. console.error( 'THREE.WebGPUAttributeUtils: Vertex format not supported yet.' );
  48935. }
  48936. return format;
  48937. }
  48938. /**
  48939. * Returns `true` if the given array is a typed array.
  48940. *
  48941. * @private
  48942. * @param {any} array - The array.
  48943. * @return {boolean} Whether the given array is a typed array or not.
  48944. */
  48945. _isTypedArray( array ) {
  48946. return ArrayBuffer.isView( array ) && ! ( array instanceof DataView );
  48947. }
  48948. /**
  48949. * Utility method for handling interleaved buffer attributes correctly.
  48950. * To process them, their `InterleavedBuffer` is returned.
  48951. *
  48952. * @private
  48953. * @param {BufferAttribute} attribute - The attribute.
  48954. * @return {BufferAttribute|InterleavedBuffer}
  48955. */
  48956. _getBufferAttribute( attribute ) {
  48957. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  48958. return attribute;
  48959. }
  48960. }
  48961. /**
  48962. * A WebGPU backend utility module for managing bindings.
  48963. *
  48964. * When reading the documentation it's helpful to keep in mind that
  48965. * all class definitions starting with 'GPU*' are modules from the
  48966. * WebGPU API. So for example `BindGroup` is a class from the engine
  48967. * whereas `GPUBindGroup` is a class from WebGPU.
  48968. *
  48969. * @private
  48970. */
  48971. class WebGPUBindingUtils {
  48972. /**
  48973. * Constructs a new utility object.
  48974. *
  48975. * @param {WebGPUBackend} backend - The WebGPU backend.
  48976. */
  48977. constructor( backend ) {
  48978. /**
  48979. * A reference to the WebGPU backend.
  48980. *
  48981. * @type {WebGPUBackend}
  48982. */
  48983. this.backend = backend;
  48984. /**
  48985. * A cache for managing bind group layouts.
  48986. *
  48987. * @type {WeakMap<Array<Binding>,GPUBindGroupLayout>}
  48988. */
  48989. this.bindGroupLayoutCache = new WeakMap();
  48990. }
  48991. /**
  48992. * Creates a GPU bind group layout for the given bind group.
  48993. *
  48994. * @param {BindGroup} bindGroup - The bind group.
  48995. * @return {GPUBindGroupLayout} The GPU bind group layout.
  48996. */
  48997. createBindingsLayout( bindGroup ) {
  48998. const backend = this.backend;
  48999. const device = backend.device;
  49000. const entries = [];
  49001. let index = 0;
  49002. for ( const binding of bindGroup.bindings ) {
  49003. const bindingGPU = {
  49004. binding: index ++,
  49005. visibility: binding.visibility
  49006. };
  49007. if ( binding.isUniformBuffer || binding.isStorageBuffer ) {
  49008. const buffer = {}; // GPUBufferBindingLayout
  49009. if ( binding.isStorageBuffer ) {
  49010. if ( binding.visibility & 4 ) {
  49011. // compute
  49012. if ( binding.access === NodeAccess.READ_WRITE || binding.access === NodeAccess.WRITE_ONLY ) {
  49013. buffer.type = GPUBufferBindingType.Storage;
  49014. } else {
  49015. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  49016. }
  49017. } else {
  49018. buffer.type = GPUBufferBindingType.ReadOnlyStorage;
  49019. }
  49020. }
  49021. bindingGPU.buffer = buffer;
  49022. } else if ( binding.isSampler ) {
  49023. const sampler = {}; // GPUSamplerBindingLayout
  49024. if ( binding.texture.isDepthTexture ) {
  49025. if ( binding.texture.compareFunction !== null ) {
  49026. sampler.type = GPUSamplerBindingType.Comparison;
  49027. } else if ( backend.compatibilityMode ) {
  49028. sampler.type = GPUSamplerBindingType.NonFiltering;
  49029. }
  49030. }
  49031. bindingGPU.sampler = sampler;
  49032. } else if ( binding.isSampledTexture && binding.texture.isVideoTexture ) {
  49033. bindingGPU.externalTexture = {}; // GPUExternalTextureBindingLayout
  49034. } else if ( binding.isSampledTexture && binding.store ) {
  49035. const storageTexture = {}; // GPUStorageTextureBindingLayout
  49036. storageTexture.format = this.backend.get( binding.texture ).texture.format;
  49037. const access = binding.access;
  49038. if ( access === NodeAccess.READ_WRITE ) {
  49039. storageTexture.access = GPUStorageTextureAccess.ReadWrite;
  49040. } else if ( access === NodeAccess.WRITE_ONLY ) {
  49041. storageTexture.access = GPUStorageTextureAccess.WriteOnly;
  49042. } else {
  49043. storageTexture.access = GPUStorageTextureAccess.ReadOnly;
  49044. }
  49045. bindingGPU.storageTexture = storageTexture;
  49046. } else if ( binding.isSampledTexture ) {
  49047. const texture = {}; // GPUTextureBindingLayout
  49048. const { primarySamples } = backend.utils.getTextureSampleData( binding.texture );
  49049. if ( primarySamples > 1 ) {
  49050. texture.multisampled = true;
  49051. if ( ! binding.texture.isDepthTexture ) {
  49052. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  49053. }
  49054. }
  49055. if ( binding.texture.isDepthTexture ) {
  49056. if ( backend.compatibilityMode && binding.texture.compareFunction === null ) {
  49057. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  49058. } else {
  49059. texture.sampleType = GPUTextureSampleType.Depth;
  49060. }
  49061. } else if ( binding.texture.isDataTexture || binding.texture.isDataArrayTexture || binding.texture.isData3DTexture ) {
  49062. const type = binding.texture.type;
  49063. if ( type === IntType ) {
  49064. texture.sampleType = GPUTextureSampleType.SInt;
  49065. } else if ( type === UnsignedIntType ) {
  49066. texture.sampleType = GPUTextureSampleType.UInt;
  49067. } else if ( type === FloatType ) {
  49068. if ( this.backend.hasFeature( 'float32-filterable' ) ) {
  49069. texture.sampleType = GPUTextureSampleType.Float;
  49070. } else {
  49071. texture.sampleType = GPUTextureSampleType.UnfilterableFloat;
  49072. }
  49073. }
  49074. }
  49075. if ( binding.isSampledCubeTexture ) {
  49076. texture.viewDimension = GPUTextureViewDimension.Cube;
  49077. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  49078. texture.viewDimension = GPUTextureViewDimension.TwoDArray;
  49079. } else if ( binding.isSampledTexture3D ) {
  49080. texture.viewDimension = GPUTextureViewDimension.ThreeD;
  49081. }
  49082. bindingGPU.texture = texture;
  49083. } else {
  49084. console.error( `WebGPUBindingUtils: Unsupported binding "${ binding }".` );
  49085. }
  49086. entries.push( bindingGPU );
  49087. }
  49088. return device.createBindGroupLayout( { entries } );
  49089. }
  49090. /**
  49091. * Creates bindings from the given bind group definition.
  49092. *
  49093. * @param {BindGroup} bindGroup - The bind group.
  49094. * @param {Array<BindGroup>} bindings - Array of bind groups.
  49095. * @param {number} cacheIndex - The cache index.
  49096. * @param {number} version - The version.
  49097. */
  49098. createBindings( bindGroup, bindings, cacheIndex, version = 0 ) {
  49099. const { backend, bindGroupLayoutCache } = this;
  49100. const bindingsData = backend.get( bindGroup );
  49101. // setup (static) binding layout and (dynamic) binding group
  49102. let bindLayoutGPU = bindGroupLayoutCache.get( bindGroup.bindingsReference );
  49103. if ( bindLayoutGPU === undefined ) {
  49104. bindLayoutGPU = this.createBindingsLayout( bindGroup );
  49105. bindGroupLayoutCache.set( bindGroup.bindingsReference, bindLayoutGPU );
  49106. }
  49107. let bindGroupGPU;
  49108. if ( cacheIndex > 0 ) {
  49109. if ( bindingsData.groups === undefined ) {
  49110. bindingsData.groups = [];
  49111. bindingsData.versions = [];
  49112. }
  49113. if ( bindingsData.versions[ cacheIndex ] === version ) {
  49114. bindGroupGPU = bindingsData.groups[ cacheIndex ];
  49115. }
  49116. }
  49117. if ( bindGroupGPU === undefined ) {
  49118. bindGroupGPU = this.createBindGroup( bindGroup, bindLayoutGPU );
  49119. if ( cacheIndex > 0 ) {
  49120. bindingsData.groups[ cacheIndex ] = bindGroupGPU;
  49121. bindingsData.versions[ cacheIndex ] = version;
  49122. }
  49123. }
  49124. bindingsData.group = bindGroupGPU;
  49125. bindingsData.layout = bindLayoutGPU;
  49126. }
  49127. /**
  49128. * Updates a buffer binding.
  49129. *
  49130. * @param {Buffer} binding - The buffer binding to update.
  49131. */
  49132. updateBinding( binding ) {
  49133. const backend = this.backend;
  49134. const device = backend.device;
  49135. const buffer = binding.buffer;
  49136. const bufferGPU = backend.get( binding ).buffer;
  49137. device.queue.writeBuffer( bufferGPU, 0, buffer, 0 );
  49138. }
  49139. /**
  49140. * Creates a GPU bind group for the camera index.
  49141. *
  49142. * @param {Uint32Array} data - The index data.
  49143. * @param {GPUBindGroupLayout} layout - The GPU bind group layout.
  49144. * @return {GPUBindGroup} The GPU bind group.
  49145. */
  49146. createBindGroupIndex( data, layout ) {
  49147. const backend = this.backend;
  49148. const device = backend.device;
  49149. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  49150. const index = data[ 0 ];
  49151. const buffer = device.createBuffer( {
  49152. label: 'bindingCameraIndex_' + index,
  49153. size: 16, // uint(4) * 4
  49154. usage: usage
  49155. } );
  49156. device.queue.writeBuffer( buffer, 0, data, 0 );
  49157. const entries = [ { binding: 0, resource: { buffer } } ];
  49158. return device.createBindGroup( {
  49159. label: 'bindGroupCameraIndex_' + index,
  49160. layout,
  49161. entries
  49162. } );
  49163. }
  49164. /**
  49165. * Creates a GPU bind group for the given bind group and GPU layout.
  49166. *
  49167. * @param {BindGroup} bindGroup - The bind group.
  49168. * @param {GPUBindGroupLayout} layoutGPU - The GPU bind group layout.
  49169. * @return {GPUBindGroup} The GPU bind group.
  49170. */
  49171. createBindGroup( bindGroup, layoutGPU ) {
  49172. const backend = this.backend;
  49173. const device = backend.device;
  49174. let bindingPoint = 0;
  49175. const entriesGPU = [];
  49176. for ( const binding of bindGroup.bindings ) {
  49177. if ( binding.isUniformBuffer ) {
  49178. const bindingData = backend.get( binding );
  49179. if ( bindingData.buffer === undefined ) {
  49180. const byteLength = binding.byteLength;
  49181. const usage = GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST;
  49182. const bufferGPU = device.createBuffer( {
  49183. label: 'bindingBuffer_' + binding.name,
  49184. size: byteLength,
  49185. usage: usage
  49186. } );
  49187. bindingData.buffer = bufferGPU;
  49188. }
  49189. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  49190. } else if ( binding.isStorageBuffer ) {
  49191. const bindingData = backend.get( binding );
  49192. if ( bindingData.buffer === undefined ) {
  49193. const attribute = binding.attribute;
  49194. //const usage = GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | /*GPUBufferUsage.COPY_SRC |*/ GPUBufferUsage.COPY_DST;
  49195. //backend.attributeUtils.createAttribute( attribute, usage ); // @TODO: Move it to universal renderer
  49196. bindingData.buffer = backend.get( attribute ).buffer;
  49197. }
  49198. entriesGPU.push( { binding: bindingPoint, resource: { buffer: bindingData.buffer } } );
  49199. } else if ( binding.isSampler ) {
  49200. const textureGPU = backend.get( binding.texture );
  49201. entriesGPU.push( { binding: bindingPoint, resource: textureGPU.sampler } );
  49202. } else if ( binding.isSampledTexture ) {
  49203. const textureData = backend.get( binding.texture );
  49204. let resourceGPU;
  49205. if ( textureData.externalTexture !== undefined ) {
  49206. resourceGPU = device.importExternalTexture( { source: textureData.externalTexture } );
  49207. } else {
  49208. const mipLevelCount = binding.store ? 1 : textureData.texture.mipLevelCount;
  49209. const propertyName = `view-${ textureData.texture.width }-${ textureData.texture.height }-${ mipLevelCount }`;
  49210. resourceGPU = textureData[ propertyName ];
  49211. if ( resourceGPU === undefined ) {
  49212. const aspectGPU = GPUTextureAspect.All;
  49213. let dimensionViewGPU;
  49214. if ( binding.isSampledCubeTexture ) {
  49215. dimensionViewGPU = GPUTextureViewDimension.Cube;
  49216. } else if ( binding.isSampledTexture3D ) {
  49217. dimensionViewGPU = GPUTextureViewDimension.ThreeD;
  49218. } else if ( binding.texture.isArrayTexture || binding.texture.isDataArrayTexture || binding.texture.isCompressedArrayTexture ) {
  49219. dimensionViewGPU = GPUTextureViewDimension.TwoDArray;
  49220. } else {
  49221. dimensionViewGPU = GPUTextureViewDimension.TwoD;
  49222. }
  49223. resourceGPU = textureData[ propertyName ] = textureData.texture.createView( { aspect: aspectGPU, dimension: dimensionViewGPU, mipLevelCount } );
  49224. }
  49225. }
  49226. entriesGPU.push( { binding: bindingPoint, resource: resourceGPU } );
  49227. }
  49228. bindingPoint ++;
  49229. }
  49230. return device.createBindGroup( {
  49231. label: 'bindGroup_' + bindGroup.name,
  49232. layout: layoutGPU,
  49233. entries: entriesGPU
  49234. } );
  49235. }
  49236. }
  49237. /**
  49238. * A WebGPU backend utility module for managing pipelines.
  49239. *
  49240. * @private
  49241. */
  49242. class WebGPUPipelineUtils {
  49243. /**
  49244. * Constructs a new utility object.
  49245. *
  49246. * @param {WebGPUBackend} backend - The WebGPU backend.
  49247. */
  49248. constructor( backend ) {
  49249. /**
  49250. * A reference to the WebGPU backend.
  49251. *
  49252. * @type {WebGPUBackend}
  49253. */
  49254. this.backend = backend;
  49255. /**
  49256. * A Weak Map that tracks the active pipeline for render or compute passes.
  49257. *
  49258. * @private
  49259. * @type {WeakMap<(GPURenderPassEncoder|GPUComputePassEncoder),(GPURenderPipeline|GPUComputePipeline)>}
  49260. */
  49261. this._activePipelines = new WeakMap();
  49262. }
  49263. /**
  49264. * Sets the given pipeline for the given pass. The method makes sure to only set the
  49265. * pipeline when necessary.
  49266. *
  49267. * @param {(GPURenderPassEncoder|GPUComputePassEncoder)} pass - The pass encoder.
  49268. * @param {(GPURenderPipeline|GPUComputePipeline)} pipeline - The pipeline.
  49269. */
  49270. setPipeline( pass, pipeline ) {
  49271. const currentPipeline = this._activePipelines.get( pass );
  49272. if ( currentPipeline !== pipeline ) {
  49273. pass.setPipeline( pipeline );
  49274. this._activePipelines.set( pass, pipeline );
  49275. }
  49276. }
  49277. /**
  49278. * Returns the sample count derived from the given render context.
  49279. *
  49280. * @private
  49281. * @param {RenderContext} renderContext - The render context.
  49282. * @return {number} The sample count.
  49283. */
  49284. _getSampleCount( renderContext ) {
  49285. return this.backend.utils.getSampleCountRenderContext( renderContext );
  49286. }
  49287. /**
  49288. * Creates a render pipeline for the given render object.
  49289. *
  49290. * @param {RenderObject} renderObject - The render object.
  49291. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  49292. */
  49293. createRenderPipeline( renderObject, promises ) {
  49294. const { object, material, geometry, pipeline } = renderObject;
  49295. const { vertexProgram, fragmentProgram } = pipeline;
  49296. const backend = this.backend;
  49297. const device = backend.device;
  49298. const utils = backend.utils;
  49299. const pipelineData = backend.get( pipeline );
  49300. // bind group layouts
  49301. const bindGroupLayouts = [];
  49302. for ( const bindGroup of renderObject.getBindings() ) {
  49303. const bindingsData = backend.get( bindGroup );
  49304. bindGroupLayouts.push( bindingsData.layout );
  49305. }
  49306. // vertex buffers
  49307. const vertexBuffers = backend.attributeUtils.createShaderVertexBuffers( renderObject );
  49308. // blending
  49309. let blending;
  49310. if ( material.blending !== NoBlending && ( material.blending !== NormalBlending || material.transparent !== false ) ) {
  49311. blending = this._getBlending( material );
  49312. }
  49313. // stencil
  49314. let stencilFront = {};
  49315. if ( material.stencilWrite === true ) {
  49316. stencilFront = {
  49317. compare: this._getStencilCompare( material ),
  49318. failOp: this._getStencilOperation( material.stencilFail ),
  49319. depthFailOp: this._getStencilOperation( material.stencilZFail ),
  49320. passOp: this._getStencilOperation( material.stencilZPass )
  49321. };
  49322. }
  49323. const colorWriteMask = this._getColorWriteMask( material );
  49324. const targets = [];
  49325. if ( renderObject.context.textures !== null ) {
  49326. const textures = renderObject.context.textures;
  49327. for ( let i = 0; i < textures.length; i ++ ) {
  49328. const colorFormat = utils.getTextureFormatGPU( textures[ i ] );
  49329. targets.push( {
  49330. format: colorFormat,
  49331. blend: blending,
  49332. writeMask: colorWriteMask
  49333. } );
  49334. }
  49335. } else {
  49336. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  49337. targets.push( {
  49338. format: colorFormat,
  49339. blend: blending,
  49340. writeMask: colorWriteMask
  49341. } );
  49342. }
  49343. const vertexModule = backend.get( vertexProgram ).module;
  49344. const fragmentModule = backend.get( fragmentProgram ).module;
  49345. const primitiveState = this._getPrimitiveState( object, geometry, material );
  49346. const depthCompare = this._getDepthCompare( material );
  49347. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  49348. const sampleCount = this._getSampleCount( renderObject.context );
  49349. const pipelineDescriptor = {
  49350. label: `renderPipeline_${ material.name || material.type }_${ material.id }`,
  49351. vertex: Object.assign( {}, vertexModule, { buffers: vertexBuffers } ),
  49352. fragment: Object.assign( {}, fragmentModule, { targets } ),
  49353. primitive: primitiveState,
  49354. multisample: {
  49355. count: sampleCount,
  49356. alphaToCoverageEnabled: material.alphaToCoverage && sampleCount > 1
  49357. },
  49358. layout: device.createPipelineLayout( {
  49359. bindGroupLayouts
  49360. } )
  49361. };
  49362. const depthStencil = {};
  49363. const renderDepth = renderObject.context.depth;
  49364. const renderStencil = renderObject.context.stencil;
  49365. if ( renderDepth === true || renderStencil === true ) {
  49366. if ( renderDepth === true ) {
  49367. depthStencil.format = depthStencilFormat;
  49368. depthStencil.depthWriteEnabled = material.depthWrite;
  49369. depthStencil.depthCompare = depthCompare;
  49370. }
  49371. if ( renderStencil === true ) {
  49372. depthStencil.stencilFront = stencilFront;
  49373. depthStencil.stencilBack = {}; // three.js does not provide an API to configure the back function (gl.stencilFuncSeparate() was never used)
  49374. depthStencil.stencilReadMask = material.stencilFuncMask;
  49375. depthStencil.stencilWriteMask = material.stencilWriteMask;
  49376. }
  49377. if ( material.polygonOffset === true ) {
  49378. depthStencil.depthBias = material.polygonOffsetUnits;
  49379. depthStencil.depthBiasSlopeScale = material.polygonOffsetFactor;
  49380. depthStencil.depthBiasClamp = 0; // three.js does not provide an API to configure this value
  49381. }
  49382. pipelineDescriptor.depthStencil = depthStencil;
  49383. }
  49384. if ( promises === null ) {
  49385. pipelineData.pipeline = device.createRenderPipeline( pipelineDescriptor );
  49386. } else {
  49387. const p = new Promise( ( resolve /*, reject*/ ) => {
  49388. device.createRenderPipelineAsync( pipelineDescriptor ).then( pipeline => {
  49389. pipelineData.pipeline = pipeline;
  49390. resolve();
  49391. } );
  49392. } );
  49393. promises.push( p );
  49394. }
  49395. }
  49396. /**
  49397. * Creates GPU render bundle encoder for the given render context.
  49398. *
  49399. * @param {RenderContext} renderContext - The render context.
  49400. * @param {?string} [label='renderBundleEncoder'] - The label.
  49401. * @return {GPURenderBundleEncoder} The GPU render bundle encoder.
  49402. */
  49403. createBundleEncoder( renderContext, label = 'renderBundleEncoder' ) {
  49404. const backend = this.backend;
  49405. const { utils, device } = backend;
  49406. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderContext );
  49407. const colorFormat = utils.getCurrentColorFormat( renderContext );
  49408. const sampleCount = this._getSampleCount( renderContext );
  49409. const descriptor = {
  49410. label: label,
  49411. colorFormats: [ colorFormat ],
  49412. depthStencilFormat,
  49413. sampleCount
  49414. };
  49415. return device.createRenderBundleEncoder( descriptor );
  49416. }
  49417. /**
  49418. * Creates a compute pipeline for the given compute node.
  49419. *
  49420. * @param {ComputePipeline} pipeline - The compute pipeline.
  49421. * @param {Array<BindGroup>} bindings - The bindings.
  49422. */
  49423. createComputePipeline( pipeline, bindings ) {
  49424. const backend = this.backend;
  49425. const device = backend.device;
  49426. const computeProgram = backend.get( pipeline.computeProgram ).module;
  49427. const pipelineGPU = backend.get( pipeline );
  49428. // bind group layouts
  49429. const bindGroupLayouts = [];
  49430. for ( const bindingsGroup of bindings ) {
  49431. const bindingsData = backend.get( bindingsGroup );
  49432. bindGroupLayouts.push( bindingsData.layout );
  49433. }
  49434. pipelineGPU.pipeline = device.createComputePipeline( {
  49435. compute: computeProgram,
  49436. layout: device.createPipelineLayout( {
  49437. bindGroupLayouts
  49438. } )
  49439. } );
  49440. }
  49441. /**
  49442. * Returns the blending state as a descriptor object required
  49443. * for the pipeline creation.
  49444. *
  49445. * @private
  49446. * @param {Material} material - The material.
  49447. * @return {Object} The blending state.
  49448. */
  49449. _getBlending( material ) {
  49450. let color, alpha;
  49451. const blending = material.blending;
  49452. const blendSrc = material.blendSrc;
  49453. const blendDst = material.blendDst;
  49454. const blendEquation = material.blendEquation;
  49455. if ( blending === CustomBlending ) {
  49456. const blendSrcAlpha = material.blendSrcAlpha !== null ? material.blendSrcAlpha : blendSrc;
  49457. const blendDstAlpha = material.blendDstAlpha !== null ? material.blendDstAlpha : blendDst;
  49458. const blendEquationAlpha = material.blendEquationAlpha !== null ? material.blendEquationAlpha : blendEquation;
  49459. color = {
  49460. srcFactor: this._getBlendFactor( blendSrc ),
  49461. dstFactor: this._getBlendFactor( blendDst ),
  49462. operation: this._getBlendOperation( blendEquation )
  49463. };
  49464. alpha = {
  49465. srcFactor: this._getBlendFactor( blendSrcAlpha ),
  49466. dstFactor: this._getBlendFactor( blendDstAlpha ),
  49467. operation: this._getBlendOperation( blendEquationAlpha )
  49468. };
  49469. } else {
  49470. const premultipliedAlpha = material.premultipliedAlpha;
  49471. const setBlend = ( srcRGB, dstRGB, srcAlpha, dstAlpha ) => {
  49472. color = {
  49473. srcFactor: srcRGB,
  49474. dstFactor: dstRGB,
  49475. operation: GPUBlendOperation.Add
  49476. };
  49477. alpha = {
  49478. srcFactor: srcAlpha,
  49479. dstFactor: dstAlpha,
  49480. operation: GPUBlendOperation.Add
  49481. };
  49482. };
  49483. if ( premultipliedAlpha ) {
  49484. switch ( blending ) {
  49485. case NormalBlending:
  49486. setBlend( GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  49487. break;
  49488. case AdditiveBlending:
  49489. setBlend( GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One, GPUBlendFactor.One );
  49490. break;
  49491. case SubtractiveBlending:
  49492. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  49493. break;
  49494. case MultiplyBlending:
  49495. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.SrcAlpha );
  49496. break;
  49497. }
  49498. } else {
  49499. switch ( blending ) {
  49500. case NormalBlending:
  49501. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.OneMinusSrcAlpha, GPUBlendFactor.One, GPUBlendFactor.OneMinusSrcAlpha );
  49502. break;
  49503. case AdditiveBlending:
  49504. setBlend( GPUBlendFactor.SrcAlpha, GPUBlendFactor.One, GPUBlendFactor.SrcAlpha, GPUBlendFactor.One );
  49505. break;
  49506. case SubtractiveBlending:
  49507. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.OneMinusSrc, GPUBlendFactor.Zero, GPUBlendFactor.One );
  49508. break;
  49509. case MultiplyBlending:
  49510. setBlend( GPUBlendFactor.Zero, GPUBlendFactor.Src, GPUBlendFactor.Zero, GPUBlendFactor.Src );
  49511. break;
  49512. }
  49513. }
  49514. }
  49515. if ( color !== undefined && alpha !== undefined ) {
  49516. return { color, alpha };
  49517. } else {
  49518. console.error( 'THREE.WebGPURenderer: Invalid blending: ', blending );
  49519. }
  49520. }
  49521. /**
  49522. * Returns the GPU blend factor which is required for the pipeline creation.
  49523. *
  49524. * @private
  49525. * @param {number} blend - The blend factor as a three.js constant.
  49526. * @return {string} The GPU blend factor.
  49527. */
  49528. _getBlendFactor( blend ) {
  49529. let blendFactor;
  49530. switch ( blend ) {
  49531. case ZeroFactor:
  49532. blendFactor = GPUBlendFactor.Zero;
  49533. break;
  49534. case OneFactor:
  49535. blendFactor = GPUBlendFactor.One;
  49536. break;
  49537. case SrcColorFactor:
  49538. blendFactor = GPUBlendFactor.Src;
  49539. break;
  49540. case OneMinusSrcColorFactor:
  49541. blendFactor = GPUBlendFactor.OneMinusSrc;
  49542. break;
  49543. case SrcAlphaFactor:
  49544. blendFactor = GPUBlendFactor.SrcAlpha;
  49545. break;
  49546. case OneMinusSrcAlphaFactor:
  49547. blendFactor = GPUBlendFactor.OneMinusSrcAlpha;
  49548. break;
  49549. case DstColorFactor:
  49550. blendFactor = GPUBlendFactor.Dst;
  49551. break;
  49552. case OneMinusDstColorFactor:
  49553. blendFactor = GPUBlendFactor.OneMinusDst;
  49554. break;
  49555. case DstAlphaFactor:
  49556. blendFactor = GPUBlendFactor.DstAlpha;
  49557. break;
  49558. case OneMinusDstAlphaFactor:
  49559. blendFactor = GPUBlendFactor.OneMinusDstAlpha;
  49560. break;
  49561. case SrcAlphaSaturateFactor:
  49562. blendFactor = GPUBlendFactor.SrcAlphaSaturated;
  49563. break;
  49564. case BlendColorFactor:
  49565. blendFactor = GPUBlendFactor.Constant;
  49566. break;
  49567. case OneMinusBlendColorFactor:
  49568. blendFactor = GPUBlendFactor.OneMinusConstant;
  49569. break;
  49570. default:
  49571. console.error( 'THREE.WebGPURenderer: Blend factor not supported.', blend );
  49572. }
  49573. return blendFactor;
  49574. }
  49575. /**
  49576. * Returns the GPU stencil compare function which is required for the pipeline creation.
  49577. *
  49578. * @private
  49579. * @param {Material} material - The material.
  49580. * @return {string} The GPU stencil compare function.
  49581. */
  49582. _getStencilCompare( material ) {
  49583. let stencilCompare;
  49584. const stencilFunc = material.stencilFunc;
  49585. switch ( stencilFunc ) {
  49586. case NeverStencilFunc:
  49587. stencilCompare = GPUCompareFunction.Never;
  49588. break;
  49589. case AlwaysStencilFunc:
  49590. stencilCompare = GPUCompareFunction.Always;
  49591. break;
  49592. case LessStencilFunc:
  49593. stencilCompare = GPUCompareFunction.Less;
  49594. break;
  49595. case LessEqualStencilFunc:
  49596. stencilCompare = GPUCompareFunction.LessEqual;
  49597. break;
  49598. case EqualStencilFunc:
  49599. stencilCompare = GPUCompareFunction.Equal;
  49600. break;
  49601. case GreaterEqualStencilFunc:
  49602. stencilCompare = GPUCompareFunction.GreaterEqual;
  49603. break;
  49604. case GreaterStencilFunc:
  49605. stencilCompare = GPUCompareFunction.Greater;
  49606. break;
  49607. case NotEqualStencilFunc:
  49608. stencilCompare = GPUCompareFunction.NotEqual;
  49609. break;
  49610. default:
  49611. console.error( 'THREE.WebGPURenderer: Invalid stencil function.', stencilFunc );
  49612. }
  49613. return stencilCompare;
  49614. }
  49615. /**
  49616. * Returns the GPU stencil operation which is required for the pipeline creation.
  49617. *
  49618. * @private
  49619. * @param {number} op - A three.js constant defining the stencil operation.
  49620. * @return {string} The GPU stencil operation.
  49621. */
  49622. _getStencilOperation( op ) {
  49623. let stencilOperation;
  49624. switch ( op ) {
  49625. case KeepStencilOp:
  49626. stencilOperation = GPUStencilOperation.Keep;
  49627. break;
  49628. case ZeroStencilOp:
  49629. stencilOperation = GPUStencilOperation.Zero;
  49630. break;
  49631. case ReplaceStencilOp:
  49632. stencilOperation = GPUStencilOperation.Replace;
  49633. break;
  49634. case InvertStencilOp:
  49635. stencilOperation = GPUStencilOperation.Invert;
  49636. break;
  49637. case IncrementStencilOp:
  49638. stencilOperation = GPUStencilOperation.IncrementClamp;
  49639. break;
  49640. case DecrementStencilOp:
  49641. stencilOperation = GPUStencilOperation.DecrementClamp;
  49642. break;
  49643. case IncrementWrapStencilOp:
  49644. stencilOperation = GPUStencilOperation.IncrementWrap;
  49645. break;
  49646. case DecrementWrapStencilOp:
  49647. stencilOperation = GPUStencilOperation.DecrementWrap;
  49648. break;
  49649. default:
  49650. console.error( 'THREE.WebGPURenderer: Invalid stencil operation.', stencilOperation );
  49651. }
  49652. return stencilOperation;
  49653. }
  49654. /**
  49655. * Returns the GPU blend operation which is required for the pipeline creation.
  49656. *
  49657. * @private
  49658. * @param {number} blendEquation - A three.js constant defining the blend equation.
  49659. * @return {string} The GPU blend operation.
  49660. */
  49661. _getBlendOperation( blendEquation ) {
  49662. let blendOperation;
  49663. switch ( blendEquation ) {
  49664. case AddEquation:
  49665. blendOperation = GPUBlendOperation.Add;
  49666. break;
  49667. case SubtractEquation:
  49668. blendOperation = GPUBlendOperation.Subtract;
  49669. break;
  49670. case ReverseSubtractEquation:
  49671. blendOperation = GPUBlendOperation.ReverseSubtract;
  49672. break;
  49673. case MinEquation:
  49674. blendOperation = GPUBlendOperation.Min;
  49675. break;
  49676. case MaxEquation:
  49677. blendOperation = GPUBlendOperation.Max;
  49678. break;
  49679. default:
  49680. console.error( 'THREE.WebGPUPipelineUtils: Blend equation not supported.', blendEquation );
  49681. }
  49682. return blendOperation;
  49683. }
  49684. /**
  49685. * Returns the primitive state as a descriptor object required
  49686. * for the pipeline creation.
  49687. *
  49688. * @private
  49689. * @param {Object3D} object - The 3D object.
  49690. * @param {BufferGeometry} geometry - The geometry.
  49691. * @param {Material} material - The material.
  49692. * @return {Object} The primitive state.
  49693. */
  49694. _getPrimitiveState( object, geometry, material ) {
  49695. const descriptor = {};
  49696. const utils = this.backend.utils;
  49697. descriptor.topology = utils.getPrimitiveTopology( object, material );
  49698. if ( geometry.index !== null && object.isLine === true && object.isLineSegments !== true ) {
  49699. descriptor.stripIndexFormat = ( geometry.index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  49700. }
  49701. switch ( material.side ) {
  49702. case FrontSide:
  49703. descriptor.frontFace = GPUFrontFace.CCW;
  49704. descriptor.cullMode = GPUCullMode.Back;
  49705. break;
  49706. case BackSide:
  49707. descriptor.frontFace = GPUFrontFace.CCW;
  49708. descriptor.cullMode = GPUCullMode.Front;
  49709. break;
  49710. case DoubleSide:
  49711. descriptor.frontFace = GPUFrontFace.CCW;
  49712. descriptor.cullMode = GPUCullMode.None;
  49713. break;
  49714. default:
  49715. console.error( 'THREE.WebGPUPipelineUtils: Unknown material.side value.', material.side );
  49716. break;
  49717. }
  49718. return descriptor;
  49719. }
  49720. /**
  49721. * Returns the GPU color write mask which is required for the pipeline creation.
  49722. *
  49723. * @private
  49724. * @param {Material} material - The material.
  49725. * @return {string} The GPU color write mask.
  49726. */
  49727. _getColorWriteMask( material ) {
  49728. return ( material.colorWrite === true ) ? GPUColorWriteFlags.All : GPUColorWriteFlags.None;
  49729. }
  49730. /**
  49731. * Returns the GPU depth compare function which is required for the pipeline creation.
  49732. *
  49733. * @private
  49734. * @param {Material} material - The material.
  49735. * @return {string} The GPU depth compare function.
  49736. */
  49737. _getDepthCompare( material ) {
  49738. let depthCompare;
  49739. if ( material.depthTest === false ) {
  49740. depthCompare = GPUCompareFunction.Always;
  49741. } else {
  49742. const depthFunc = material.depthFunc;
  49743. switch ( depthFunc ) {
  49744. case NeverDepth:
  49745. depthCompare = GPUCompareFunction.Never;
  49746. break;
  49747. case AlwaysDepth:
  49748. depthCompare = GPUCompareFunction.Always;
  49749. break;
  49750. case LessDepth:
  49751. depthCompare = GPUCompareFunction.Less;
  49752. break;
  49753. case LessEqualDepth:
  49754. depthCompare = GPUCompareFunction.LessEqual;
  49755. break;
  49756. case EqualDepth:
  49757. depthCompare = GPUCompareFunction.Equal;
  49758. break;
  49759. case GreaterEqualDepth:
  49760. depthCompare = GPUCompareFunction.GreaterEqual;
  49761. break;
  49762. case GreaterDepth:
  49763. depthCompare = GPUCompareFunction.Greater;
  49764. break;
  49765. case NotEqualDepth:
  49766. depthCompare = GPUCompareFunction.NotEqual;
  49767. break;
  49768. default:
  49769. console.error( 'THREE.WebGPUPipelineUtils: Invalid depth function.', depthFunc );
  49770. }
  49771. }
  49772. return depthCompare;
  49773. }
  49774. }
  49775. /**
  49776. * Manages a pool of WebGPU timestamp queries for performance measurement.
  49777. * Extends the base TimestampQueryPool to provide WebGPU-specific implementation.
  49778. *
  49779. * @augments TimestampQueryPool
  49780. */
  49781. class WebGPUTimestampQueryPool extends TimestampQueryPool {
  49782. /**
  49783. * Creates a new WebGPU timestamp query pool.
  49784. *
  49785. * @param {GPUDevice} device - The WebGPU device to create queries on.
  49786. * @param {string} type - The type identifier for this query pool.
  49787. * @param {number} [maxQueries=2048] - Maximum number of queries this pool can hold.
  49788. */
  49789. constructor( device, type, maxQueries = 2048 ) {
  49790. super( maxQueries );
  49791. this.device = device;
  49792. this.type = type;
  49793. this.querySet = this.device.createQuerySet( {
  49794. type: 'timestamp',
  49795. count: this.maxQueries,
  49796. label: `queryset_global_timestamp_${type}`
  49797. } );
  49798. const bufferSize = this.maxQueries * 8;
  49799. this.resolveBuffer = this.device.createBuffer( {
  49800. label: `buffer_timestamp_resolve_${type}`,
  49801. size: bufferSize,
  49802. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  49803. } );
  49804. this.resultBuffer = this.device.createBuffer( {
  49805. label: `buffer_timestamp_result_${type}`,
  49806. size: bufferSize,
  49807. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  49808. } );
  49809. }
  49810. /**
  49811. * Allocates a pair of queries for a given render context.
  49812. *
  49813. * @param {Object} renderContext - The render context to allocate queries for.
  49814. * @returns {?number} The base offset for the allocated queries, or null if allocation failed.
  49815. */
  49816. allocateQueriesForContext( renderContext ) {
  49817. if ( ! this.trackTimestamp || this.isDisposed ) return null;
  49818. if ( this.currentQueryIndex + 2 > this.maxQueries ) {
  49819. 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() } ).` );
  49820. return null;
  49821. }
  49822. const baseOffset = this.currentQueryIndex;
  49823. this.currentQueryIndex += 2;
  49824. this.queryOffsets.set( renderContext.id, baseOffset );
  49825. return baseOffset;
  49826. }
  49827. /**
  49828. * Asynchronously resolves all pending queries and returns the total duration.
  49829. * If there's already a pending resolve operation, returns that promise instead.
  49830. *
  49831. * @async
  49832. * @returns {Promise<number>} The total duration in milliseconds, or the last valid value if resolution fails.
  49833. */
  49834. async resolveQueriesAsync() {
  49835. if ( ! this.trackTimestamp || this.currentQueryIndex === 0 || this.isDisposed ) {
  49836. return this.lastValue;
  49837. }
  49838. if ( this.pendingResolve ) {
  49839. return this.pendingResolve;
  49840. }
  49841. this.pendingResolve = this._resolveQueries();
  49842. try {
  49843. const result = await this.pendingResolve;
  49844. return result;
  49845. } finally {
  49846. this.pendingResolve = null;
  49847. }
  49848. }
  49849. /**
  49850. * Internal method to resolve queries and calculate total duration.
  49851. *
  49852. * @async
  49853. * @private
  49854. * @returns {Promise<number>} The total duration in milliseconds.
  49855. */
  49856. async _resolveQueries() {
  49857. if ( this.isDisposed ) {
  49858. return this.lastValue;
  49859. }
  49860. try {
  49861. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  49862. return this.lastValue;
  49863. }
  49864. const currentOffsets = new Map( this.queryOffsets );
  49865. const queryCount = this.currentQueryIndex;
  49866. const bytesUsed = queryCount * 8;
  49867. // Reset state before GPU work
  49868. this.currentQueryIndex = 0;
  49869. this.queryOffsets.clear();
  49870. const commandEncoder = this.device.createCommandEncoder();
  49871. commandEncoder.resolveQuerySet(
  49872. this.querySet,
  49873. 0,
  49874. queryCount,
  49875. this.resolveBuffer,
  49876. 0
  49877. );
  49878. commandEncoder.copyBufferToBuffer(
  49879. this.resolveBuffer,
  49880. 0,
  49881. this.resultBuffer,
  49882. 0,
  49883. bytesUsed
  49884. );
  49885. const commandBuffer = commandEncoder.finish();
  49886. this.device.queue.submit( [ commandBuffer ] );
  49887. if ( this.resultBuffer.mapState !== 'unmapped' ) {
  49888. return this.lastValue;
  49889. }
  49890. // Create and track the mapping operation
  49891. await this.resultBuffer.mapAsync( GPUMapMode.READ, 0, bytesUsed );
  49892. if ( this.isDisposed ) {
  49893. if ( this.resultBuffer.mapState === 'mapped' ) {
  49894. this.resultBuffer.unmap();
  49895. }
  49896. return this.lastValue;
  49897. }
  49898. const times = new BigUint64Array( this.resultBuffer.getMappedRange( 0, bytesUsed ) );
  49899. let totalDuration = 0;
  49900. for ( const [ , baseOffset ] of currentOffsets ) {
  49901. const startTime = times[ baseOffset ];
  49902. const endTime = times[ baseOffset + 1 ];
  49903. const duration = Number( endTime - startTime ) / 1e6;
  49904. totalDuration += duration;
  49905. }
  49906. this.resultBuffer.unmap();
  49907. this.lastValue = totalDuration;
  49908. return totalDuration;
  49909. } catch ( error ) {
  49910. console.error( 'Error resolving queries:', error );
  49911. if ( this.resultBuffer.mapState === 'mapped' ) {
  49912. this.resultBuffer.unmap();
  49913. }
  49914. return this.lastValue;
  49915. }
  49916. }
  49917. /**
  49918. * Dispose of the query pool.
  49919. *
  49920. * @async
  49921. * @returns {Promise} A Promise that resolves when the dispose has been executed.
  49922. */
  49923. async dispose() {
  49924. if ( this.isDisposed ) {
  49925. return;
  49926. }
  49927. this.isDisposed = true;
  49928. // Wait for pending resolve operation
  49929. if ( this.pendingResolve ) {
  49930. try {
  49931. await this.pendingResolve;
  49932. } catch ( error ) {
  49933. console.error( 'Error waiting for pending resolve:', error );
  49934. }
  49935. }
  49936. // Ensure buffer is unmapped before destroying
  49937. if ( this.resultBuffer && this.resultBuffer.mapState === 'mapped' ) {
  49938. try {
  49939. this.resultBuffer.unmap();
  49940. } catch ( error ) {
  49941. console.error( 'Error unmapping buffer:', error );
  49942. }
  49943. }
  49944. // Destroy resources
  49945. if ( this.querySet ) {
  49946. this.querySet.destroy();
  49947. this.querySet = null;
  49948. }
  49949. if ( this.resolveBuffer ) {
  49950. this.resolveBuffer.destroy();
  49951. this.resolveBuffer = null;
  49952. }
  49953. if ( this.resultBuffer ) {
  49954. this.resultBuffer.destroy();
  49955. this.resultBuffer = null;
  49956. }
  49957. this.queryOffsets.clear();
  49958. this.pendingResolve = null;
  49959. }
  49960. }
  49961. /*// debugger tools
  49962. import 'https://greggman.github.io/webgpu-avoid-redundant-state-setting/webgpu-check-redundant-state-setting.js';
  49963. //*/
  49964. /**
  49965. * A backend implementation targeting WebGPU.
  49966. *
  49967. * @private
  49968. * @augments Backend
  49969. */
  49970. class WebGPUBackend extends Backend {
  49971. /**
  49972. * WebGPUBackend options.
  49973. *
  49974. * @typedef {Object} WebGPUBackend~Options
  49975. * @property {boolean} [logarithmicDepthBuffer=false] - Whether logarithmic depth buffer is enabled or not.
  49976. * @property {boolean} [alpha=true] - Whether the default framebuffer (which represents the final contents of the canvas) should be transparent or opaque.
  49977. * @property {boolean} [compatibilityMode=false] - Whether the backend should be in compatibility mode or not.
  49978. * @property {boolean} [depth=true] - Whether the default framebuffer should have a depth buffer or not.
  49979. * @property {boolean} [stencil=false] - Whether the default framebuffer should have a stencil buffer or not.
  49980. * @property {boolean} [antialias=false] - Whether MSAA as the default anti-aliasing should be enabled or not.
  49981. * @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.
  49982. * @property {boolean} [forceWebGL=false] - If set to `true`, the renderer uses a WebGL 2 backend no matter if WebGPU is supported or not.
  49983. * @property {boolean} [trackTimestamp=false] - Whether to track timestamps with a Timestamp Query API or not.
  49984. * @property {string} [powerPreference=undefined] - The power preference.
  49985. * @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.
  49986. * @property {GPUDevice} [device=undefined] - If there is an existing GPU device on app level, it can be passed to the renderer as a parameter.
  49987. * @property {number} [outputType=undefined] - Texture type for output to canvas. By default, device's preferred format is used; other formats may incur overhead.
  49988. */
  49989. /**
  49990. * Constructs a new WebGPU backend.
  49991. *
  49992. * @param {WebGPUBackend~Options} [parameters] - The configuration parameter.
  49993. */
  49994. constructor( parameters = {} ) {
  49995. super( parameters );
  49996. /**
  49997. * This flag can be used for type testing.
  49998. *
  49999. * @type {boolean}
  50000. * @readonly
  50001. * @default true
  50002. */
  50003. this.isWebGPUBackend = true;
  50004. // some parameters require default values other than "undefined"
  50005. this.parameters.alpha = ( parameters.alpha === undefined ) ? true : parameters.alpha;
  50006. this.parameters.compatibilityMode = ( parameters.compatibilityMode === undefined ) ? false : parameters.compatibilityMode;
  50007. this.parameters.requiredLimits = ( parameters.requiredLimits === undefined ) ? {} : parameters.requiredLimits;
  50008. /**
  50009. * Indicates whether the backend is in compatibility mode or not.
  50010. * @type {boolean}
  50011. * @default false
  50012. */
  50013. this.compatibilityMode = this.parameters.compatibilityMode;
  50014. /**
  50015. * A reference to the device.
  50016. *
  50017. * @type {?GPUDevice}
  50018. * @default null
  50019. */
  50020. this.device = null;
  50021. /**
  50022. * A reference to the context.
  50023. *
  50024. * @type {?GPUCanvasContext}
  50025. * @default null
  50026. */
  50027. this.context = null;
  50028. /**
  50029. * A reference to the color attachment of the default framebuffer.
  50030. *
  50031. * @type {?GPUTexture}
  50032. * @default null
  50033. */
  50034. this.colorBuffer = null;
  50035. /**
  50036. * A reference to the default render pass descriptor.
  50037. *
  50038. * @type {?Object}
  50039. * @default null
  50040. */
  50041. this.defaultRenderPassdescriptor = null;
  50042. /**
  50043. * A reference to a backend module holding common utility functions.
  50044. *
  50045. * @type {WebGPUUtils}
  50046. */
  50047. this.utils = new WebGPUUtils( this );
  50048. /**
  50049. * A reference to a backend module holding shader attribute-related
  50050. * utility functions.
  50051. *
  50052. * @type {WebGPUAttributeUtils}
  50053. */
  50054. this.attributeUtils = new WebGPUAttributeUtils( this );
  50055. /**
  50056. * A reference to a backend module holding shader binding-related
  50057. * utility functions.
  50058. *
  50059. * @type {WebGPUBindingUtils}
  50060. */
  50061. this.bindingUtils = new WebGPUBindingUtils( this );
  50062. /**
  50063. * A reference to a backend module holding shader pipeline-related
  50064. * utility functions.
  50065. *
  50066. * @type {WebGPUPipelineUtils}
  50067. */
  50068. this.pipelineUtils = new WebGPUPipelineUtils( this );
  50069. /**
  50070. * A reference to a backend module holding shader texture-related
  50071. * utility functions.
  50072. *
  50073. * @type {WebGPUTextureUtils}
  50074. */
  50075. this.textureUtils = new WebGPUTextureUtils( this );
  50076. /**
  50077. * A map that manages the resolve buffers for occlusion queries.
  50078. *
  50079. * @type {Map<number,GPUBuffer>}
  50080. */
  50081. this.occludedResolveCache = new Map();
  50082. }
  50083. /**
  50084. * Initializes the backend so it is ready for usage.
  50085. *
  50086. * @async
  50087. * @param {Renderer} renderer - The renderer.
  50088. * @return {Promise} A Promise that resolves when the backend has been initialized.
  50089. */
  50090. async init( renderer ) {
  50091. await super.init( renderer );
  50092. //
  50093. const parameters = this.parameters;
  50094. // create the device if it is not passed with parameters
  50095. let device;
  50096. if ( parameters.device === undefined ) {
  50097. const adapterOptions = {
  50098. powerPreference: parameters.powerPreference,
  50099. featureLevel: parameters.compatibilityMode ? 'compatibility' : undefined
  50100. };
  50101. const adapter = ( typeof navigator !== 'undefined' ) ? await navigator.gpu.requestAdapter( adapterOptions ) : null;
  50102. if ( adapter === null ) {
  50103. throw new Error( 'WebGPUBackend: Unable to create WebGPU adapter.' );
  50104. }
  50105. // feature support
  50106. const features = Object.values( GPUFeatureName );
  50107. const supportedFeatures = [];
  50108. for ( const name of features ) {
  50109. if ( adapter.features.has( name ) ) {
  50110. supportedFeatures.push( name );
  50111. }
  50112. }
  50113. const deviceDescriptor = {
  50114. requiredFeatures: supportedFeatures,
  50115. requiredLimits: parameters.requiredLimits
  50116. };
  50117. device = await adapter.requestDevice( deviceDescriptor );
  50118. } else {
  50119. device = parameters.device;
  50120. }
  50121. device.lost.then( ( info ) => {
  50122. const deviceLossInfo = {
  50123. api: 'WebGPU',
  50124. message: info.message || 'Unknown reason',
  50125. reason: info.reason || null,
  50126. originalEvent: info
  50127. };
  50128. renderer.onDeviceLost( deviceLossInfo );
  50129. } );
  50130. const context = ( parameters.context !== undefined ) ? parameters.context : renderer.domElement.getContext( 'webgpu' );
  50131. this.device = device;
  50132. this.context = context;
  50133. const alphaMode = parameters.alpha ? 'premultiplied' : 'opaque';
  50134. this.trackTimestamp = this.trackTimestamp && this.hasFeature( GPUFeatureName.TimestampQuery );
  50135. this.context.configure( {
  50136. device: this.device,
  50137. format: this.utils.getPreferredCanvasFormat(),
  50138. usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC,
  50139. alphaMode: alphaMode
  50140. } );
  50141. this.updateSize();
  50142. }
  50143. /**
  50144. * The coordinate system of the backend.
  50145. *
  50146. * @type {number}
  50147. * @readonly
  50148. */
  50149. get coordinateSystem() {
  50150. return WebGPUCoordinateSystem;
  50151. }
  50152. /**
  50153. * This method performs a readback operation by moving buffer data from
  50154. * a storage buffer attribute from the GPU to the CPU.
  50155. *
  50156. * @async
  50157. * @param {StorageBufferAttribute} attribute - The storage buffer attribute.
  50158. * @return {Promise<ArrayBuffer>} A promise that resolves with the buffer data when the data are ready.
  50159. */
  50160. async getArrayBufferAsync( attribute ) {
  50161. return await this.attributeUtils.getArrayBufferAsync( attribute );
  50162. }
  50163. /**
  50164. * Returns the backend's rendering context.
  50165. *
  50166. * @return {GPUCanvasContext} The rendering context.
  50167. */
  50168. getContext() {
  50169. return this.context;
  50170. }
  50171. /**
  50172. * Returns the default render pass descriptor.
  50173. *
  50174. * In WebGPU, the default framebuffer must be configured
  50175. * like custom framebuffers so the backend needs a render
  50176. * pass descriptor even when rendering directly to screen.
  50177. *
  50178. * @private
  50179. * @return {Object} The render pass descriptor.
  50180. */
  50181. _getDefaultRenderPassDescriptor() {
  50182. let descriptor = this.defaultRenderPassdescriptor;
  50183. if ( descriptor === null ) {
  50184. const renderer = this.renderer;
  50185. descriptor = {
  50186. colorAttachments: [ {
  50187. view: null
  50188. } ],
  50189. };
  50190. if ( this.renderer.depth === true || this.renderer.stencil === true ) {
  50191. descriptor.depthStencilAttachment = {
  50192. view: this.textureUtils.getDepthBuffer( renderer.depth, renderer.stencil ).createView()
  50193. };
  50194. }
  50195. const colorAttachment = descriptor.colorAttachments[ 0 ];
  50196. if ( this.renderer.samples > 0 ) {
  50197. colorAttachment.view = this.colorBuffer.createView();
  50198. } else {
  50199. colorAttachment.resolveTarget = undefined;
  50200. }
  50201. this.defaultRenderPassdescriptor = descriptor;
  50202. }
  50203. const colorAttachment = descriptor.colorAttachments[ 0 ];
  50204. if ( this.renderer.samples > 0 ) {
  50205. colorAttachment.resolveTarget = this.context.getCurrentTexture().createView();
  50206. } else {
  50207. colorAttachment.view = this.context.getCurrentTexture().createView();
  50208. }
  50209. return descriptor;
  50210. }
  50211. /**
  50212. * Internal to determine if the current render target is a render target array with depth 2D array texture.
  50213. *
  50214. * @param {RenderContext} renderContext - The render context.
  50215. * @return {boolean} Whether the render target is a render target array with depth 2D array texture.
  50216. *
  50217. * @private
  50218. */
  50219. _isRenderCameraDepthArray( renderContext ) {
  50220. return renderContext.depthTexture && renderContext.depthTexture.image.depth > 1 && renderContext.camera.isArrayCamera;
  50221. }
  50222. /**
  50223. * Returns the render pass descriptor for the given render context.
  50224. *
  50225. * @private
  50226. * @param {RenderContext} renderContext - The render context.
  50227. * @param {Object} colorAttachmentsConfig - Configuration object for the color attachments.
  50228. * @return {Object} The render pass descriptor.
  50229. */
  50230. _getRenderPassDescriptor( renderContext, colorAttachmentsConfig = {} ) {
  50231. const renderTarget = renderContext.renderTarget;
  50232. const renderTargetData = this.get( renderTarget );
  50233. let descriptors = renderTargetData.descriptors;
  50234. if ( descriptors === undefined ||
  50235. renderTargetData.width !== renderTarget.width ||
  50236. renderTargetData.height !== renderTarget.height ||
  50237. renderTargetData.dimensions !== renderTarget.dimensions ||
  50238. renderTargetData.activeMipmapLevel !== renderContext.activeMipmapLevel ||
  50239. renderTargetData.activeCubeFace !== renderContext.activeCubeFace ||
  50240. renderTargetData.samples !== renderTarget.samples
  50241. ) {
  50242. descriptors = {};
  50243. renderTargetData.descriptors = descriptors;
  50244. // dispose
  50245. const onDispose = () => {
  50246. renderTarget.removeEventListener( 'dispose', onDispose );
  50247. this.delete( renderTarget );
  50248. };
  50249. if ( renderTarget.hasEventListener( 'dispose', onDispose ) === false ) {
  50250. renderTarget.addEventListener( 'dispose', onDispose );
  50251. }
  50252. }
  50253. const cacheKey = renderContext.getCacheKey();
  50254. let descriptorBase = descriptors[ cacheKey ];
  50255. if ( descriptorBase === undefined ) {
  50256. const textures = renderContext.textures;
  50257. const textureViews = [];
  50258. let sliceIndex;
  50259. const isRenderCameraDepthArray = this._isRenderCameraDepthArray( renderContext );
  50260. for ( let i = 0; i < textures.length; i ++ ) {
  50261. const textureData = this.get( textures[ i ] );
  50262. const viewDescriptor = {
  50263. label: `colorAttachment_${ i }`,
  50264. baseMipLevel: renderContext.activeMipmapLevel,
  50265. mipLevelCount: 1,
  50266. baseArrayLayer: renderContext.activeCubeFace,
  50267. arrayLayerCount: 1,
  50268. dimension: GPUTextureViewDimension.TwoD
  50269. };
  50270. if ( renderTarget.isRenderTarget3D ) {
  50271. sliceIndex = renderContext.activeCubeFace;
  50272. viewDescriptor.baseArrayLayer = 0;
  50273. viewDescriptor.dimension = GPUTextureViewDimension.ThreeD;
  50274. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  50275. } else if ( renderTarget.isRenderTarget && textures[ i ].image.depth > 1 ) {
  50276. if ( isRenderCameraDepthArray === true ) {
  50277. const cameras = renderContext.camera.cameras;
  50278. for ( let layer = 0; layer < cameras.length; layer ++ ) {
  50279. const layerViewDescriptor = {
  50280. ...viewDescriptor,
  50281. baseArrayLayer: layer,
  50282. arrayLayerCount: 1,
  50283. dimension: GPUTextureViewDimension.TwoD
  50284. };
  50285. const textureView = textureData.texture.createView( layerViewDescriptor );
  50286. textureViews.push( {
  50287. view: textureView,
  50288. resolveTarget: undefined,
  50289. depthSlice: undefined
  50290. } );
  50291. }
  50292. } else {
  50293. viewDescriptor.dimension = GPUTextureViewDimension.TwoDArray;
  50294. viewDescriptor.depthOrArrayLayers = textures[ i ].image.depth;
  50295. }
  50296. }
  50297. if ( isRenderCameraDepthArray !== true ) {
  50298. const textureView = textureData.texture.createView( viewDescriptor );
  50299. let view, resolveTarget;
  50300. if ( textureData.msaaTexture !== undefined ) {
  50301. view = textureData.msaaTexture.createView();
  50302. resolveTarget = textureView;
  50303. } else {
  50304. view = textureView;
  50305. resolveTarget = undefined;
  50306. }
  50307. textureViews.push( {
  50308. view,
  50309. resolveTarget,
  50310. depthSlice: sliceIndex
  50311. } );
  50312. }
  50313. }
  50314. descriptorBase = { textureViews };
  50315. if ( renderContext.depth ) {
  50316. const depthTextureData = this.get( renderContext.depthTexture );
  50317. const options = {};
  50318. if ( renderContext.depthTexture.isArrayTexture ) {
  50319. options.dimension = GPUTextureViewDimension.TwoD;
  50320. options.arrayLayerCount = 1;
  50321. options.baseArrayLayer = renderContext.activeCubeFace;
  50322. }
  50323. descriptorBase.depthStencilView = depthTextureData.texture.createView( options );
  50324. }
  50325. descriptors[ cacheKey ] = descriptorBase;
  50326. renderTargetData.width = renderTarget.width;
  50327. renderTargetData.height = renderTarget.height;
  50328. renderTargetData.samples = renderTarget.samples;
  50329. renderTargetData.activeMipmapLevel = renderContext.activeMipmapLevel;
  50330. renderTargetData.activeCubeFace = renderContext.activeCubeFace;
  50331. renderTargetData.dimensions = renderTarget.dimensions;
  50332. }
  50333. const descriptor = {
  50334. colorAttachments: []
  50335. };
  50336. // Apply dynamic properties to cached views
  50337. for ( let i = 0; i < descriptorBase.textureViews.length; i ++ ) {
  50338. const viewInfo = descriptorBase.textureViews[ i ];
  50339. let clearValue = { r: 0, g: 0, b: 0, a: 1 };
  50340. if ( i === 0 && colorAttachmentsConfig.clearValue ) {
  50341. clearValue = colorAttachmentsConfig.clearValue;
  50342. }
  50343. descriptor.colorAttachments.push( {
  50344. view: viewInfo.view,
  50345. depthSlice: viewInfo.depthSlice,
  50346. resolveTarget: viewInfo.resolveTarget,
  50347. loadOp: colorAttachmentsConfig.loadOp || GPULoadOp.Load,
  50348. storeOp: colorAttachmentsConfig.storeOp || GPUStoreOp.Store,
  50349. clearValue: clearValue
  50350. } );
  50351. }
  50352. if ( descriptorBase.depthStencilView ) {
  50353. descriptor.depthStencilAttachment = {
  50354. view: descriptorBase.depthStencilView
  50355. };
  50356. }
  50357. return descriptor;
  50358. }
  50359. /**
  50360. * This method is executed at the beginning of a render call and prepares
  50361. * the WebGPU state for upcoming render calls
  50362. *
  50363. * @param {RenderContext} renderContext - The render context.
  50364. */
  50365. beginRender( renderContext ) {
  50366. const renderContextData = this.get( renderContext );
  50367. const device = this.device;
  50368. const occlusionQueryCount = renderContext.occlusionQueryCount;
  50369. let occlusionQuerySet;
  50370. if ( occlusionQueryCount > 0 ) {
  50371. if ( renderContextData.currentOcclusionQuerySet ) renderContextData.currentOcclusionQuerySet.destroy();
  50372. if ( renderContextData.currentOcclusionQueryBuffer ) renderContextData.currentOcclusionQueryBuffer.destroy();
  50373. // Get a reference to the array of objects with queries. The renderContextData property
  50374. // can be changed by another render pass before the buffer.mapAsyc() completes.
  50375. renderContextData.currentOcclusionQuerySet = renderContextData.occlusionQuerySet;
  50376. renderContextData.currentOcclusionQueryBuffer = renderContextData.occlusionQueryBuffer;
  50377. renderContextData.currentOcclusionQueryObjects = renderContextData.occlusionQueryObjects;
  50378. //
  50379. occlusionQuerySet = device.createQuerySet( { type: 'occlusion', count: occlusionQueryCount, label: `occlusionQuerySet_${ renderContext.id }` } );
  50380. renderContextData.occlusionQuerySet = occlusionQuerySet;
  50381. renderContextData.occlusionQueryIndex = 0;
  50382. renderContextData.occlusionQueryObjects = new Array( occlusionQueryCount );
  50383. renderContextData.lastOcclusionObject = null;
  50384. }
  50385. let descriptor;
  50386. if ( renderContext.textures === null ) {
  50387. descriptor = this._getDefaultRenderPassDescriptor();
  50388. } else {
  50389. descriptor = this._getRenderPassDescriptor( renderContext, { loadOp: GPULoadOp.Load } );
  50390. }
  50391. this.initTimestampQuery( renderContext, descriptor );
  50392. descriptor.occlusionQuerySet = occlusionQuerySet;
  50393. const depthStencilAttachment = descriptor.depthStencilAttachment;
  50394. if ( renderContext.textures !== null ) {
  50395. const colorAttachments = descriptor.colorAttachments;
  50396. for ( let i = 0; i < colorAttachments.length; i ++ ) {
  50397. const colorAttachment = colorAttachments[ i ];
  50398. if ( renderContext.clearColor ) {
  50399. colorAttachment.clearValue = i === 0 ? renderContext.clearColorValue : { r: 0, g: 0, b: 0, a: 1 };
  50400. colorAttachment.loadOp = GPULoadOp.Clear;
  50401. } else {
  50402. colorAttachment.loadOp = GPULoadOp.Load;
  50403. }
  50404. colorAttachment.storeOp = GPUStoreOp.Store;
  50405. }
  50406. } else {
  50407. const colorAttachment = descriptor.colorAttachments[ 0 ];
  50408. if ( renderContext.clearColor ) {
  50409. colorAttachment.clearValue = renderContext.clearColorValue;
  50410. colorAttachment.loadOp = GPULoadOp.Clear;
  50411. } else {
  50412. colorAttachment.loadOp = GPULoadOp.Load;
  50413. }
  50414. colorAttachment.storeOp = GPUStoreOp.Store;
  50415. }
  50416. //
  50417. if ( renderContext.depth ) {
  50418. if ( renderContext.clearDepth ) {
  50419. depthStencilAttachment.depthClearValue = renderContext.clearDepthValue;
  50420. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  50421. } else {
  50422. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  50423. }
  50424. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  50425. }
  50426. if ( renderContext.stencil ) {
  50427. if ( renderContext.clearStencil ) {
  50428. depthStencilAttachment.stencilClearValue = renderContext.clearStencilValue;
  50429. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  50430. } else {
  50431. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  50432. }
  50433. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  50434. }
  50435. //
  50436. const encoder = device.createCommandEncoder( { label: 'renderContext_' + renderContext.id } );
  50437. // shadow arrays - prepare bundle encoders for each camera in an array camera
  50438. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  50439. const cameras = renderContext.camera.cameras;
  50440. if ( ! renderContextData.layerDescriptors || renderContextData.layerDescriptors.length !== cameras.length ) {
  50441. this._createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras );
  50442. } else {
  50443. this._updateDepthLayerDescriptors( renderContext, renderContextData, cameras );
  50444. }
  50445. // Create bundle encoders for each layer
  50446. renderContextData.bundleEncoders = [];
  50447. renderContextData.bundleSets = [];
  50448. // Create separate bundle encoders for each camera in the array
  50449. for ( let i = 0; i < cameras.length; i ++ ) {
  50450. const bundleEncoder = this.pipelineUtils.createBundleEncoder(
  50451. renderContext,
  50452. 'renderBundleArrayCamera_' + i
  50453. );
  50454. // Initialize state tracking for this bundle
  50455. const bundleSets = {
  50456. attributes: {},
  50457. bindingGroups: [],
  50458. pipeline: null,
  50459. index: null
  50460. };
  50461. renderContextData.bundleEncoders.push( bundleEncoder );
  50462. renderContextData.bundleSets.push( bundleSets );
  50463. }
  50464. // We'll complete the bundles in finishRender
  50465. renderContextData.currentPass = null;
  50466. } else {
  50467. const currentPass = encoder.beginRenderPass( descriptor );
  50468. renderContextData.currentPass = currentPass;
  50469. if ( renderContext.viewport ) {
  50470. this.updateViewport( renderContext );
  50471. }
  50472. if ( renderContext.scissor ) {
  50473. const { x, y, width, height } = renderContext.scissorValue;
  50474. currentPass.setScissorRect( x, y, width, height );
  50475. }
  50476. }
  50477. //
  50478. renderContextData.descriptor = descriptor;
  50479. renderContextData.encoder = encoder;
  50480. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  50481. renderContextData.renderBundles = [];
  50482. }
  50483. /**
  50484. * This method creates layer descriptors for each camera in an array camera
  50485. * to prepare for rendering to a depth array texture.
  50486. *
  50487. * @param {RenderContext} renderContext - The render context.
  50488. * @param {Object} renderContextData - The render context data.
  50489. * @param {Object} descriptor - The render pass descriptor.
  50490. * @param {ArrayCamera} cameras - The array camera.
  50491. *
  50492. * @private
  50493. */
  50494. _createDepthLayerDescriptors( renderContext, renderContextData, descriptor, cameras ) {
  50495. const depthStencilAttachment = descriptor.depthStencilAttachment;
  50496. renderContextData.layerDescriptors = [];
  50497. const depthTextureData = this.get( renderContext.depthTexture );
  50498. if ( ! depthTextureData.viewCache ) {
  50499. depthTextureData.viewCache = [];
  50500. }
  50501. for ( let i = 0; i < cameras.length; i ++ ) {
  50502. const layerDescriptor = {
  50503. ...descriptor,
  50504. colorAttachments: [ {
  50505. ...descriptor.colorAttachments[ 0 ],
  50506. view: descriptor.colorAttachments[ i ].view
  50507. } ]
  50508. };
  50509. if ( descriptor.depthStencilAttachment ) {
  50510. const layerIndex = i;
  50511. if ( ! depthTextureData.viewCache[ layerIndex ] ) {
  50512. depthTextureData.viewCache[ layerIndex ] = depthTextureData.texture.createView( {
  50513. dimension: GPUTextureViewDimension.TwoD,
  50514. baseArrayLayer: i,
  50515. arrayLayerCount: 1
  50516. } );
  50517. }
  50518. layerDescriptor.depthStencilAttachment = {
  50519. view: depthTextureData.viewCache[ layerIndex ],
  50520. depthLoadOp: depthStencilAttachment.depthLoadOp || GPULoadOp.Clear,
  50521. depthStoreOp: depthStencilAttachment.depthStoreOp || GPUStoreOp.Store,
  50522. depthClearValue: depthStencilAttachment.depthClearValue || 1.0
  50523. };
  50524. if ( renderContext.stencil ) {
  50525. layerDescriptor.depthStencilAttachment.stencilLoadOp = depthStencilAttachment.stencilLoadOp;
  50526. layerDescriptor.depthStencilAttachment.stencilStoreOp = depthStencilAttachment.stencilStoreOp;
  50527. layerDescriptor.depthStencilAttachment.stencilClearValue = depthStencilAttachment.stencilClearValue;
  50528. }
  50529. } else {
  50530. layerDescriptor.depthStencilAttachment = { ...depthStencilAttachment };
  50531. }
  50532. renderContextData.layerDescriptors.push( layerDescriptor );
  50533. }
  50534. }
  50535. /**
  50536. * This method updates the layer descriptors for each camera in an array camera
  50537. * to prepare for rendering to a depth array texture.
  50538. *
  50539. * @param {RenderContext} renderContext - The render context.
  50540. * @param {Object} renderContextData - The render context data.
  50541. * @param {ArrayCamera} cameras - The array camera.
  50542. *
  50543. */
  50544. _updateDepthLayerDescriptors( renderContext, renderContextData, cameras ) {
  50545. for ( let i = 0; i < cameras.length; i ++ ) {
  50546. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  50547. if ( layerDescriptor.depthStencilAttachment ) {
  50548. const depthAttachment = layerDescriptor.depthStencilAttachment;
  50549. if ( renderContext.depth ) {
  50550. if ( renderContext.clearDepth ) {
  50551. depthAttachment.depthClearValue = renderContext.clearDepthValue;
  50552. depthAttachment.depthLoadOp = GPULoadOp.Clear;
  50553. } else {
  50554. depthAttachment.depthLoadOp = GPULoadOp.Load;
  50555. }
  50556. }
  50557. if ( renderContext.stencil ) {
  50558. if ( renderContext.clearStencil ) {
  50559. depthAttachment.stencilClearValue = renderContext.clearStencilValue;
  50560. depthAttachment.stencilLoadOp = GPULoadOp.Clear;
  50561. } else {
  50562. depthAttachment.stencilLoadOp = GPULoadOp.Load;
  50563. }
  50564. }
  50565. }
  50566. }
  50567. }
  50568. /**
  50569. * This method is executed at the end of a render call and finalizes work
  50570. * after draw calls.
  50571. *
  50572. * @param {RenderContext} renderContext - The render context.
  50573. */
  50574. finishRender( renderContext ) {
  50575. const renderContextData = this.get( renderContext );
  50576. const occlusionQueryCount = renderContext.occlusionQueryCount;
  50577. if ( renderContextData.renderBundles.length > 0 ) {
  50578. renderContextData.currentPass.executeBundles( renderContextData.renderBundles );
  50579. }
  50580. if ( occlusionQueryCount > renderContextData.occlusionQueryIndex ) {
  50581. renderContextData.currentPass.endOcclusionQuery();
  50582. }
  50583. // shadow arrays - Execute bundles for each layer
  50584. const encoder = renderContextData.encoder;
  50585. if ( this._isRenderCameraDepthArray( renderContext ) === true ) {
  50586. const bundles = [];
  50587. for ( let i = 0; i < renderContextData.bundleEncoders.length; i ++ ) {
  50588. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  50589. bundles.push( bundleEncoder.finish() );
  50590. }
  50591. for ( let i = 0; i < renderContextData.layerDescriptors.length; i ++ ) {
  50592. if ( i < bundles.length ) {
  50593. const layerDescriptor = renderContextData.layerDescriptors[ i ];
  50594. const renderPass = encoder.beginRenderPass( layerDescriptor );
  50595. if ( renderContext.viewport ) {
  50596. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  50597. renderPass.setViewport( x, y, width, height, minDepth, maxDepth );
  50598. }
  50599. if ( renderContext.scissor ) {
  50600. const { x, y, width, height } = renderContext.scissorValue;
  50601. renderPass.setScissorRect( x, y, width, height );
  50602. }
  50603. renderPass.executeBundles( [ bundles[ i ] ] );
  50604. renderPass.end();
  50605. }
  50606. }
  50607. } else if ( renderContextData.currentPass ) {
  50608. renderContextData.currentPass.end();
  50609. }
  50610. if ( occlusionQueryCount > 0 ) {
  50611. const bufferSize = occlusionQueryCount * 8; // 8 byte entries for query results
  50612. //
  50613. let queryResolveBuffer = this.occludedResolveCache.get( bufferSize );
  50614. if ( queryResolveBuffer === undefined ) {
  50615. queryResolveBuffer = this.device.createBuffer(
  50616. {
  50617. size: bufferSize,
  50618. usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC
  50619. }
  50620. );
  50621. this.occludedResolveCache.set( bufferSize, queryResolveBuffer );
  50622. }
  50623. //
  50624. const readBuffer = this.device.createBuffer(
  50625. {
  50626. size: bufferSize,
  50627. usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ
  50628. }
  50629. );
  50630. // two buffers required here - WebGPU doesn't allow usage of QUERY_RESOLVE & MAP_READ to be combined
  50631. renderContextData.encoder.resolveQuerySet( renderContextData.occlusionQuerySet, 0, occlusionQueryCount, queryResolveBuffer, 0 );
  50632. renderContextData.encoder.copyBufferToBuffer( queryResolveBuffer, 0, readBuffer, 0, bufferSize );
  50633. renderContextData.occlusionQueryBuffer = readBuffer;
  50634. //
  50635. this.resolveOccludedAsync( renderContext );
  50636. }
  50637. this.device.queue.submit( [ renderContextData.encoder.finish() ] );
  50638. //
  50639. if ( renderContext.textures !== null ) {
  50640. const textures = renderContext.textures;
  50641. for ( let i = 0; i < textures.length; i ++ ) {
  50642. const texture = textures[ i ];
  50643. if ( texture.generateMipmaps === true ) {
  50644. this.textureUtils.generateMipmaps( texture );
  50645. }
  50646. }
  50647. }
  50648. }
  50649. /**
  50650. * Returns `true` if the given 3D object is fully occluded by other
  50651. * 3D objects in the scene.
  50652. *
  50653. * @param {RenderContext} renderContext - The render context.
  50654. * @param {Object3D} object - The 3D object to test.
  50655. * @return {boolean} Whether the 3D object is fully occluded or not.
  50656. */
  50657. isOccluded( renderContext, object ) {
  50658. const renderContextData = this.get( renderContext );
  50659. return renderContextData.occluded && renderContextData.occluded.has( object );
  50660. }
  50661. /**
  50662. * This method processes the result of occlusion queries and writes it
  50663. * into render context data.
  50664. *
  50665. * @async
  50666. * @param {RenderContext} renderContext - The render context.
  50667. * @return {Promise} A Promise that resolves when the occlusion query results have been processed.
  50668. */
  50669. async resolveOccludedAsync( renderContext ) {
  50670. const renderContextData = this.get( renderContext );
  50671. // handle occlusion query results
  50672. const { currentOcclusionQueryBuffer, currentOcclusionQueryObjects } = renderContextData;
  50673. if ( currentOcclusionQueryBuffer && currentOcclusionQueryObjects ) {
  50674. const occluded = new WeakSet();
  50675. renderContextData.currentOcclusionQueryObjects = null;
  50676. renderContextData.currentOcclusionQueryBuffer = null;
  50677. await currentOcclusionQueryBuffer.mapAsync( GPUMapMode.READ );
  50678. const buffer = currentOcclusionQueryBuffer.getMappedRange();
  50679. const results = new BigUint64Array( buffer );
  50680. for ( let i = 0; i < currentOcclusionQueryObjects.length; i ++ ) {
  50681. if ( results[ i ] === BigInt( 0 ) ) {
  50682. occluded.add( currentOcclusionQueryObjects[ i ] );
  50683. }
  50684. }
  50685. currentOcclusionQueryBuffer.destroy();
  50686. renderContextData.occluded = occluded;
  50687. }
  50688. }
  50689. /**
  50690. * Updates the viewport with the values from the given render context.
  50691. *
  50692. * @param {RenderContext} renderContext - The render context.
  50693. */
  50694. updateViewport( renderContext ) {
  50695. const { currentPass } = this.get( renderContext );
  50696. const { x, y, width, height, minDepth, maxDepth } = renderContext.viewportValue;
  50697. currentPass.setViewport( x, y, width, height, minDepth, maxDepth );
  50698. }
  50699. /**
  50700. * Returns the clear color and alpha into a single
  50701. * color object.
  50702. *
  50703. * @return {Color4} The clear color.
  50704. */
  50705. getClearColor() {
  50706. const clearColor = super.getClearColor();
  50707. // only premultiply alpha when alphaMode is "premultiplied"
  50708. if ( this.renderer.alpha === true ) {
  50709. clearColor.r *= clearColor.a;
  50710. clearColor.g *= clearColor.a;
  50711. clearColor.b *= clearColor.a;
  50712. }
  50713. return clearColor;
  50714. }
  50715. /**
  50716. * Performs a clear operation.
  50717. *
  50718. * @param {boolean} color - Whether the color buffer should be cleared or not.
  50719. * @param {boolean} depth - Whether the depth buffer should be cleared or not.
  50720. * @param {boolean} stencil - Whether the stencil buffer should be cleared or not.
  50721. * @param {?RenderContext} [renderTargetContext=null] - The render context of the current set render target.
  50722. */
  50723. clear( color, depth, stencil, renderTargetContext = null ) {
  50724. const device = this.device;
  50725. const renderer = this.renderer;
  50726. let colorAttachments = [];
  50727. let depthStencilAttachment;
  50728. let clearValue;
  50729. let supportsDepth;
  50730. let supportsStencil;
  50731. if ( color ) {
  50732. const clearColor = this.getClearColor();
  50733. clearValue = { r: clearColor.r, g: clearColor.g, b: clearColor.b, a: clearColor.a };
  50734. }
  50735. if ( renderTargetContext === null ) {
  50736. supportsDepth = renderer.depth;
  50737. supportsStencil = renderer.stencil;
  50738. const descriptor = this._getDefaultRenderPassDescriptor();
  50739. if ( color ) {
  50740. colorAttachments = descriptor.colorAttachments;
  50741. const colorAttachment = colorAttachments[ 0 ];
  50742. colorAttachment.clearValue = clearValue;
  50743. colorAttachment.loadOp = GPULoadOp.Clear;
  50744. colorAttachment.storeOp = GPUStoreOp.Store;
  50745. }
  50746. if ( supportsDepth || supportsStencil ) {
  50747. depthStencilAttachment = descriptor.depthStencilAttachment;
  50748. }
  50749. } else {
  50750. supportsDepth = renderTargetContext.depth;
  50751. supportsStencil = renderTargetContext.stencil;
  50752. const clearConfig = {
  50753. loadOp: color ? GPULoadOp.Clear : GPULoadOp.Load,
  50754. clearValue: color ? clearValue : undefined
  50755. };
  50756. if ( supportsDepth ) {
  50757. clearConfig.depthLoadOp = depth ? GPULoadOp.Clear : GPULoadOp.Load;
  50758. clearConfig.depthClearValue = depth ? renderer.getClearDepth() : undefined;
  50759. clearConfig.depthStoreOp = GPUStoreOp.Store;
  50760. }
  50761. if ( supportsStencil ) {
  50762. clearConfig.stencilLoadOp = stencil ? GPULoadOp.Clear : GPULoadOp.Load;
  50763. clearConfig.stencilClearValue = stencil ? renderer.getClearStencil() : undefined;
  50764. clearConfig.stencilStoreOp = GPUStoreOp.Store;
  50765. }
  50766. const descriptor = this._getRenderPassDescriptor( renderTargetContext, clearConfig );
  50767. colorAttachments = descriptor.colorAttachments;
  50768. depthStencilAttachment = descriptor.depthStencilAttachment;
  50769. }
  50770. if ( supportsDepth && depthStencilAttachment && depthStencilAttachment.depthLoadOp === undefined ) {
  50771. if ( depth ) {
  50772. depthStencilAttachment.depthLoadOp = GPULoadOp.Clear;
  50773. depthStencilAttachment.depthClearValue = renderer.getClearDepth();
  50774. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  50775. } else {
  50776. depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  50777. depthStencilAttachment.depthStoreOp = GPUStoreOp.Store;
  50778. }
  50779. }
  50780. //
  50781. if ( supportsStencil && depthStencilAttachment && depthStencilAttachment.stencilLoadOp === undefined ) {
  50782. if ( stencil ) {
  50783. depthStencilAttachment.stencilLoadOp = GPULoadOp.Clear;
  50784. depthStencilAttachment.stencilClearValue = renderer.getClearStencil();
  50785. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  50786. } else {
  50787. depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  50788. depthStencilAttachment.stencilStoreOp = GPUStoreOp.Store;
  50789. }
  50790. }
  50791. //
  50792. const encoder = device.createCommandEncoder( { label: 'clear' } );
  50793. const currentPass = encoder.beginRenderPass( {
  50794. colorAttachments,
  50795. depthStencilAttachment
  50796. } );
  50797. currentPass.end();
  50798. device.queue.submit( [ encoder.finish() ] );
  50799. }
  50800. // compute
  50801. /**
  50802. * This method is executed at the beginning of a compute call and
  50803. * prepares the state for upcoming compute tasks.
  50804. *
  50805. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  50806. */
  50807. beginCompute( computeGroup ) {
  50808. const groupGPU = this.get( computeGroup );
  50809. const descriptor = {
  50810. label: 'computeGroup_' + computeGroup.id
  50811. };
  50812. this.initTimestampQuery( computeGroup, descriptor );
  50813. groupGPU.cmdEncoderGPU = this.device.createCommandEncoder( { label: 'computeGroup_' + computeGroup.id } );
  50814. groupGPU.passEncoderGPU = groupGPU.cmdEncoderGPU.beginComputePass( descriptor );
  50815. }
  50816. /**
  50817. * Executes a compute command for the given compute node.
  50818. *
  50819. * @param {Node|Array<Node>} computeGroup - The group of compute nodes of a compute call. Can be a single compute node.
  50820. * @param {Node} computeNode - The compute node.
  50821. * @param {Array<BindGroup>} bindings - The bindings.
  50822. * @param {ComputePipeline} pipeline - The compute pipeline.
  50823. */
  50824. compute( computeGroup, computeNode, bindings, pipeline ) {
  50825. const { passEncoderGPU } = this.get( computeGroup );
  50826. // pipeline
  50827. const pipelineGPU = this.get( pipeline ).pipeline;
  50828. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  50829. // bind groups
  50830. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  50831. const bindGroup = bindings[ i ];
  50832. const bindingsData = this.get( bindGroup );
  50833. passEncoderGPU.setBindGroup( i, bindingsData.group );
  50834. }
  50835. const maxComputeWorkgroupsPerDimension = this.device.limits.maxComputeWorkgroupsPerDimension;
  50836. const computeNodeData = this.get( computeNode );
  50837. if ( computeNodeData.dispatchSize === undefined ) computeNodeData.dispatchSize = { x: 0, y: 1, z: 1 };
  50838. const { dispatchSize } = computeNodeData;
  50839. if ( computeNode.dispatchCount > maxComputeWorkgroupsPerDimension ) {
  50840. dispatchSize.x = Math.min( computeNode.dispatchCount, maxComputeWorkgroupsPerDimension );
  50841. dispatchSize.y = Math.ceil( computeNode.dispatchCount / maxComputeWorkgroupsPerDimension );
  50842. } else {
  50843. dispatchSize.x = computeNode.dispatchCount;
  50844. }
  50845. passEncoderGPU.dispatchWorkgroups(
  50846. dispatchSize.x,
  50847. dispatchSize.y,
  50848. dispatchSize.z
  50849. );
  50850. }
  50851. /**
  50852. * This method is executed at the end of a compute call and
  50853. * finalizes work after compute tasks.
  50854. *
  50855. * @param {Node|Array<Node>} computeGroup - The compute node(s).
  50856. */
  50857. finishCompute( computeGroup ) {
  50858. const groupData = this.get( computeGroup );
  50859. groupData.passEncoderGPU.end();
  50860. this.device.queue.submit( [ groupData.cmdEncoderGPU.finish() ] );
  50861. }
  50862. /**
  50863. * Can be used to synchronize CPU operations with GPU tasks. So when this method is called,
  50864. * the CPU waits for the GPU to complete its operation (e.g. a compute task).
  50865. *
  50866. * @async
  50867. * @return {Promise} A Promise that resolves when synchronization has been finished.
  50868. */
  50869. async waitForGPU() {
  50870. await this.device.queue.onSubmittedWorkDone();
  50871. }
  50872. // render object
  50873. /**
  50874. * Executes a draw command for the given render object.
  50875. *
  50876. * @param {RenderObject} renderObject - The render object to draw.
  50877. * @param {Info} info - Holds a series of statistical information about the GPU memory and the rendering process.
  50878. */
  50879. draw( renderObject, info ) {
  50880. const { object, material, context, pipeline } = renderObject;
  50881. const bindings = renderObject.getBindings();
  50882. const renderContextData = this.get( context );
  50883. const pipelineGPU = this.get( pipeline ).pipeline;
  50884. const index = renderObject.getIndex();
  50885. const hasIndex = ( index !== null );
  50886. const drawParams = renderObject.getDrawParameters();
  50887. if ( drawParams === null ) return;
  50888. // pipeline
  50889. const setPipelineAndBindings = ( passEncoderGPU, currentSets ) => {
  50890. // pipeline
  50891. this.pipelineUtils.setPipeline( passEncoderGPU, pipelineGPU );
  50892. currentSets.pipeline = pipelineGPU;
  50893. // bind groups
  50894. const currentBindingGroups = currentSets.bindingGroups;
  50895. for ( let i = 0, l = bindings.length; i < l; i ++ ) {
  50896. const bindGroup = bindings[ i ];
  50897. const bindingsData = this.get( bindGroup );
  50898. if ( currentBindingGroups[ bindGroup.index ] !== bindGroup.id ) {
  50899. passEncoderGPU.setBindGroup( bindGroup.index, bindingsData.group );
  50900. currentBindingGroups[ bindGroup.index ] = bindGroup.id;
  50901. }
  50902. }
  50903. // attributes
  50904. // index
  50905. if ( hasIndex === true ) {
  50906. if ( currentSets.index !== index ) {
  50907. const buffer = this.get( index ).buffer;
  50908. const indexFormat = ( index.array instanceof Uint16Array ) ? GPUIndexFormat.Uint16 : GPUIndexFormat.Uint32;
  50909. passEncoderGPU.setIndexBuffer( buffer, indexFormat );
  50910. currentSets.index = index;
  50911. }
  50912. }
  50913. // vertex buffers
  50914. const vertexBuffers = renderObject.getVertexBuffers();
  50915. for ( let i = 0, l = vertexBuffers.length; i < l; i ++ ) {
  50916. const vertexBuffer = vertexBuffers[ i ];
  50917. if ( currentSets.attributes[ i ] !== vertexBuffer ) {
  50918. const buffer = this.get( vertexBuffer ).buffer;
  50919. passEncoderGPU.setVertexBuffer( i, buffer );
  50920. currentSets.attributes[ i ] = vertexBuffer;
  50921. }
  50922. }
  50923. // stencil
  50924. if ( context.stencil === true && material.stencilWrite === true && renderContextData.currentStencilRef !== material.stencilRef ) {
  50925. passEncoderGPU.setStencilReference( material.stencilRef );
  50926. renderContextData.currentStencilRef = material.stencilRef;
  50927. }
  50928. };
  50929. // Define draw function
  50930. const draw = ( passEncoderGPU, currentSets ) => {
  50931. setPipelineAndBindings( passEncoderGPU, currentSets );
  50932. if ( object.isBatchedMesh === true ) {
  50933. const starts = object._multiDrawStarts;
  50934. const counts = object._multiDrawCounts;
  50935. const drawCount = object._multiDrawCount;
  50936. const drawInstances = object._multiDrawInstances;
  50937. if ( drawInstances !== null ) {
  50938. // @deprecated, r174
  50939. warnOnce( 'THREE.WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.' );
  50940. }
  50941. for ( let i = 0; i < drawCount; i ++ ) {
  50942. const count = drawInstances ? drawInstances[ i ] : 1;
  50943. const firstInstance = count > 1 ? 0 : i;
  50944. if ( hasIndex === true ) {
  50945. passEncoderGPU.drawIndexed( counts[ i ], count, starts[ i ] / index.array.BYTES_PER_ELEMENT, 0, firstInstance );
  50946. } else {
  50947. passEncoderGPU.draw( counts[ i ], count, starts[ i ], firstInstance );
  50948. }
  50949. info.update( object, counts[ i ], count );
  50950. }
  50951. } else if ( hasIndex === true ) {
  50952. const { vertexCount: indexCount, instanceCount, firstVertex: firstIndex } = drawParams;
  50953. const indirect = renderObject.getIndirect();
  50954. if ( indirect !== null ) {
  50955. const buffer = this.get( indirect ).buffer;
  50956. passEncoderGPU.drawIndexedIndirect( buffer, 0 );
  50957. } else {
  50958. passEncoderGPU.drawIndexed( indexCount, instanceCount, firstIndex, 0, 0 );
  50959. }
  50960. info.update( object, indexCount, instanceCount );
  50961. } else {
  50962. const { vertexCount, instanceCount, firstVertex } = drawParams;
  50963. const indirect = renderObject.getIndirect();
  50964. if ( indirect !== null ) {
  50965. const buffer = this.get( indirect ).buffer;
  50966. passEncoderGPU.drawIndirect( buffer, 0 );
  50967. } else {
  50968. passEncoderGPU.draw( vertexCount, instanceCount, firstVertex, 0 );
  50969. }
  50970. info.update( object, vertexCount, instanceCount );
  50971. }
  50972. };
  50973. if ( renderObject.camera.isArrayCamera && renderObject.camera.cameras.length > 0 ) {
  50974. const cameraData = this.get( renderObject.camera );
  50975. const cameras = renderObject.camera.cameras;
  50976. const cameraIndex = renderObject.getBindingGroup( 'cameraIndex' );
  50977. if ( cameraData.indexesGPU === undefined || cameraData.indexesGPU.length !== cameras.length ) {
  50978. const bindingsData = this.get( cameraIndex );
  50979. const indexesGPU = [];
  50980. const data = new Uint32Array( [ 0, 0, 0, 0 ] );
  50981. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  50982. data[ 0 ] = i;
  50983. const bindGroupIndex = this.bindingUtils.createBindGroupIndex( data, bindingsData.layout );
  50984. indexesGPU.push( bindGroupIndex );
  50985. }
  50986. cameraData.indexesGPU = indexesGPU; // TODO: Create a global library for this
  50987. }
  50988. const pixelRatio = this.renderer.getPixelRatio();
  50989. for ( let i = 0, len = cameras.length; i < len; i ++ ) {
  50990. const subCamera = cameras[ i ];
  50991. if ( object.layers.test( subCamera.layers ) ) {
  50992. const vp = subCamera.viewport;
  50993. let pass = renderContextData.currentPass;
  50994. let sets = renderContextData.currentSets;
  50995. if ( renderContextData.bundleEncoders ) {
  50996. const bundleEncoder = renderContextData.bundleEncoders[ i ];
  50997. const bundleSets = renderContextData.bundleSets[ i ];
  50998. pass = bundleEncoder;
  50999. sets = bundleSets;
  51000. }
  51001. if ( vp ) {
  51002. pass.setViewport(
  51003. Math.floor( vp.x * pixelRatio ),
  51004. Math.floor( vp.y * pixelRatio ),
  51005. Math.floor( vp.width * pixelRatio ),
  51006. Math.floor( vp.height * pixelRatio ),
  51007. context.viewportValue.minDepth,
  51008. context.viewportValue.maxDepth
  51009. );
  51010. }
  51011. // Set camera index binding for this layer
  51012. if ( cameraIndex && cameraData.indexesGPU ) {
  51013. pass.setBindGroup( cameraIndex.index, cameraData.indexesGPU[ i ] );
  51014. sets.bindingGroups[ cameraIndex.index ] = cameraIndex.id;
  51015. }
  51016. draw( pass, sets );
  51017. }
  51018. }
  51019. } else {
  51020. // Regular single camera rendering
  51021. if ( renderContextData.currentPass ) {
  51022. // Handle occlusion queries
  51023. if ( renderContextData.occlusionQuerySet !== undefined ) {
  51024. const lastObject = renderContextData.lastOcclusionObject;
  51025. if ( lastObject !== object ) {
  51026. if ( lastObject !== null && lastObject.occlusionTest === true ) {
  51027. renderContextData.currentPass.endOcclusionQuery();
  51028. renderContextData.occlusionQueryIndex ++;
  51029. }
  51030. if ( object.occlusionTest === true ) {
  51031. renderContextData.currentPass.beginOcclusionQuery( renderContextData.occlusionQueryIndex );
  51032. renderContextData.occlusionQueryObjects[ renderContextData.occlusionQueryIndex ] = object;
  51033. }
  51034. renderContextData.lastOcclusionObject = object;
  51035. }
  51036. }
  51037. draw( renderContextData.currentPass, renderContextData.currentSets );
  51038. }
  51039. }
  51040. }
  51041. // cache key
  51042. /**
  51043. * Returns `true` if the render pipeline requires an update.
  51044. *
  51045. * @param {RenderObject} renderObject - The render object.
  51046. * @return {boolean} Whether the render pipeline requires an update or not.
  51047. */
  51048. needsRenderUpdate( renderObject ) {
  51049. const data = this.get( renderObject );
  51050. const { object, material } = renderObject;
  51051. const utils = this.utils;
  51052. const sampleCount = utils.getSampleCountRenderContext( renderObject.context );
  51053. const colorSpace = utils.getCurrentColorSpace( renderObject.context );
  51054. const colorFormat = utils.getCurrentColorFormat( renderObject.context );
  51055. const depthStencilFormat = utils.getCurrentDepthStencilFormat( renderObject.context );
  51056. const primitiveTopology = utils.getPrimitiveTopology( object, material );
  51057. let needsUpdate = false;
  51058. if ( data.material !== material || data.materialVersion !== material.version ||
  51059. data.transparent !== material.transparent || data.blending !== material.blending || data.premultipliedAlpha !== material.premultipliedAlpha ||
  51060. data.blendSrc !== material.blendSrc || data.blendDst !== material.blendDst || data.blendEquation !== material.blendEquation ||
  51061. data.blendSrcAlpha !== material.blendSrcAlpha || data.blendDstAlpha !== material.blendDstAlpha || data.blendEquationAlpha !== material.blendEquationAlpha ||
  51062. data.colorWrite !== material.colorWrite || data.depthWrite !== material.depthWrite || data.depthTest !== material.depthTest || data.depthFunc !== material.depthFunc ||
  51063. data.stencilWrite !== material.stencilWrite || data.stencilFunc !== material.stencilFunc ||
  51064. data.stencilFail !== material.stencilFail || data.stencilZFail !== material.stencilZFail || data.stencilZPass !== material.stencilZPass ||
  51065. data.stencilFuncMask !== material.stencilFuncMask || data.stencilWriteMask !== material.stencilWriteMask ||
  51066. data.side !== material.side || data.alphaToCoverage !== material.alphaToCoverage ||
  51067. data.sampleCount !== sampleCount || data.colorSpace !== colorSpace ||
  51068. data.colorFormat !== colorFormat || data.depthStencilFormat !== depthStencilFormat ||
  51069. data.primitiveTopology !== primitiveTopology ||
  51070. data.clippingContextCacheKey !== renderObject.clippingContextCacheKey
  51071. ) {
  51072. data.material = material; data.materialVersion = material.version;
  51073. data.transparent = material.transparent; data.blending = material.blending; data.premultipliedAlpha = material.premultipliedAlpha;
  51074. data.blendSrc = material.blendSrc; data.blendDst = material.blendDst; data.blendEquation = material.blendEquation;
  51075. data.blendSrcAlpha = material.blendSrcAlpha; data.blendDstAlpha = material.blendDstAlpha; data.blendEquationAlpha = material.blendEquationAlpha;
  51076. data.colorWrite = material.colorWrite;
  51077. data.depthWrite = material.depthWrite; data.depthTest = material.depthTest; data.depthFunc = material.depthFunc;
  51078. data.stencilWrite = material.stencilWrite; data.stencilFunc = material.stencilFunc;
  51079. data.stencilFail = material.stencilFail; data.stencilZFail = material.stencilZFail; data.stencilZPass = material.stencilZPass;
  51080. data.stencilFuncMask = material.stencilFuncMask; data.stencilWriteMask = material.stencilWriteMask;
  51081. data.side = material.side; data.alphaToCoverage = material.alphaToCoverage;
  51082. data.sampleCount = sampleCount;
  51083. data.colorSpace = colorSpace;
  51084. data.colorFormat = colorFormat;
  51085. data.depthStencilFormat = depthStencilFormat;
  51086. data.primitiveTopology = primitiveTopology;
  51087. data.clippingContextCacheKey = renderObject.clippingContextCacheKey;
  51088. needsUpdate = true;
  51089. }
  51090. return needsUpdate;
  51091. }
  51092. /**
  51093. * Returns a cache key that is used to identify render pipelines.
  51094. *
  51095. * @param {RenderObject} renderObject - The render object.
  51096. * @return {string} The cache key.
  51097. */
  51098. getRenderCacheKey( renderObject ) {
  51099. const { object, material } = renderObject;
  51100. const utils = this.utils;
  51101. const renderContext = renderObject.context;
  51102. return [
  51103. material.transparent, material.blending, material.premultipliedAlpha,
  51104. material.blendSrc, material.blendDst, material.blendEquation,
  51105. material.blendSrcAlpha, material.blendDstAlpha, material.blendEquationAlpha,
  51106. material.colorWrite,
  51107. material.depthWrite, material.depthTest, material.depthFunc,
  51108. material.stencilWrite, material.stencilFunc,
  51109. material.stencilFail, material.stencilZFail, material.stencilZPass,
  51110. material.stencilFuncMask, material.stencilWriteMask,
  51111. material.side,
  51112. utils.getSampleCountRenderContext( renderContext ),
  51113. utils.getCurrentColorSpace( renderContext ), utils.getCurrentColorFormat( renderContext ), utils.getCurrentDepthStencilFormat( renderContext ),
  51114. utils.getPrimitiveTopology( object, material ),
  51115. renderObject.getGeometryCacheKey(),
  51116. renderObject.clippingContextCacheKey
  51117. ].join();
  51118. }
  51119. // textures
  51120. /**
  51121. * Creates a GPU sampler for the given texture.
  51122. *
  51123. * @param {Texture} texture - The texture to create the sampler for.
  51124. */
  51125. createSampler( texture ) {
  51126. this.textureUtils.createSampler( texture );
  51127. }
  51128. /**
  51129. * Destroys the GPU sampler for the given texture.
  51130. *
  51131. * @param {Texture} texture - The texture to destroy the sampler for.
  51132. */
  51133. destroySampler( texture ) {
  51134. this.textureUtils.destroySampler( texture );
  51135. }
  51136. /**
  51137. * Creates a default texture for the given texture that can be used
  51138. * as a placeholder until the actual texture is ready for usage.
  51139. *
  51140. * @param {Texture} texture - The texture to create a default texture for.
  51141. */
  51142. createDefaultTexture( texture ) {
  51143. this.textureUtils.createDefaultTexture( texture );
  51144. }
  51145. /**
  51146. * Defines a texture on the GPU for the given texture object.
  51147. *
  51148. * @param {Texture} texture - The texture.
  51149. * @param {Object} [options={}] - Optional configuration parameter.
  51150. */
  51151. createTexture( texture, options ) {
  51152. this.textureUtils.createTexture( texture, options );
  51153. }
  51154. /**
  51155. * Uploads the updated texture data to the GPU.
  51156. *
  51157. * @param {Texture} texture - The texture.
  51158. * @param {Object} [options={}] - Optional configuration parameter.
  51159. */
  51160. updateTexture( texture, options ) {
  51161. this.textureUtils.updateTexture( texture, options );
  51162. }
  51163. /**
  51164. * Generates mipmaps for the given texture.
  51165. *
  51166. * @param {Texture} texture - The texture.
  51167. */
  51168. generateMipmaps( texture ) {
  51169. this.textureUtils.generateMipmaps( texture );
  51170. }
  51171. /**
  51172. * Destroys the GPU data for the given texture object.
  51173. *
  51174. * @param {Texture} texture - The texture.
  51175. */
  51176. destroyTexture( texture ) {
  51177. this.textureUtils.destroyTexture( texture );
  51178. }
  51179. /**
  51180. * Returns texture data as a typed array.
  51181. *
  51182. * @async
  51183. * @param {Texture} texture - The texture to copy.
  51184. * @param {number} x - The x coordinate of the copy origin.
  51185. * @param {number} y - The y coordinate of the copy origin.
  51186. * @param {number} width - The width of the copy.
  51187. * @param {number} height - The height of the copy.
  51188. * @param {number} faceIndex - The face index.
  51189. * @return {Promise<TypedArray>} A Promise that resolves with a typed array when the copy operation has finished.
  51190. */
  51191. async copyTextureToBuffer( texture, x, y, width, height, faceIndex ) {
  51192. return this.textureUtils.copyTextureToBuffer( texture, x, y, width, height, faceIndex );
  51193. }
  51194. /**
  51195. * Inits a time stamp query for the given render context.
  51196. *
  51197. * @param {RenderContext} renderContext - The render context.
  51198. * @param {Object} descriptor - The query descriptor.
  51199. */
  51200. initTimestampQuery( renderContext, descriptor ) {
  51201. if ( ! this.trackTimestamp ) return;
  51202. const type = renderContext.isComputeNode ? 'compute' : 'render';
  51203. if ( ! this.timestampQueryPool[ type ] ) {
  51204. // TODO: Variable maxQueries?
  51205. this.timestampQueryPool[ type ] = new WebGPUTimestampQueryPool( this.device, type, 2048 );
  51206. }
  51207. const timestampQueryPool = this.timestampQueryPool[ type ];
  51208. const baseOffset = timestampQueryPool.allocateQueriesForContext( renderContext );
  51209. descriptor.timestampWrites = {
  51210. querySet: timestampQueryPool.querySet,
  51211. beginningOfPassWriteIndex: baseOffset,
  51212. endOfPassWriteIndex: baseOffset + 1,
  51213. };
  51214. }
  51215. // node builder
  51216. /**
  51217. * Returns a node builder for the given render object.
  51218. *
  51219. * @param {RenderObject} object - The render object.
  51220. * @param {Renderer} renderer - The renderer.
  51221. * @return {WGSLNodeBuilder} The node builder.
  51222. */
  51223. createNodeBuilder( object, renderer ) {
  51224. return new WGSLNodeBuilder( object, renderer );
  51225. }
  51226. // program
  51227. /**
  51228. * Creates a shader program from the given programmable stage.
  51229. *
  51230. * @param {ProgrammableStage} program - The programmable stage.
  51231. */
  51232. createProgram( program ) {
  51233. const programGPU = this.get( program );
  51234. programGPU.module = {
  51235. module: this.device.createShaderModule( { code: program.code, label: program.stage + ( program.name !== '' ? `_${ program.name }` : '' ) } ),
  51236. entryPoint: 'main'
  51237. };
  51238. }
  51239. /**
  51240. * Destroys the shader program of the given programmable stage.
  51241. *
  51242. * @param {ProgrammableStage} program - The programmable stage.
  51243. */
  51244. destroyProgram( program ) {
  51245. this.delete( program );
  51246. }
  51247. // pipelines
  51248. /**
  51249. * Creates a render pipeline for the given render object.
  51250. *
  51251. * @param {RenderObject} renderObject - The render object.
  51252. * @param {Array<Promise>} promises - An array of compilation promises which are used in `compileAsync()`.
  51253. */
  51254. createRenderPipeline( renderObject, promises ) {
  51255. this.pipelineUtils.createRenderPipeline( renderObject, promises );
  51256. }
  51257. /**
  51258. * Creates a compute pipeline for the given compute node.
  51259. *
  51260. * @param {ComputePipeline} computePipeline - The compute pipeline.
  51261. * @param {Array<BindGroup>} bindings - The bindings.
  51262. */
  51263. createComputePipeline( computePipeline, bindings ) {
  51264. this.pipelineUtils.createComputePipeline( computePipeline, bindings );
  51265. }
  51266. /**
  51267. * Prepares the state for encoding render bundles.
  51268. *
  51269. * @param {RenderContext} renderContext - The render context.
  51270. */
  51271. beginBundle( renderContext ) {
  51272. const renderContextData = this.get( renderContext );
  51273. renderContextData._currentPass = renderContextData.currentPass;
  51274. renderContextData._currentSets = renderContextData.currentSets;
  51275. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  51276. renderContextData.currentPass = this.pipelineUtils.createBundleEncoder( renderContext );
  51277. }
  51278. /**
  51279. * After processing render bundles this method finalizes related work.
  51280. *
  51281. * @param {RenderContext} renderContext - The render context.
  51282. * @param {RenderBundle} bundle - The render bundle.
  51283. */
  51284. finishBundle( renderContext, bundle ) {
  51285. const renderContextData = this.get( renderContext );
  51286. const bundleEncoder = renderContextData.currentPass;
  51287. const bundleGPU = bundleEncoder.finish();
  51288. this.get( bundle ).bundleGPU = bundleGPU;
  51289. // restore render pass state
  51290. renderContextData.currentSets = renderContextData._currentSets;
  51291. renderContextData.currentPass = renderContextData._currentPass;
  51292. }
  51293. /**
  51294. * Adds a render bundle to the render context data.
  51295. *
  51296. * @param {RenderContext} renderContext - The render context.
  51297. * @param {RenderBundle} bundle - The render bundle to add.
  51298. */
  51299. addBundle( renderContext, bundle ) {
  51300. const renderContextData = this.get( renderContext );
  51301. renderContextData.renderBundles.push( this.get( bundle ).bundleGPU );
  51302. }
  51303. // bindings
  51304. /**
  51305. * Creates bindings from the given bind group definition.
  51306. *
  51307. * @param {BindGroup} bindGroup - The bind group.
  51308. * @param {Array<BindGroup>} bindings - Array of bind groups.
  51309. * @param {number} cacheIndex - The cache index.
  51310. * @param {number} version - The version.
  51311. */
  51312. createBindings( bindGroup, bindings, cacheIndex, version ) {
  51313. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  51314. }
  51315. /**
  51316. * Updates the given bind group definition.
  51317. *
  51318. * @param {BindGroup} bindGroup - The bind group.
  51319. * @param {Array<BindGroup>} bindings - Array of bind groups.
  51320. * @param {number} cacheIndex - The cache index.
  51321. * @param {number} version - The version.
  51322. */
  51323. updateBindings( bindGroup, bindings, cacheIndex, version ) {
  51324. this.bindingUtils.createBindings( bindGroup, bindings, cacheIndex, version );
  51325. }
  51326. /**
  51327. * Updates a buffer binding.
  51328. *
  51329. * @param {Buffer} binding - The buffer binding to update.
  51330. */
  51331. updateBinding( binding ) {
  51332. this.bindingUtils.updateBinding( binding );
  51333. }
  51334. // attributes
  51335. /**
  51336. * Creates the buffer of an indexed shader attribute.
  51337. *
  51338. * @param {BufferAttribute} attribute - The indexed buffer attribute.
  51339. */
  51340. createIndexAttribute( attribute ) {
  51341. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.INDEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  51342. }
  51343. /**
  51344. * Creates the GPU buffer of a shader attribute.
  51345. *
  51346. * @param {BufferAttribute} attribute - The buffer attribute.
  51347. */
  51348. createAttribute( attribute ) {
  51349. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  51350. }
  51351. /**
  51352. * Creates the GPU buffer of a storage attribute.
  51353. *
  51354. * @param {BufferAttribute} attribute - The buffer attribute.
  51355. */
  51356. createStorageAttribute( attribute ) {
  51357. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  51358. }
  51359. /**
  51360. * Creates the GPU buffer of an indirect storage attribute.
  51361. *
  51362. * @param {BufferAttribute} attribute - The buffer attribute.
  51363. */
  51364. createIndirectStorageAttribute( attribute ) {
  51365. this.attributeUtils.createAttribute( attribute, GPUBufferUsage.STORAGE | GPUBufferUsage.INDIRECT | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST );
  51366. }
  51367. /**
  51368. * Updates the GPU buffer of a shader attribute.
  51369. *
  51370. * @param {BufferAttribute} attribute - The buffer attribute to update.
  51371. */
  51372. updateAttribute( attribute ) {
  51373. this.attributeUtils.updateAttribute( attribute );
  51374. }
  51375. /**
  51376. * Destroys the GPU buffer of a shader attribute.
  51377. *
  51378. * @param {BufferAttribute} attribute - The buffer attribute to destroy.
  51379. */
  51380. destroyAttribute( attribute ) {
  51381. this.attributeUtils.destroyAttribute( attribute );
  51382. }
  51383. // canvas
  51384. /**
  51385. * Triggers an update of the default render pass descriptor.
  51386. */
  51387. updateSize() {
  51388. this.colorBuffer = this.textureUtils.getColorBuffer();
  51389. this.defaultRenderPassdescriptor = null;
  51390. }
  51391. // utils public
  51392. /**
  51393. * Returns the maximum anisotropy texture filtering value.
  51394. *
  51395. * @return {number} The maximum anisotropy texture filtering value.
  51396. */
  51397. getMaxAnisotropy() {
  51398. return 16;
  51399. }
  51400. /**
  51401. * Checks if the given feature is supported by the backend.
  51402. *
  51403. * @param {string} name - The feature's name.
  51404. * @return {boolean} Whether the feature is supported or not.
  51405. */
  51406. hasFeature( name ) {
  51407. return this.device.features.has( name );
  51408. }
  51409. /**
  51410. * Copies data of the given source texture to the given destination texture.
  51411. *
  51412. * @param {Texture} srcTexture - The source texture.
  51413. * @param {Texture} dstTexture - The destination texture.
  51414. * @param {?(Box3|Box2)} [srcRegion=null] - The region of the source texture to copy.
  51415. * @param {?(Vector2|Vector3)} [dstPosition=null] - The destination position of the copy.
  51416. * @param {number} [srcLevel=0] - The mipmap level to copy.
  51417. * @param {number} [dstLevel=0] - The destination mip level to copy to.
  51418. */
  51419. copyTextureToTexture( srcTexture, dstTexture, srcRegion = null, dstPosition = null, srcLevel = 0, dstLevel = 0 ) {
  51420. let dstX = 0;
  51421. let dstY = 0;
  51422. let dstZ = 0;
  51423. let srcX = 0;
  51424. let srcY = 0;
  51425. let srcZ = 0;
  51426. let srcWidth = srcTexture.image.width;
  51427. let srcHeight = srcTexture.image.height;
  51428. let srcDepth = 1;
  51429. if ( srcRegion !== null ) {
  51430. if ( srcRegion.isBox3 === true ) {
  51431. srcX = srcRegion.min.x;
  51432. srcY = srcRegion.min.y;
  51433. srcZ = srcRegion.min.z;
  51434. srcWidth = srcRegion.max.x - srcRegion.min.x;
  51435. srcHeight = srcRegion.max.y - srcRegion.min.y;
  51436. srcDepth = srcRegion.max.z - srcRegion.min.z;
  51437. } else {
  51438. // Assume it's a Box2
  51439. srcX = srcRegion.min.x;
  51440. srcY = srcRegion.min.y;
  51441. srcWidth = srcRegion.max.x - srcRegion.min.x;
  51442. srcHeight = srcRegion.max.y - srcRegion.min.y;
  51443. srcDepth = 1;
  51444. }
  51445. }
  51446. if ( dstPosition !== null ) {
  51447. dstX = dstPosition.x;
  51448. dstY = dstPosition.y;
  51449. dstZ = dstPosition.z || 0;
  51450. }
  51451. const encoder = this.device.createCommandEncoder( { label: 'copyTextureToTexture_' + srcTexture.id + '_' + dstTexture.id } );
  51452. const sourceGPU = this.get( srcTexture ).texture;
  51453. const destinationGPU = this.get( dstTexture ).texture;
  51454. encoder.copyTextureToTexture(
  51455. {
  51456. texture: sourceGPU,
  51457. mipLevel: srcLevel,
  51458. origin: { x: srcX, y: srcY, z: srcZ }
  51459. },
  51460. {
  51461. texture: destinationGPU,
  51462. mipLevel: dstLevel,
  51463. origin: { x: dstX, y: dstY, z: dstZ }
  51464. },
  51465. [
  51466. srcWidth,
  51467. srcHeight,
  51468. srcDepth
  51469. ]
  51470. );
  51471. this.device.queue.submit( [ encoder.finish() ] );
  51472. if ( dstLevel === 0 && dstTexture.generateMipmaps ) {
  51473. this.textureUtils.generateMipmaps( dstTexture );
  51474. }
  51475. }
  51476. /**
  51477. * Copies the current bound framebuffer to the given texture.
  51478. *
  51479. * @param {Texture} texture - The destination texture.
  51480. * @param {RenderContext} renderContext - The render context.
  51481. * @param {Vector4} rectangle - A four dimensional vector defining the origin and dimension of the copy.
  51482. */
  51483. copyFramebufferToTexture( texture, renderContext, rectangle ) {
  51484. const renderContextData = this.get( renderContext );
  51485. let sourceGPU = null;
  51486. if ( renderContext.renderTarget ) {
  51487. if ( texture.isDepthTexture ) {
  51488. sourceGPU = this.get( renderContext.depthTexture ).texture;
  51489. } else {
  51490. sourceGPU = this.get( renderContext.textures[ 0 ] ).texture;
  51491. }
  51492. } else {
  51493. if ( texture.isDepthTexture ) {
  51494. sourceGPU = this.textureUtils.getDepthBuffer( renderContext.depth, renderContext.stencil );
  51495. } else {
  51496. sourceGPU = this.context.getCurrentTexture();
  51497. }
  51498. }
  51499. const destinationGPU = this.get( texture ).texture;
  51500. if ( sourceGPU.format !== destinationGPU.format ) {
  51501. console.error( 'WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.', sourceGPU.format, destinationGPU.format );
  51502. return;
  51503. }
  51504. let encoder;
  51505. if ( renderContextData.currentPass ) {
  51506. renderContextData.currentPass.end();
  51507. encoder = renderContextData.encoder;
  51508. } else {
  51509. encoder = this.device.createCommandEncoder( { label: 'copyFramebufferToTexture_' + texture.id } );
  51510. }
  51511. encoder.copyTextureToTexture(
  51512. {
  51513. texture: sourceGPU,
  51514. origin: [ rectangle.x, rectangle.y, 0 ],
  51515. },
  51516. {
  51517. texture: destinationGPU
  51518. },
  51519. [
  51520. rectangle.z,
  51521. rectangle.w
  51522. ]
  51523. );
  51524. if ( renderContextData.currentPass ) {
  51525. const { descriptor } = renderContextData;
  51526. for ( let i = 0; i < descriptor.colorAttachments.length; i ++ ) {
  51527. descriptor.colorAttachments[ i ].loadOp = GPULoadOp.Load;
  51528. }
  51529. if ( renderContext.depth ) descriptor.depthStencilAttachment.depthLoadOp = GPULoadOp.Load;
  51530. if ( renderContext.stencil ) descriptor.depthStencilAttachment.stencilLoadOp = GPULoadOp.Load;
  51531. renderContextData.currentPass = encoder.beginRenderPass( descriptor );
  51532. renderContextData.currentSets = { attributes: {}, bindingGroups: [], pipeline: null, index: null };
  51533. if ( renderContext.viewport ) {
  51534. this.updateViewport( renderContext );
  51535. }
  51536. if ( renderContext.scissor ) {
  51537. const { x, y, width, height } = renderContext.scissorValue;
  51538. renderContextData.currentPass.setScissorRect( x, y, width, height );
  51539. }
  51540. } else {
  51541. this.device.queue.submit( [ encoder.finish() ] );
  51542. }
  51543. if ( texture.generateMipmaps ) {
  51544. this.textureUtils.generateMipmaps( texture );
  51545. }
  51546. }
  51547. }
  51548. /**
  51549. * A IES version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  51550. *
  51551. * @augments SpotLight
  51552. */
  51553. class IESSpotLight extends SpotLight {
  51554. /**
  51555. * Constructs a new IES spot light.
  51556. *
  51557. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  51558. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  51559. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  51560. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  51561. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  51562. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  51563. */
  51564. constructor( color, intensity, distance, angle, penumbra, decay ) {
  51565. super( color, intensity, distance, angle, penumbra, decay );
  51566. /**
  51567. * TODO
  51568. *
  51569. * @type {?Texture}
  51570. * @default null
  51571. */
  51572. this.iesMap = null;
  51573. }
  51574. copy( source, recursive ) {
  51575. super.copy( source, recursive );
  51576. this.iesMap = source.iesMap;
  51577. return this;
  51578. }
  51579. }
  51580. /**
  51581. * A projector light version of {@link SpotLight}. Can only be used with {@link WebGPURenderer}.
  51582. *
  51583. * @augments SpotLight
  51584. */
  51585. class ProjectorLight extends SpotLight {
  51586. /**
  51587. * Constructs a new projector light.
  51588. *
  51589. * @param {(number|Color|string)} [color=0xffffff] - The light's color.
  51590. * @param {number} [intensity=1] - The light's strength/intensity measured in candela (cd).
  51591. * @param {number} [distance=0] - Maximum range of the light. `0` means no limit.
  51592. * @param {number} [angle=Math.PI/3] - Maximum angle of light dispersion from its direction whose upper bound is `Math.PI/2`.
  51593. * @param {number} [penumbra=0] - Percent of the spotlight cone that is attenuated due to penumbra. Value range is `[0,1]`.
  51594. * @param {number} [decay=2] - The amount the light dims along the distance of the light.
  51595. */
  51596. constructor( color, intensity, distance, angle, penumbra, decay ) {
  51597. super( color, intensity, distance, angle, penumbra, decay );
  51598. /**
  51599. * Aspect ratio of the light. Set to `null` to use the texture aspect ratio.
  51600. *
  51601. * @type {number}
  51602. * @default null
  51603. */
  51604. this.aspect = null;
  51605. }
  51606. copy( source, recursive ) {
  51607. super.copy( source, recursive );
  51608. this.aspect = source.aspect;
  51609. return this;
  51610. }
  51611. }
  51612. /**
  51613. * This version of a node library represents a basic version
  51614. * just focusing on lights and tone mapping techniques.
  51615. *
  51616. * @private
  51617. * @augments NodeLibrary
  51618. */
  51619. class BasicNodeLibrary extends NodeLibrary {
  51620. /**
  51621. * Constructs a new basic node library.
  51622. */
  51623. constructor() {
  51624. super();
  51625. this.addLight( PointLightNode, PointLight );
  51626. this.addLight( DirectionalLightNode, DirectionalLight );
  51627. this.addLight( RectAreaLightNode, RectAreaLight );
  51628. this.addLight( SpotLightNode, SpotLight );
  51629. this.addLight( AmbientLightNode, AmbientLight );
  51630. this.addLight( HemisphereLightNode, HemisphereLight );
  51631. this.addLight( LightProbeNode, LightProbe );
  51632. this.addLight( IESSpotLightNode, IESSpotLight );
  51633. this.addLight( ProjectorLightNode, ProjectorLight );
  51634. this.addToneMapping( linearToneMapping, LinearToneMapping );
  51635. this.addToneMapping( reinhardToneMapping, ReinhardToneMapping );
  51636. this.addToneMapping( cineonToneMapping, CineonToneMapping );
  51637. this.addToneMapping( acesFilmicToneMapping, ACESFilmicToneMapping );
  51638. this.addToneMapping( agxToneMapping, AgXToneMapping );
  51639. this.addToneMapping( neutralToneMapping, NeutralToneMapping );
  51640. }
  51641. }
  51642. /**
  51643. * This alternative version of {@link WebGPURenderer} only supports node materials.
  51644. * So classes like `MeshBasicMaterial` are not compatible.
  51645. *
  51646. * @private
  51647. * @augments Renderer
  51648. */
  51649. class WebGPURenderer extends Renderer {
  51650. /**
  51651. * Constructs a new WebGPU renderer.
  51652. *
  51653. * @param {WebGPURenderer~Options} [parameters] - The configuration parameter.
  51654. */
  51655. constructor( parameters = {} ) {
  51656. let BackendClass;
  51657. if ( parameters.forceWebGL ) {
  51658. BackendClass = WebGLBackend;
  51659. } else {
  51660. BackendClass = WebGPUBackend;
  51661. parameters.getFallback = () => {
  51662. console.warn( 'THREE.WebGPURenderer: WebGPU is not available, running under WebGL2 backend.' );
  51663. return new WebGLBackend( parameters );
  51664. };
  51665. }
  51666. const backend = new BackendClass( parameters );
  51667. super( backend, parameters );
  51668. /**
  51669. * The generic default value is overwritten with the
  51670. * standard node library for type mapping. Material
  51671. * mapping is not supported with this version.
  51672. *
  51673. * @type {BasicNodeLibrary}
  51674. */
  51675. this.library = new BasicNodeLibrary();
  51676. /**
  51677. * This flag can be used for type testing.
  51678. *
  51679. * @type {boolean}
  51680. * @readonly
  51681. * @default true
  51682. */
  51683. this.isWebGPURenderer = true;
  51684. }
  51685. }
  51686. /**
  51687. * A specialized group which enables applications access to the
  51688. * Render Bundle API of WebGPU. The group with all its descendant nodes
  51689. * are considered as one render bundle and processed as such by
  51690. * the renderer.
  51691. *
  51692. * This module is only fully supported by `WebGPURenderer` with a WebGPU backend.
  51693. * With a WebGL backend, the group can technically be rendered but without
  51694. * any performance improvements.
  51695. *
  51696. * @augments Group
  51697. */
  51698. class BundleGroup extends Group {
  51699. /**
  51700. * Constructs a new bundle group.
  51701. */
  51702. constructor() {
  51703. super();
  51704. /**
  51705. * This flag can be used for type testing.
  51706. *
  51707. * @type {boolean}
  51708. * @readonly
  51709. * @default true
  51710. */
  51711. this.isBundleGroup = true;
  51712. /**
  51713. * This property is only relevant for detecting types
  51714. * during serialization/deserialization. It should always
  51715. * match the class name.
  51716. *
  51717. * @type {string}
  51718. * @readonly
  51719. * @default 'BundleGroup'
  51720. */
  51721. this.type = 'BundleGroup';
  51722. /**
  51723. * Whether the bundle is static or not. When set to `true`, the structure
  51724. * is assumed to be static and does not change. E.g. no new objects are
  51725. * added to the group
  51726. *
  51727. * If a change is required, an update can still be forced by setting the
  51728. * `needsUpdate` flag to `true`.
  51729. *
  51730. * @type {boolean}
  51731. * @default true
  51732. */
  51733. this.static = true;
  51734. /**
  51735. * The bundle group's version.
  51736. *
  51737. * @type {number}
  51738. * @readonly
  51739. * @default 0
  51740. */
  51741. this.version = 0;
  51742. }
  51743. /**
  51744. * Set this property to `true` when the bundle group has changed.
  51745. *
  51746. * @type {boolean}
  51747. * @default false
  51748. * @param {boolean} value
  51749. */
  51750. set needsUpdate( value ) {
  51751. if ( value === true ) this.version ++;
  51752. }
  51753. }
  51754. /**
  51755. * This module is responsible to manage the post processing setups in apps.
  51756. * You usually create a single instance of this class and use it to define
  51757. * the output of your post processing effect chain.
  51758. * ```js
  51759. * const postProcessing = new PostProcessing( renderer );
  51760. *
  51761. * const scenePass = pass( scene, camera );
  51762. *
  51763. * postProcessing.outputNode = scenePass;
  51764. * ```
  51765. *
  51766. * Note: This module can only be used with `WebGPURenderer`.
  51767. */
  51768. class PostProcessing {
  51769. /**
  51770. * Constructs a new post processing management module.
  51771. *
  51772. * @param {Renderer} renderer - A reference to the renderer.
  51773. * @param {Node<vec4>} outputNode - An optional output node.
  51774. */
  51775. constructor( renderer, outputNode = vec4( 0, 0, 1, 1 ) ) {
  51776. /**
  51777. * A reference to the renderer.
  51778. *
  51779. * @type {Renderer}
  51780. */
  51781. this.renderer = renderer;
  51782. /**
  51783. * A node which defines the final output of the post
  51784. * processing. This is usually the last node in a chain
  51785. * of effect nodes.
  51786. *
  51787. * @type {Node<vec4>}
  51788. */
  51789. this.outputNode = outputNode;
  51790. /**
  51791. * Whether the default output tone mapping and color
  51792. * space transformation should be enabled or not.
  51793. *
  51794. * It is enabled by default by it must be disabled when
  51795. * effects must be executed after tone mapping and color
  51796. * space conversion. A typical example is FXAA which
  51797. * requires sRGB input.
  51798. *
  51799. * When set to `false`, the app must control the output
  51800. * transformation with `RenderOutputNode`.
  51801. *
  51802. * ```js
  51803. * const outputPass = renderOutput( scenePass );
  51804. * ```
  51805. *
  51806. * @type {boolean}
  51807. */
  51808. this.outputColorTransform = true;
  51809. /**
  51810. * Must be set to `true` when the output node changes.
  51811. *
  51812. * @type {Node<vec4>}
  51813. */
  51814. this.needsUpdate = true;
  51815. const material = new NodeMaterial();
  51816. material.name = 'PostProcessing';
  51817. /**
  51818. * The full screen quad that is used to render
  51819. * the effects.
  51820. *
  51821. * @private
  51822. * @type {QuadMesh}
  51823. */
  51824. this._quadMesh = new QuadMesh( material );
  51825. }
  51826. /**
  51827. * When `PostProcessing` is used to apply post processing effects,
  51828. * the application must use this version of `render()` inside
  51829. * its animation loop (not the one from the renderer).
  51830. */
  51831. render() {
  51832. this._update();
  51833. const renderer = this.renderer;
  51834. const toneMapping = renderer.toneMapping;
  51835. const outputColorSpace = renderer.outputColorSpace;
  51836. renderer.toneMapping = NoToneMapping;
  51837. renderer.outputColorSpace = LinearSRGBColorSpace;
  51838. //
  51839. const currentXR = renderer.xr.enabled;
  51840. renderer.xr.enabled = false;
  51841. this._quadMesh.render( renderer );
  51842. renderer.xr.enabled = currentXR;
  51843. //
  51844. renderer.toneMapping = toneMapping;
  51845. renderer.outputColorSpace = outputColorSpace;
  51846. }
  51847. /**
  51848. * Frees internal resources.
  51849. */
  51850. dispose() {
  51851. this._quadMesh.material.dispose();
  51852. }
  51853. /**
  51854. * Updates the state of the module.
  51855. *
  51856. * @private
  51857. */
  51858. _update() {
  51859. if ( this.needsUpdate === true ) {
  51860. const renderer = this.renderer;
  51861. const toneMapping = renderer.toneMapping;
  51862. const outputColorSpace = renderer.outputColorSpace;
  51863. this._quadMesh.material.fragmentNode = this.outputColorTransform === true ? renderOutput( this.outputNode, toneMapping, outputColorSpace ) : this.outputNode.context( { toneMapping, outputColorSpace } );
  51864. this._quadMesh.material.needsUpdate = true;
  51865. this.needsUpdate = false;
  51866. }
  51867. }
  51868. /**
  51869. * When `PostProcessing` is used to apply post processing effects,
  51870. * the application must use this version of `renderAsync()` inside
  51871. * its animation loop (not the one from the renderer).
  51872. *
  51873. * @async
  51874. * @return {Promise} A Promise that resolves when the render has been finished.
  51875. */
  51876. async renderAsync() {
  51877. this._update();
  51878. const renderer = this.renderer;
  51879. const toneMapping = renderer.toneMapping;
  51880. const outputColorSpace = renderer.outputColorSpace;
  51881. renderer.toneMapping = NoToneMapping;
  51882. renderer.outputColorSpace = LinearSRGBColorSpace;
  51883. //
  51884. const currentXR = renderer.xr.enabled;
  51885. renderer.xr.enabled = false;
  51886. await this._quadMesh.renderAsync( renderer );
  51887. renderer.xr.enabled = currentXR;
  51888. //
  51889. renderer.toneMapping = toneMapping;
  51890. renderer.outputColorSpace = outputColorSpace;
  51891. }
  51892. }
  51893. /**
  51894. * This special type of texture is intended for compute shaders.
  51895. * It can be used to compute the data of a texture with a compute shader.
  51896. *
  51897. * Note: This type of texture can only be used with `WebGPURenderer`
  51898. * and a WebGPU backend.
  51899. *
  51900. * @augments Texture
  51901. */
  51902. class StorageTexture extends Texture {
  51903. /**
  51904. * Constructs a new storage texture.
  51905. *
  51906. * @param {number} [width=1] - The storage texture's width.
  51907. * @param {number} [height=1] - The storage texture's height.
  51908. */
  51909. constructor( width = 1, height = 1 ) {
  51910. super();
  51911. /**
  51912. * The image object which just represents the texture's dimension.
  51913. *
  51914. * @type {{width: number, height: number}}
  51915. */
  51916. this.image = { width, height };
  51917. /**
  51918. * The default `magFilter` for storage textures is `THREE.LinearFilter`.
  51919. *
  51920. * @type {number}
  51921. */
  51922. this.magFilter = LinearFilter;
  51923. /**
  51924. * The default `minFilter` for storage textures is `THREE.LinearFilter`.
  51925. *
  51926. * @type {number}
  51927. */
  51928. this.minFilter = LinearFilter;
  51929. /**
  51930. * This flag can be used for type testing.
  51931. *
  51932. * @type {boolean}
  51933. * @readonly
  51934. * @default true
  51935. */
  51936. this.isStorageTexture = true;
  51937. }
  51938. }
  51939. /**
  51940. * This special type of buffer attribute is intended for compute shaders.
  51941. * It can be used to encode draw parameters for indirect draw calls.
  51942. *
  51943. * Note: This type of buffer attribute can only be used with `WebGPURenderer`
  51944. * and a WebGPU backend.
  51945. *
  51946. * @augments StorageBufferAttribute
  51947. */
  51948. class IndirectStorageBufferAttribute extends StorageBufferAttribute {
  51949. /**
  51950. * Constructs a new storage buffer attribute.
  51951. *
  51952. * @param {number|Uint32Array} count - The item count. It is also valid to pass a `Uint32Array` as an argument.
  51953. * The subsequent parameter is then obsolete.
  51954. * @param {number} itemSize - The item size.
  51955. */
  51956. constructor( count, itemSize ) {
  51957. super( count, itemSize, Uint32Array );
  51958. /**
  51959. * This flag can be used for type testing.
  51960. *
  51961. * @type {boolean}
  51962. * @readonly
  51963. * @default true
  51964. */
  51965. this.isIndirectStorageBufferAttribute = true;
  51966. }
  51967. }
  51968. /**
  51969. * A loader for loading node objects in the three.js JSON Object/Scene format.
  51970. *
  51971. * @augments Loader
  51972. */
  51973. class NodeLoader extends Loader {
  51974. /**
  51975. * Constructs a new node loader.
  51976. *
  51977. * @param {LoadingManager} [manager] - A reference to a loading manager.
  51978. */
  51979. constructor( manager ) {
  51980. super( manager );
  51981. /**
  51982. * Represents a dictionary of textures.
  51983. *
  51984. * @type {Object<string,Texture>}
  51985. */
  51986. this.textures = {};
  51987. /**
  51988. * Represents a dictionary of node types.
  51989. *
  51990. * @type {Object<string,Node.constructor>}
  51991. */
  51992. this.nodes = {};
  51993. }
  51994. /**
  51995. * Loads the node definitions from the given URL.
  51996. *
  51997. * @param {string} url - The path/URL of the file to be loaded.
  51998. * @param {Function} onLoad - Will be called when load completes.
  51999. * @param {Function} onProgress - Will be called while load progresses.
  52000. * @param {Function} onError - Will be called when errors are thrown during the loading process.
  52001. */
  52002. load( url, onLoad, onProgress, onError ) {
  52003. const loader = new FileLoader( this.manager );
  52004. loader.setPath( this.path );
  52005. loader.setRequestHeader( this.requestHeader );
  52006. loader.setWithCredentials( this.withCredentials );
  52007. loader.load( url, ( text ) => {
  52008. try {
  52009. onLoad( this.parse( JSON.parse( text ) ) );
  52010. } catch ( e ) {
  52011. if ( onError ) {
  52012. onError( e );
  52013. } else {
  52014. console.error( e );
  52015. }
  52016. this.manager.itemError( url );
  52017. }
  52018. }, onProgress, onError );
  52019. }
  52020. /**
  52021. * Parse the node dependencies for the loaded node.
  52022. *
  52023. * @param {Array<Object>} [json] - The JSON definition
  52024. * @return {Object<string,Node>} A dictionary with node dependencies.
  52025. */
  52026. parseNodes( json ) {
  52027. const nodes = {};
  52028. if ( json !== undefined ) {
  52029. for ( const nodeJSON of json ) {
  52030. const { uuid, type } = nodeJSON;
  52031. nodes[ uuid ] = this.createNodeFromType( type );
  52032. nodes[ uuid ].uuid = uuid;
  52033. }
  52034. const meta = { nodes, textures: this.textures };
  52035. for ( const nodeJSON of json ) {
  52036. nodeJSON.meta = meta;
  52037. const node = nodes[ nodeJSON.uuid ];
  52038. node.deserialize( nodeJSON );
  52039. delete nodeJSON.meta;
  52040. }
  52041. }
  52042. return nodes;
  52043. }
  52044. /**
  52045. * Parses the node from the given JSON.
  52046. *
  52047. * @param {Object} json - The JSON definition
  52048. * @param {string} json.type - The node type.
  52049. * @param {string} json.uuid - The node UUID.
  52050. * @param {Array<Object>} [json.nodes] - The node dependencies.
  52051. * @param {Object} [json.meta] - The meta data.
  52052. * @return {Node} The parsed node.
  52053. */
  52054. parse( json ) {
  52055. const node = this.createNodeFromType( json.type );
  52056. node.uuid = json.uuid;
  52057. const nodes = this.parseNodes( json.nodes );
  52058. const meta = { nodes, textures: this.textures };
  52059. json.meta = meta;
  52060. node.deserialize( json );
  52061. delete json.meta;
  52062. return node;
  52063. }
  52064. /**
  52065. * Defines the dictionary of textures.
  52066. *
  52067. * @param {Object<string,Texture>} value - The texture library defines as `<uuid,texture>`.
  52068. * @return {NodeLoader} A reference to this loader.
  52069. */
  52070. setTextures( value ) {
  52071. this.textures = value;
  52072. return this;
  52073. }
  52074. /**
  52075. * Defines the dictionary of node types.
  52076. *
  52077. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  52078. * @return {NodeLoader} A reference to this loader.
  52079. */
  52080. setNodes( value ) {
  52081. this.nodes = value;
  52082. return this;
  52083. }
  52084. /**
  52085. * Creates a node object from the given type.
  52086. *
  52087. * @param {string} type - The node type.
  52088. * @return {Node} The created node instance.
  52089. */
  52090. createNodeFromType( type ) {
  52091. if ( this.nodes[ type ] === undefined ) {
  52092. console.error( 'THREE.NodeLoader: Node type not found:', type );
  52093. return float();
  52094. }
  52095. return nodeObject( new this.nodes[ type ]() );
  52096. }
  52097. }
  52098. /**
  52099. * A special type of material loader for loading node materials.
  52100. *
  52101. * @augments MaterialLoader
  52102. */
  52103. class NodeMaterialLoader extends MaterialLoader {
  52104. /**
  52105. * Constructs a new node material loader.
  52106. *
  52107. * @param {LoadingManager} [manager] - A reference to a loading manager.
  52108. */
  52109. constructor( manager ) {
  52110. super( manager );
  52111. /**
  52112. * Represents a dictionary of node types.
  52113. *
  52114. * @type {Object<string,Node.constructor>}
  52115. */
  52116. this.nodes = {};
  52117. /**
  52118. * Represents a dictionary of node material types.
  52119. *
  52120. * @type {Object<string,NodeMaterial.constructor>}
  52121. */
  52122. this.nodeMaterials = {};
  52123. }
  52124. /**
  52125. * Parses the node material from the given JSON.
  52126. *
  52127. * @param {Object} json - The JSON definition
  52128. * @return {NodeMaterial}. The parsed material.
  52129. */
  52130. parse( json ) {
  52131. const material = super.parse( json );
  52132. const nodes = this.nodes;
  52133. const inputNodes = json.inputNodes;
  52134. for ( const property in inputNodes ) {
  52135. const uuid = inputNodes[ property ];
  52136. material[ property ] = nodes[ uuid ];
  52137. }
  52138. return material;
  52139. }
  52140. /**
  52141. * Defines the dictionary of node types.
  52142. *
  52143. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  52144. * @return {NodeLoader} A reference to this loader.
  52145. */
  52146. setNodes( value ) {
  52147. this.nodes = value;
  52148. return this;
  52149. }
  52150. /**
  52151. * Defines the dictionary of node material types.
  52152. *
  52153. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  52154. * @return {NodeLoader} A reference to this loader.
  52155. */
  52156. setNodeMaterials( value ) {
  52157. this.nodeMaterials = value;
  52158. return this;
  52159. }
  52160. /**
  52161. * Creates a node material from the given type.
  52162. *
  52163. * @param {string} type - The node material type.
  52164. * @return {Node} The created node material instance.
  52165. */
  52166. createMaterialFromType( type ) {
  52167. const materialClass = this.nodeMaterials[ type ];
  52168. if ( materialClass !== undefined ) {
  52169. return new materialClass();
  52170. }
  52171. return super.createMaterialFromType( type );
  52172. }
  52173. }
  52174. /**
  52175. * A special type of object loader for loading 3D objects using
  52176. * node materials.
  52177. *
  52178. * @augments ObjectLoader
  52179. */
  52180. class NodeObjectLoader extends ObjectLoader {
  52181. /**
  52182. * Constructs a new node object loader.
  52183. *
  52184. * @param {LoadingManager} [manager] - A reference to a loading manager.
  52185. */
  52186. constructor( manager ) {
  52187. super( manager );
  52188. /**
  52189. * Represents a dictionary of node types.
  52190. *
  52191. * @type {Object<string,Node.constructor>}
  52192. */
  52193. this.nodes = {};
  52194. /**
  52195. * Represents a dictionary of node material types.
  52196. *
  52197. * @type {Object<string,NodeMaterial.constructor>}
  52198. */
  52199. this.nodeMaterials = {};
  52200. /**
  52201. * A reference to hold the `nodes` JSON property.
  52202. *
  52203. * @private
  52204. * @type {?Object[]}
  52205. */
  52206. this._nodesJSON = null;
  52207. }
  52208. /**
  52209. * Defines the dictionary of node types.
  52210. *
  52211. * @param {Object<string,Node.constructor>} value - The node library defined as `<classname,class>`.
  52212. * @return {NodeObjectLoader} A reference to this loader.
  52213. */
  52214. setNodes( value ) {
  52215. this.nodes = value;
  52216. return this;
  52217. }
  52218. /**
  52219. * Defines the dictionary of node material types.
  52220. *
  52221. * @param {Object<string,NodeMaterial.constructor>} value - The node material library defined as `<classname,class>`.
  52222. * @return {NodeObjectLoader} A reference to this loader.
  52223. */
  52224. setNodeMaterials( value ) {
  52225. this.nodeMaterials = value;
  52226. return this;
  52227. }
  52228. /**
  52229. * Parses the node objects from the given JSON.
  52230. *
  52231. * @param {Object} json - The JSON definition
  52232. * @param {Function} onLoad - The onLoad callback function.
  52233. * @return {Object3D}. The parsed 3D object.
  52234. */
  52235. parse( json, onLoad ) {
  52236. this._nodesJSON = json.nodes;
  52237. const data = super.parse( json, onLoad );
  52238. this._nodesJSON = null; // dispose
  52239. return data;
  52240. }
  52241. /**
  52242. * Parses the node objects from the given JSON and textures.
  52243. *
  52244. * @param {Object[]} json - The JSON definition
  52245. * @param {Object<string,Texture>} textures - The texture library.
  52246. * @return {Object<string,Node>}. The parsed nodes.
  52247. */
  52248. parseNodes( json, textures ) {
  52249. if ( json !== undefined ) {
  52250. const loader = new NodeLoader();
  52251. loader.setNodes( this.nodes );
  52252. loader.setTextures( textures );
  52253. return loader.parseNodes( json );
  52254. }
  52255. return {};
  52256. }
  52257. /**
  52258. * Parses the node objects from the given JSON and textures.
  52259. *
  52260. * @param {Object} json - The JSON definition
  52261. * @param {Object<string,Texture>} textures - The texture library.
  52262. * @return {Object<string,NodeMaterial>}. The parsed materials.
  52263. */
  52264. parseMaterials( json, textures ) {
  52265. const materials = {};
  52266. if ( json !== undefined ) {
  52267. const nodes = this.parseNodes( this._nodesJSON, textures );
  52268. const loader = new NodeMaterialLoader();
  52269. loader.setTextures( textures );
  52270. loader.setNodes( nodes );
  52271. loader.setNodeMaterials( this.nodeMaterials );
  52272. for ( let i = 0, l = json.length; i < l; i ++ ) {
  52273. const data = json[ i ];
  52274. materials[ data.uuid ] = loader.parse( data );
  52275. }
  52276. }
  52277. return materials;
  52278. }
  52279. }
  52280. /**
  52281. * In earlier three.js versions, clipping was defined globally
  52282. * on the renderer or on material level. This special version of
  52283. * `THREE.Group` allows to encode the clipping state into the scene
  52284. * graph. Meaning if you create an instance of this group, all
  52285. * descendant 3D objects will be affected by the respective clipping
  52286. * planes.
  52287. *
  52288. * Note: `ClippingGroup` can only be used with `WebGPURenderer`.
  52289. *
  52290. * @augments Group
  52291. */
  52292. class ClippingGroup extends Group {
  52293. /**
  52294. * Constructs a new clipping group.
  52295. */
  52296. constructor() {
  52297. super();
  52298. /**
  52299. * This flag can be used for type testing.
  52300. *
  52301. * @type {boolean}
  52302. * @readonly
  52303. * @default true
  52304. */
  52305. this.isClippingGroup = true;
  52306. /**
  52307. * An array with clipping planes.
  52308. *
  52309. * @type {Array<Plane>}
  52310. */
  52311. this.clippingPlanes = [];
  52312. /**
  52313. * Whether clipping should be enabled or not.
  52314. *
  52315. * @type {boolean}
  52316. * @default true
  52317. */
  52318. this.enabled = true;
  52319. /**
  52320. * Whether the intersection of the clipping planes is used to clip objects, rather than their union.
  52321. *
  52322. * @type {boolean}
  52323. * @default false
  52324. */
  52325. this.clipIntersection = false;
  52326. /**
  52327. * Whether shadows should be clipped or not.
  52328. *
  52329. * @type {boolean}
  52330. * @default false
  52331. */
  52332. this.clipShadows = false;
  52333. }
  52334. }
  52335. export { ACESFilmicToneMapping, AONode, AddEquation, AddOperation, AdditiveBlending, AgXToneMapping, AlphaFormat, AlwaysCompare, AlwaysDepth, AlwaysStencilFunc, AmbientLight, AmbientLightNode, AnalyticLightNode, ArrayCamera, ArrayElementNode, ArrayNode, AssignNode, AttributeNode, BackSide, BasicEnvironmentNode, BasicShadowMap, BatchNode, BoxGeometry, BufferAttribute, BufferAttributeNode, BufferGeometry, BufferNode, BumpMapNode, BundleGroup, BypassNode, ByteType, CacheNode, Camera, CineonToneMapping, ClampToEdgeWrapping, ClippingGroup, CodeNode, Color, ColorManagement, ColorSpaceNode, ComputeNode, ConstNode, ContextNode, ConvertNode, CubeCamera, CubeReflectionMapping, CubeRefractionMapping, CubeTexture, CubeTextureNode, CubeUVReflectionMapping, CullFaceBack, CullFaceFront, CullFaceNone, CustomBlending, CylinderGeometry, DataArrayTexture, DataTexture, DebugNode, DecrementStencilOp, DecrementWrapStencilOp, DepthFormat, DepthStencilFormat, DepthTexture, DirectionalLight, DirectionalLightNode, DoubleSide, DstAlphaFactor, DstColorFactor, DynamicDrawUsage, EnvironmentNode, EqualCompare, EqualDepth, EqualStencilFunc, EquirectUVNode, EquirectangularReflectionMapping, EquirectangularRefractionMapping, Euler, EventDispatcher, 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, MatcapUVNode, 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, SubtractEquation, SubtractiveBlending, TSL, TangentSpaceNormalMap, TempNode, Texture, Texture3DNode, TextureNode, TextureSizeNode, ToneMappingNode, ToonOutlinePassNode, TriplanarTexturesNode, UVMapping, Uint16BufferAttribute, Uint32BufferAttribute, UniformArrayNode, UniformGroupNode, UniformNode, UnsignedByteType, UnsignedInt248Type, UnsignedInt5999Type, UnsignedIntType, UnsignedShort4444Type, UnsignedShort5551Type, UnsignedShortType, UserDataNode, VSMShadowMap, VarNode, VaryingNode, Vector2, Vector3, Vector4, VertexColorNode, ViewportDepthNode, ViewportDepthTextureNode, ViewportSharedTextureNode, ViewportTextureNode, VolumeNodeMaterial, WebGLCoordinateSystem, WebGLCubeRenderTarget, WebGPUCoordinateSystem, WebGPURenderer, WebXRController, ZeroFactor, ZeroStencilOp, createCanvasElement, defaultBuildStages, defaultShaderStages, shaderStages, vectorComponents };
粤ICP备19079148号